org.apache.xpath.objects.XString

public class XString extends XObject implements XMLString
{

  /** Empty string XString object */
  public static XString EMPTYSTRING = new XString("");

  /**
   * Construct a XString object.  This constructor exists for derived classes.
   *
   * @param val String object this will wrap.
   */
  protected XString(Object val)
  {
    super(val);
  }

  /**
   * Construct a XNodeSet object.
   *
   * @param val String object this will wrap.
   */
  public XString(String val)
  {
    super(val);
  }

  /**
   * Tell that this is a CLASS_STRING.
   *
   * @return type CLASS_STRING
   */
  public int getType()
  {
    return CLASS_STRING;
  }

  /**
   * Given a request type, return the equivalent string.
   * For diagnostic purposes.
   *
   * @return type string "#STRING"
   */
  public String getTypeString()
  {
    return "#STRING";
  }

  /**
   * Tell if this object contains a java String object.
   *
   * @return true if this XMLString can return a string without creating one.
   */
  public boolean hasString()
  {
    return true;
  }

  /**
   * Cast result object to a number.
   *
   * @return 0.0 if this string is null, numeric value of this string
   * or NaN
   */
  public double num()
  {
    return toDouble();
  }

  /**
   * Convert a string to a double -- Allowed input is in fixed
   * notation ddd.fff.
   *
   * @return A double value representation of the string, or return Double.NaN
   * if the string can not be converted.
   */
  public double toDouble()
  {
    int end = length();

    if(0 == end)
      return Double.NaN;

    double result = 0.0;
    int start = 0;
    int punctPos = end-1;

    for (int i = start; i < end; i++)
    {
      char c = charAt(i);

      if (!XMLCharacterRecognizer.isWhiteSpace(c))
      {
        break;
      }
      else
        start++;
    }

    double sign = 1.0;

    if (start < end && charAt(start) == '-')
    {
      sign = -1.0;

      start++;
    }

    int digitsFound = 0;

    {
      char c = charAt(i);

      if (c != '.')
      {
        if (XMLCharacterRecognizer.isWhiteSpace(c))
          break;
        else if (Character.isDigit(c))
        {
          result = result * 10.0 + (c - 0x30);

          digitsFound++;
        }
        else
        {
          return Double.NaN;
        }
      }
      else
      {
        punctPos = i;

        break;
      }
    }

    {
      double fractPart = 0.0;

      for (int i = end - 1; i > punctPos; i--)
      {
        char c = charAt(i);

        if (XMLCharacterRecognizer.isWhiteSpace(c))
          break;
        else if (Character.isDigit(c))
        {
          fractPart = fractPart / 10.0 + (c - 0x30);

          digitsFound++;
        }
        else
        {
          return Double.NaN;
        }
      }

      result += fractPart / 10.0;
    }

    if (0 == digitsFound)
      return Double.NaN;

    return result * sign;
  }

  /**
   * Cast result object to a boolean.
   *
   * @return True if the length of this string object is greater
   * than 0.
   */
  public boolean bool()
  {
    return str().length() > 0;
  }

  /**
   * Cast result object to a string.
   *
   * @return The string this wraps or the empty string if null
   */
  public XMLString xstr()
  {
    return this;
  }

  /**
   * Cast result object to a string.
   *
   * @return The string this wraps or the empty string if null
   */
  public String str()
  {
    return (null != m_obj) ? ((String) m_obj) : "";
  }

  /**
   * Cast result object to a result tree fragment.
   *
   * @param support Xpath context to use for the conversion
   *
   * @return A document fragment with this string as a child node
   */
  public int rtf(XPathContext support)
  {

    DTM frag = support.createDocumentFragment();

    frag.appendTextChild(str());

    return frag.getDocument();
  }

  /**
   * Directly call the
   * characters method on the passed ContentHandler for the
   * string-value. Multiple calls to the
   * ContentHandler's characters methods may well occur for a single call to
   * this method.
   *
   * @param ch A non-null reference to a ContentHandler.
   *
   * @throws org.xml.sax.SAXException
   */
  public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
          throws org.xml.sax.SAXException
  {

    String str = str();

    ch.characters(str.toCharArray(), 0, str.length());
  }

  /**
   * Directly call the
   * comment method on the passed LexicalHandler for the
   * string-value.
   *
   * @param lh A non-null reference to a LexicalHandler.
   *
   * @throws org.xml.sax.SAXException
   */
  public void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh)
          throws org.xml.sax.SAXException
  {

    String str = str();

    lh.comment(str.toCharArray(), 0, str.length());
  }

  /**
   * Returns the length of this string.
   *
   * @return  the length of the sequence of characters represented by this
   *          object.
   */
  public int length()
  {
    return str().length();
  }

  /**
   * Returns the character at the specified index. An index ranges
   * from 0 to length() - 1. The first character
   * of the sequence is at index 0, the next at index
   * 1, and so on, as for array indexing.
   *
   * @param      index   the index of the character.
   * @return     the character at the specified index of this string.
   *             The first character is at index 0.
   * @exception  IndexOutOfBoundsException  if the index
   *             argument is negative or not less than the length of this
   *             string.
   */
  public char charAt(int index)
  {
    return str().charAt(index);
  }

  /**
   * Copies characters from this string into the destination character
   * array.
   *
   * @param      srcBegin   index of the first character in the string
   *                        to copy.
   * @param      srcEnd     index after the last character in the string
   *                        to copy.
   * @param      dst        the destination array.
   * @param      dstBegin   the start offset in the destination array.
   * @exception IndexOutOfBoundsException If any of the following
   *            is true:
   *

srcBegin is negative.
   *
srcBegin is greater than srcEnd
   *
srcEnd is greater than the length of this
   *                string
   *
dstBegin is negative
   *
dstBegin+(srcEnd-srcBegin) is larger than
   *                dst.length

   * @exception NullPointerException if dst is null
   */
  public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
  {
    str().getChars(srcBegin, srcEnd, dst, dstBegin);
  }

  /**
   * Tell if two objects are functionally equal.
   *
   * @param obj2 Object to compare this to
   *
   * @return true if the two objects are equal
   *
   * @throws javax.xml.transform.TransformerException
   */
  public boolean equals(XObject obj2)
  {

    int t = obj2.getType();
    try
    {
	    if (XObject.CLASS_NODESET == t)
	      return obj2.equals(this);
	    else if(XObject.CLASS_BOOLEAN == t)
	    	return obj2.bool() == bool();
	    else if(XObject.CLASS_NUMBER == t)
	    	return obj2.num() == num();
    }
    catch(javax.xml.transform.TransformerException te)
    {
    	throw new org.apache.xml.utils.WrappedRuntimeException(te);
    }

    return xstr().equals(obj2.xstr());
  }

  /**
   * Compares this string to the specified object.
   * The result is true if and only if the argument is not
   * null and is a String object that represents
   * the same sequence of characters as this object.
   *
   * @param obj2   the object to compare this String
   *                     against.
   * @return  true if the String are equal;
   *          false otherwise.
   * @see     java.lang.String#compareTo(java.lang.String)
   * @see     java.lang.String#equalsIgnoreCase(java.lang.String)
   */
  public boolean equals(XMLString obj2)
  {

    if (!obj2.hasString())
      return obj2.equals(this);
    else
      return str().equals(obj2.toString());
  }

  /**
   * Compares this string to the specified object.
   * The result is true if and only if the argument is not
   * null and is a String object that represents
   * the same sequence of characters as this object.
   *
   * @param   anObject   the object to compare this String
   *                     against.
   *
   * NEEDSDOC @param obj2
   * @return  true if the String are equal;
   *          false otherwise.
   * @see     java.lang.String#compareTo(java.lang.String)
   * @see     java.lang.String#equalsIgnoreCase(java.lang.String)
   */
  public boolean equals(Object obj2)
  {

    if (null == obj2)
      return false;

    else if (obj2 instanceof XNodeSet)
      return obj2.equals(this);
    else if(obj2 instanceof XNumber)
    	return obj2.equals(this);
    else
      return str().equals(obj2.toString());
  }

  /**
   * Compares this String to another String,
   * ignoring case considerations.  Two strings are considered equal
   * ignoring case if they are of the same length, and corresponding
   * characters in the two strings are equal ignoring case.
   *
   * @param   anotherString   the String to compare this
   *                          String against.
   * @return  true if the argument is not null
   *          and the Strings are equal,
   *          ignoring case; false otherwise.
   * @see     #equals(Object)
   * @see     java.lang.Character#toLowerCase(char)
   * @see java.lang.Character#toUpperCase(char)
   */
  public boolean equalsIgnoreCase(String anotherString)
  {
    return str().equalsIgnoreCase(anotherString);
  }

  /**
   * Compares two strings lexicographically.
   *
   * @param   anotherString   the String to be compared.
   *
   * NEEDSDOC @param xstr
   * @return  the value 0 if the argument string is equal to
   *          this string; a value less than 0 if this string
   *          is lexicographically less than the string argument; and a
   *          value greater than 0 if this string is
   *          lexicographically greater than the string argument.
   * @exception java.lang.NullPointerException if anotherString
   *          is null.
   */
  public int compareTo(XMLString xstr)
  {

    int len1 = this.length();
    int len2 = xstr.length();
    int n = Math.min(len1, len2);
    int i = 0;
    int j = 0;

    while (n-- != 0)
    {
      char c1 = this.charAt(i);
      char c2 = xstr.charAt(j);

      if (c1 != c2)
      {
        return c1 - c2;
      }

      i++;
      j++;
    }

    return len1 - len2;
  }

  /**
   * Compares two strings lexicographically, ignoring case considerations.
   * This method returns an integer whose sign is that of
   * this.toUpperCase().toLowerCase().compareTo(
   * str.toUpperCase().toLowerCase()).
   *

   * Note that this method does not take locale into account,
   * and will result in an unsatisfactory ordering for certain locales.
   * The java.text package provides collators to allow
   * locale-sensitive ordering.
   *
   * @param   str   the String to be compared.
   * @return  a negative integer, zero, or a positive integer as the
   *          the specified String is greater than, equal to, or less
   *          than this String, ignoring case considerations.
   * @see     java.text.Collator#compare(String, String)
   * @since   1.2
   */
  public int compareToIgnoreCase(XMLString str)
  {

    throw new org.apache.xml.utils.WrappedRuntimeException(
      new java.lang.NoSuchMethodException(
        "Java 1.2 method, not yet implemented"));
  }

  /**
   * Tests if this string starts with the specified prefix beginning
   * a specified index.
   *
   * @param   prefix    the prefix.
   * @param   toffset   where to begin looking in the string.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the substring of this object starting
   *          at index toffset; false otherwise.
   *          The result is false if toffset is
   *          negative or greater than the length of this
   *          String object; otherwise the result is the same
   *          as the result of the expression
   *

   *          this.subString(toffset).startsWith(prefix)
   *

   * @exception java.lang.NullPointerException if prefix is
   *          null.
   */
  public boolean startsWith(String prefix, int toffset)
  {
    return str().startsWith(prefix, toffset);
  }

  /**
   * Tests if this string starts with the specified prefix.
   *
   * @param   prefix   the prefix.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the character sequence represented by
   *          this string; false otherwise.
   *          Note also that true will be returned if the
   *          argument is an empty string or is equal to this
   *          String object as determined by the
   *          {@link #equals(Object)} method.
   * @exception java.lang.NullPointerException if prefix is
   *          null.
   */
  public boolean startsWith(String prefix)
  {
    return startsWith(prefix, 0);
  }

  /**
   * Tests if this string starts with the specified prefix beginning
   * a specified index.
   *
   * @param   prefix    the prefix.
   * @param   toffset   where to begin looking in the string.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the substring of this object starting
   *          at index toffset; false otherwise.
   *          The result is false if toffset is
   *          negative or greater than the length of this
   *          String object; otherwise the result is the same
   *          as the result of the expression
   *

   *          this.subString(toffset).startsWith(prefix)
   *

   * @exception java.lang.NullPointerException if prefix is
   *          null.
   */
  public boolean startsWith(XMLString prefix, int toffset)
  {

    int to = toffset;
    int tlim = this.length();
    int po = 0;
    int pc = prefix.length();

    if ((toffset < 0) || (toffset > tlim - pc))
    {
      return false;
    }

    while (--pc >= 0)
    {
      if (this.charAt(to) != prefix.charAt(po))
      {
        return false;
      }

      to++;
      po++;
    }

    return true;
  }

  /**
   * Tests if this string starts with the specified prefix.
   *
   * @param   prefix   the prefix.
   * @return  true if the character sequence represented by the
   *          argument is a prefix of the character sequence represented by
   *          this string; false otherwise.
   *          Note also that true will be returned if the
   *          argument is an empty string or is equal to this
   *          String object as determined by the
   *          {@link #equals(Object)} method.
   * @exception java.lang.NullPointerException if prefix is
   *          null.
   */
  public boolean startsWith(XMLString prefix)
  {
    return startsWith(prefix, 0);
  }

  /**
   * Tests if this string ends with the specified suffix.
   *
   * @param   suffix   the suffix.
   * @return  true if the character sequence represented by the
   *          argument is a suffix of the character sequence represented by
   *          this object; false otherwise. Note that the
   *          result will be true if the argument is the
   *          empty string or is equal to this String object
   *          as determined by the {@link #equals(Object)} method.
   * @exception java.lang.NullPointerException if suffix is
   *          null.
   */
  public boolean endsWith(String suffix)
  {
    return str().endsWith(suffix);
  }

  /**
   * Returns a hashcode for this string. The hashcode for a
   * String object is computed as
   *

   * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
   *

   * using int arithmetic, where s[i] is the
   * ith character of the string, n is the length of
   * the string, and ^ indicates exponentiation.
   * (The hash value of the empty string is zero.)
   *
   * @return  a hash code value for this object.
   */
  public int hashCode()
  {
    return str().hashCode();
  }

  /**
   * Returns the index within this string of the first occurrence of the
   * specified character. If a character with value ch occurs
   * in the character sequence represented by this String
   * object, then the index of the first such occurrence is returned --
   * that is, the smallest value k such that:
   *

   * this.charAt(k) == ch
   *

   * is true. If no such character occurs in this string,
   * then -1 is returned.
   *
   * @param   ch   a character.
   * @return  the index of the first occurrence of the character in the
   *          character sequence represented by this object, or
   *          -1 if the character does not occur.
   */
  public int indexOf(int ch)
  {
    return str().indexOf(ch);
  }

  /**
   * Returns the index within this string of the first occurrence of the
   * specified character, starting the search at the specified index.
   *

   * If a character with value ch occurs in the character
   * sequence represented by this String object at an index
   * no smaller than fromIndex, then the index of the first
   * such occurrence is returned--that is, the smallest value k
   * such that:
   *

   * (this.charAt(k) == ch) && (k >= fromIndex)
   *

   * is true. If no such character occurs in this string at or after
   * position fromIndex, then -1 is returned.
   *

   * There is no restriction on the value of fromIndex. If it
   * is negative, it has the same effect as if it were zero: this entire
   * string may be searched. If it is greater than the length of this
   * string, it has the same effect as if it were equal to the length of
   * this string: -1 is returned.
   *
   * @param   ch          a character.
   * @param   fromIndex   the index to start the search from.
   * @return  the index of the first occurrence of the character in the
   *          character sequence represented by this object that is greater
   *          than or equal to fromIndex, or -1
   *          if the character does not occur.
   */
  public int indexOf(int ch, int fromIndex)
  {
    return str().indexOf(ch, fromIndex);
  }

  /**
   * Returns the index within this string of the last occurrence of the
   * specified character. That is, the index returned is the largest
   * value k such that:
   *

   * this.charAt(k) == ch
   *

   * is true.
   * The String is searched backwards starting at the last character.
   *
   * @param   ch   a character.
   * @return  the index of the last occurrence of the character in the
   *          character sequence represented by this object, or
   *          -1 if the character does not occur.
   */
  public int lastIndexOf(int ch)
  {
    return str().lastIndexOf(ch);
  }

  /**
   * Returns the index within this string of the last occurrence of the
   * specified character, searching backward starting at the specified
   * index. That is, the index returned is the largest value k
   * such that:
   *

   * this.charAt(k) == ch) && (k <= fromIndex)
   *

   * is true.
   *
   * @param   ch          a character.
   * @param   fromIndex   the index to start the search from. There is no
   *          restriction on the value of fromIndex. If it is
   *          greater than or equal to the length of this string, it has
   *          the same effect as if it were equal to one less than the
   *          length of this string: this entire string may be searched.
   *          If it is negative, it has the same effect as if it were -1:
   *          -1 is returned.
   * @return  the index of the last occurrence of the character in the
   *          character sequence represented by this object that is less
   *          than or equal to fromIndex, or -1
   *          if the character does not occur before that point.
   */
  public int lastIndexOf(int ch, int fromIndex)
  {
    return str().lastIndexOf(ch, fromIndex);
  }

  /**
   * Returns the index within this string of the first occurrence of the
   * specified substring. The integer returned is the smallest value
   * k such that:
   *

   * this.startsWith(str, k)
   *

   * is true.
   *
   * @param   str   any string.
   * @return  if the string argument occurs as a substring within this
   *          object, then the index of the first character of the first
   *          such substring is returned; if it does not occur as a
   *          substring, -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public int indexOf(String str)
  {
    return str().indexOf(str);
  }

  /**
   * Returns the index within this string of the first occurrence of the
   * specified substring. The integer returned is the smallest value
   * k such that:
   *

   * this.startsWith(str, k)
   *

   * is true.
   *
   * @param   str   any string.
   * @return  if the string argument occurs as a substring within this
   *          object, then the index of the first character of the first
   *          such substring is returned; if it does not occur as a
   *          substring, -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public int indexOf(XMLString str)
  {
    return str().indexOf(str.toString());
  }

  /**
   * Returns the index within this string of the first occurrence of the
   * specified substring, starting at the specified index. The integer
   * returned is the smallest value k such that:
   *

   * this.startsWith(str, k) && (k >= fromIndex)
   *

   * is true.
   *

   * There is no restriction on the value of fromIndex. If
   * it is negative, it has the same effect as if it were zero: this entire
   * string may be searched. If it is greater than the length of this
   * string, it has the same effect as if it were equal to the length of
   * this string: -1 is returned.
   *
   * @param   str         the substring to search for.
   * @param   fromIndex   the index to start the search from.
   * @return  If the string argument occurs as a substring within this
   *          object at a starting index no smaller than
   *          fromIndex, then the index of the first character
   *          of the first such substring is returned. If it does not occur
   *          as a substring starting at fromIndex or beyond,
   *          -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null
   */
  public int indexOf(String str, int fromIndex)
  {
    return str().indexOf(str, fromIndex);
  }

  /**
   * Returns the index within this string of the rightmost occurrence
   * of the specified substring.  The rightmost empty string "" is
   * considered to occur at the index value this.length().
   * The returned index is the largest value k such that
   *

   * this.startsWith(str, k)
   *

   * is true.
   *
   * @param   str   the substring to search for.
   * @return  if the string argument occurs one or more times as a substring
   *          within this object, then the index of the first character of
   *          the last such substring is returned. If it does not occur as
   *          a substring, -1 is returned.
   * @exception java.lang.NullPointerException  if str is
   *          null.
   */
  public int lastIndexOf(String str)
  {
    return str().lastIndexOf(str);
  }

  /**
   * Returns the index within this string of the last occurrence of
   * the specified substring.
   *
   * @param   str         the substring to search for.
   * @param   fromIndex   the index to start the search from. There is no
   *          restriction on the value of fromIndex. If it is greater than
   *          the length of this string, it has the same effect as if it
   *          were equal to the length of this string: this entire string
   *          may be searched. If it is negative, it has the same effect
   *          as if it were -1: -1 is returned.
   * @return  If the string argument occurs one or more times as a substring
   *          within this object at a starting index no greater than
   *          fromIndex, then the index of the first character of
   *          the last such substring is returned. If it does not occur as a
   *          substring starting at fromIndex or earlier,
   *          -1 is returned.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public int lastIndexOf(String str, int fromIndex)
  {
    return str().lastIndexOf(str, fromIndex);
  }

  /**
   * Returns a new string that is a substring of this string. The
   * substring begins with the character at the specified index and
   * extends to the end of this string.

   * Examples:
   *

   * "unhappy".substring(2) returns "happy"
   * "Harbison".substring(3) returns "bison"
   * "emptiness".substring(9) returns "" (an empty string)
   *

   *
   * @param      beginIndex   the beginning index, inclusive.
   * @return     the specified substring.
   * @exception  IndexOutOfBoundsException  if
   *             beginIndex is negative or larger than the
   *             length of this String object.
   */
  public XMLString substring(int beginIndex)
  {
    return new XString(str().substring(beginIndex));
  }

  /**
   * Returns a new string that is a substring of this string. The
   * substring begins at the specified beginIndex and
   * extends to the character at index endIndex - 1.
   * Thus the length of the substring is endIndex-beginIndex.
   *
   * @param      beginIndex   the beginning index, inclusive.
   * @param      endIndex     the ending index, exclusive.
   * @return     the specified substring.
   * @exception  IndexOutOfBoundsException  if the
   *             beginIndex is negative, or
   *             endIndex is larger than the length of
   *             this String object, or
   *             beginIndex is larger than
   *             endIndex.
   */
  public XMLString substring(int beginIndex, int endIndex)
  {
    return new XString(str().substring(beginIndex, endIndex));
  }

  /**
   * Concatenates the specified string to the end of this string.
   *
   * @param   str   the String that is concatenated to the end
   *                of this String.
   * @return  a string that represents the concatenation of this object's
   *          characters followed by the string argument's characters.
   * @exception java.lang.NullPointerException if str is
   *          null.
   */
  public XMLString concat(String str)
  {

    return new XString(str().concat(str));
  }

  /**
   * Converts all of the characters in this String to lower
   * case using the rules of the given Locale.
   *
   * @param locale use the case transformation rules for this locale
   * @return the String, converted to lowercase.
   * @see     java.lang.Character#toLowerCase(char)
   * @see     java.lang.String#toUpperCase(Locale)
   */
  public XMLString toLowerCase(Locale locale)
  {
    return new XString(str().toLowerCase(locale));
  }

  /**
   * Converts all of the characters in this String to lower
   * case using the rules of the default locale, which is returned
   * by Locale.getDefault.
   *

   *
   * @return  the string, converted to lowercase.
   * @see     java.lang.Character#toLowerCase(char)
   * @see     java.lang.String#toLowerCase(Locale)
   */
  public XMLString toLowerCase()
  {
    return new XString(str().toLowerCase());
  }

  /**
   * Converts all of the characters in this String to upper
   * case using the rules of the given locale.
   * @param locale use the case transformation rules for this locale
   * @return the String, converted to uppercase.
   * @see     java.lang.Character#toUpperCase(char)
   * @see     java.lang.String#toLowerCase(Locale)
   */
  public XMLString toUpperCase(Locale locale)
  {
    return new XString(str().toUpperCase(locale));
  }

  /**
   * Converts all of the characters in this String to upper
   * case using the rules of the default locale, which is returned
   * by Locale.getDefault.
   *
   *

   * If no character in this string has a different uppercase version,
   * based on calling the toUpperCase method defined by
   * Character, then the original string is returned.
   *

   * Otherwise, this method creates a new String object
   * representing a character sequence identical in length to the
   * character sequence represented by this String object and
   * with every character equal to the result of applying the method
   * Character.toUpperCase to the corresponding character of
   * this String object.

   * Examples:
   *

   * "Fahrvergnügen".toUpperCase() returns "FAHRVERGNÜGEN"
   * "Visit Ljubinje!".toUpperCase() returns "VISIT LJUBINJE!"
   *

   *
   * @return  the string, converted to uppercase.
   * @see     java.lang.Character#toUpperCase(char)
   * @see     java.lang.String#toUpperCase(Locale)
   */
  public XMLString toUpperCase()
  {
    return new XString(str().toUpperCase());
  }

  /**
   * Removes white space from both ends of this string.
   *
   * @return  this string, with white space removed from the front and end.
   */
  public XMLString trim()
  {
    return new XString(str().trim());
  }

  /**
   * Returns whether the specified <var>ch</var> conforms to the XML 1.0 definition
   * the definition of S for details.
   * @param   ch      Character to check as XML whitespace.
   * @return          =true if <var>ch</var> is XML whitespace; otherwise =false.
   */
  private static boolean isSpace(char ch)
  {
  }

  /**
   * Conditionally trim all leading and trailing whitespace in the specified String.
   * All strings of white space are
   * replaced by a single space character (#x20), except spaces after punctuation which
   * receive double spaces if doublePunctuationSpaces is true.
   * This function may be useful to a formatter, but to get first class
   * results, the formatter should probably do it's own white space handling
   * based on the semantics of the formatting object.
   *
   * @param   trimHead    Trim leading whitespace?
   * @param   trimTail    Trim trailing whitespace?
   * @param   doublePunctuationSpaces    Use double spaces for punctuation?
   * @return              The trimmed string.
   */
  public XMLString fixWhiteSpace(boolean trimHead, boolean trimTail,
                                 boolean doublePunctuationSpaces)
  {

    int len = this.length();
    char[] buf = new char[len];

    this.getChars(0, len, buf, 0);

    boolean edit = false;
    int s;

    for (s = 0; s < len; s++)
    {
      if (isSpace(buf[s]))
      {
        break;
      }
    }

    /* replace S to ' '. and ' '+ -> single ' '. */
    int d = s;
    boolean pres = false;

    for (; s < len; s++)
    {
      char c = buf[s];

      if (isSpace(c))
      {
        if (!pres)
        {
          if (' ' != c)
          {
            edit = true;
          }

          buf[d++] = ' ';

          if (doublePunctuationSpaces && (s != 0))
          {
            char prevChar = buf[s - 1];

            if (!((prevChar == '.') || (prevChar == '!')
                  || (prevChar == '?')))
            {
              pres = true;
            }
          }
          else
          {
            pres = true;
          }
        }
        else
        {
          edit = true;
          pres = true;
        }
      }
      else
      {
        buf[d++] = c;
        pres = false;
      }
    }

    if (trimTail && 1 <= d && ' ' == buf[d - 1])
    {
      edit = true;

      d--;
    }

    int start = 0;

    if (trimHead && 0 < d && ' ' == buf[0])
    {
      edit = true;

      start++;
    }

    XMLStringFactory xsf = XMLStringFactoryImpl.getFactory();

    return edit ? xsf.newstr(new String(buf, start, d - start)) : this;
  }

  /**
   * @see XPathVisitable#callVisitors(ExpressionOwner, XPathVisitor)
   */
  public void callVisitors(ExpressionOwner owner, XPathVisitor visitor)
  {
  	visitor.visitStringLiteral(owner, this);

  public XMLString xstr()
  {
    return this;

FUNC_DECL RETURN VAR_DECL PARAM CALL CALL CALL CALL

FUNC_DECL PARAM PARAM PARAM PARAM CALL CALL

FUNC_DECL RETURN TRY VAR_DECL PARAM CALL CATCH IF CALL THROW_RAISE IF RETURN BINARY_OP CALL CALL CALL IF RETURN BINARY_OP CALL RETURN BINARY_OP BINARY_OP BINARY_OP CALL CALL CALL CALL

FUNC_DECL IF PARAM RETURN RETURN CALL CALL CALL CALL CALL

FUNC_DECL IF PARAM IF RETURN BINARY_OP IF RETURN BINARY_OP LITERAL_ANCHOR LITERAL_ANCHOR RETURN RETURN BINARY_OP CALL CALL CALL CALL CALL

FUNC_DECL RETURN PARAM PARAM CALL CALL CALL


org.apache.poi.hssf.record.DBCellRecord

public class DBCellRecord
    extends Record
{
    public final static int BLOCK_SIZE = 32;
    public final static short sid = 0xd7;
    private int               field_1_row_offset;
    private short[]           field_2_cell_offsets;

    public DBCellRecord()
    {
    }

    /**
     * Constructs a DBCellRecord and sets its fields appropriately
     *
     * @param id     id must be 0xd7 or an exception will be throw upon validation
     * @param size  the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     */

    public DBCellRecord(RecordInputStream in)
    {
        super(in);
    }

    protected void validateSid(short id)
    {
        if (id != sid)
        {
            throw new RecordFormatException("NOT A valid DBCell RECORD");
        }
    }

    protected void fillFields(RecordInputStream in)
    {
        field_1_row_offset   = in.readUShort();
        int size = in.remaining();
        field_2_cell_offsets = new short[ size / 2 ];

        for (int i=0;i<field_2_cell_offsets.length;i++)
        {
            field_2_cell_offsets[ i ] = in.readShort();
        }
    }

    /**
     * sets offset from the start of this DBCellRecord to the start of the first cell in
     * the next DBCell block.
     *
     * @param offset    offset to the start of the first cell in the next DBCell block
     */

    public void setRowOffset(int offset)
    {
        field_1_row_offset = offset;
    }

    public void addCellOffset(short offset)
    {
        if (field_2_cell_offsets == null)
        {
            field_2_cell_offsets = new short[ 1 ];
        }
        else
        {
            short[] temp = new short[ field_2_cell_offsets.length + 1 ];

            System.arraycopy(field_2_cell_offsets, 0, temp, 0,
                             field_2_cell_offsets.length);
            field_2_cell_offsets = temp;
        }
        field_2_cell_offsets[ field_2_cell_offsets.length - 1 ] = offset;
    }

    /**
     * gets offset from the start of this DBCellRecord to the start of the first cell in
     * the next DBCell block.
     *
     * @return rowoffset to the start of the first cell in the next DBCell block
     */

    public int getRowOffset()
    {
        return field_1_row_offset;
    }

    /**
     * return the cell offset in the array
     *
     * @param index of the cell offset to retrieve
     * @return celloffset from the celloffset array
     */

    public short getCellOffsetAt(int index)
    {
        return field_2_cell_offsets[ index ];
    }

    /**
     * get the number of cell offsets in the celloffset array
     *
     * @return number of cell offsets
     */

    public int getNumCellOffsets()
    {
        return field_2_cell_offsets.length;
    }

    public String toString()
    {
        StringBuffer buffer = new StringBuffer();

        buffer.append("[DBCELL]\n");
        buffer.append("    .rowoffset       = ")
            .append(Integer.toHexString(getRowOffset())).append("\n");
        for (int k = 0; k < getNumCellOffsets(); k++)
        {
            buffer.append("    .cell_" + k + "          = ")
                .append(Integer.toHexString(getCellOffsetAt(k))).append("\n");
        }
        buffer.append("[/DBCELL]\n");
        return buffer.toString();
    }

    public int serialize(int offset, byte [] data)
    {
        if (field_2_cell_offsets == null)
        {
            field_2_cell_offsets = new short[ 0 ];
        }
        LittleEndian.putShort(data, 0 + offset, sid);
        LittleEndian.putShort(data, 2 + offset,
                              (( short ) (4 + (getNumCellOffsets() * 2))));
        LittleEndian.putInt(data, 4 + offset, getRowOffset());
        for (int k = 0; k < getNumCellOffsets(); k++)
        {
            LittleEndian.putShort(data, 8 + 2*k + offset, getCellOffsetAt(k));
        }
        return getRecordSize();
    }

    public int getRecordSize()
    {
        return 8 + (getNumCellOffsets() * 2);
    }

    /** Returns the size of a DBCellRecord when it needs to reference a certain number of rows*/
    public static int getRecordSizeForRows(int rows) {
      return 8 + (rows * 2);
    }

    public short getSid()
    {
        return sid;
    }

    public boolean isInValueSection()
    {
        return true;

    public short getSid()
    {
        return sid;


public class LogOutputStream extends LineOrientedOutputStream {

    private ProjectComponent pc;
    private int level = Project.MSG_INFO;

    /**
     * Create a new LogOutputStream for the specified ProjectComponent.
     *
     * @param pc the project component for whom to log
     * @since Ant 1.7.1
     */
    public LogOutputStream(ProjectComponent pc) {
        this.pc = pc;
    }

    /**
     * Creates a new instance of this class.
     *
     * @param task the task for whom to log
     * @param level loglevel used to log data written to this stream.
     */
    public LogOutputStream(Task task, int level) {
        this((ProjectComponent) task, level);
    }

    /**
     * Creates a new instance of this class.
     *
     * @param pc the project component for whom to log
     * @param level loglevel used to log data written to this stream.
     * @since Ant 1.6.3
     */
    public LogOutputStream(ProjectComponent pc, int level) {
        this(pc);
        this.level = level;
    }

    /**
     * Converts the buffer to a string and sends it to processLine
     */
    protected void processBuffer() {
        try {
            super.processBuffer();
        } catch (IOException e) {
            throw new RuntimeException("Impossible IOException caught: " + e);
        }
    }

    /**
     * Logs a line to the log system of ant.
     *
     * @param line the line to log.
     */
    protected void processLine(String line) {
        processLine(line, level);
    }

    /**
     * Logs a line to the log system of ant.
     *
     * @param line the line to log.
     * @param level the logging level to use.
     */
    protected void processLine(String line, int level) {
        pc.log(line, level);
    }

    /**
     * Get the level.
     * @return the log level.
     */
    public int getMessageLevel() {
        return level;


public class PlainJUnitResultFormatter implements JUnitResultFormatter {

    private static final double ONE_SECOND = 1000.0;

    /**
     * Formatter for timings.
     */
    private NumberFormat nf = NumberFormat.getInstance();
    /**
     * Timing helper.
     */
    private Hashtable testStarts = new Hashtable();
    /**
     * Where to write the log to.
     */
    private OutputStream out;
    /**
     * Helper to store intermediate output.
     */
    private StringWriter inner;
    /**
     * Convenience layer on top of {@link #inner inner}.
     */
    private PrintWriter wri;
    /**
     * Suppress endTest if testcase failed.
     */
    private Hashtable failed = new Hashtable();

    private String systemOutput = null;
    private String systemError = null;

    /** No arg constructor */
    public PlainJUnitResultFormatter() {
        inner = new StringWriter();
        wri = new PrintWriter(inner);
    }

    /** {@inheritDoc}. */
    public void setOutput(OutputStream out) {
        this.out = out;
    }

    /** {@inheritDoc}. */
    public void setSystemOutput(String out) {
        systemOutput = out;
    }

    /** {@inheritDoc}. */
    public void setSystemError(String err) {
        systemError = err;
    }

    /**
     * The whole testsuite started.
     * @param suite the test suite
     * @throws BuildException if unable to write the output
     */
    public void startTestSuite(JUnitTest suite) throws BuildException {
        if (out == null) {
        }
        StringBuffer sb = new StringBuffer("Testsuite: ");
        sb.append(suite.getName());
        sb.append(StringUtils.LINE_SEP);
        try {
            out.write(sb.toString().getBytes());
            out.flush();
        } catch (IOException ex) {
            throw new BuildException("Unable to write output", ex);
        }
    }

    /**
     * The whole testsuite ended.
     * @param suite the test suite
     * @throws BuildException if unable to write the output
     */
    public void endTestSuite(JUnitTest suite) throws BuildException {
        StringBuffer sb = new StringBuffer("Tests run: ");
        sb.append(suite.runCount());
        sb.append(", Failures: ");
        sb.append(suite.failureCount());
        sb.append(", Errors: ");
        sb.append(suite.errorCount());
        sb.append(", Time elapsed: ");
        sb.append(nf.format(suite.getRunTime() / ONE_SECOND));
        sb.append(" sec");
        sb.append(StringUtils.LINE_SEP);

        if (systemOutput != null && systemOutput.length() > 0) {
            sb.append("------------- Standard Output ---------------")
                .append(StringUtils.LINE_SEP)
                .append(systemOutput)
                .append("------------- ---------------- ---------------")
                .append(StringUtils.LINE_SEP);
        }

        if (systemError != null && systemError.length() > 0) {
            sb.append("------------- Standard Error -----------------")
                .append(StringUtils.LINE_SEP)
                .append(systemError)
                .append("------------- ---------------- ---------------")
                .append(StringUtils.LINE_SEP);
        }

        sb.append(StringUtils.LINE_SEP);

        if (out != null) {
            try {
                out.write(sb.toString().getBytes());
                wri.close();
                out.write(inner.toString().getBytes());
                out.flush();
            } catch (IOException ioex) {
                throw new BuildException("Unable to write output", ioex);
            } finally {
                if (out != System.out && out != System.err) {
                    FileUtils.close(out);
                }
            }
        }
    }

    /**
     * Interface TestListener.
     *
     *
A new Test is started.
     * @param t the test.
     */
    public void startTest(Test t) {
        testStarts.put(t, new Long(System.currentTimeMillis()));
        failed.put(t, Boolean.FALSE);
    }

    /**
     * Interface TestListener.
     *
     *
A Test is finished.
     * @param test the test.
     */
    public void endTest(Test test) {
        if (Boolean.TRUE.equals(failed.get(test))) {
            return;
        }
        synchronized (wri) {
            wri.print("Testcase: "
                      + JUnitVersionHelper.getTestCaseName(test));
            Long l = (Long) testStarts.get(test);
            double seconds = 0;
            if (l != null) {
                seconds =
                    (System.currentTimeMillis() - l.longValue()) / ONE_SECOND;
            }

            wri.println(" took " + nf.format(seconds) + " sec");
        }
    }

    /**
     * Interface TestListener for JUnit <= 3.4.
     *
     *
A Test failed.
     * @param test the test.
     * @param t the exception.
     */
    public void addFailure(Test test, Throwable t) {
        formatError("\tFAILED", test, t);
    }

    /**
     * Interface TestListener for JUnit > 3.4.
     *
     *
A Test failed.
     * @param test the test.
     * @param t  the assertion that failed.
     */
    public void addFailure(Test test, AssertionFailedError t) {
        addFailure(test, (Throwable) t);
    }

    /**
     * Interface TestListener.
     *
     *
An error occurred while running the test.
     * @param test the test.
     * @param t    the exception.
     */
    public void addError(Test test, Throwable t) {
        formatError("\tCaused an ERROR", test, t);
    }

    private void formatError(String type, Test test, Throwable t) {
        synchronized (wri) {
            if (test != null) {
                endTest(test);
                failed.put(test, Boolean.TRUE);
            }

            wri.println(type);
            wri.println(t.getMessage());
            String strace = JUnitTestRunner.getFilteredTrace(t);
            wri.print(strace);
            wri.println("");

FUNC_DECL PARAM PARAM PARAM VAR_DECL IF CALL CALL CALL CALL BINARY_OP LITERAL_ANCHOR CALL CALL LITERAL_ANCHOR CALL CALL


org.apache.camel.spring.util.MethodInfo

public class MethodInfo {
    private Class type;
    private Method method;
    private Expression parametersExpression;

    public MethodInfo(Class type, Method method, Expression parametersExpression) {
        this.type = type;
        this.method = method;
        this.parametersExpression = parametersExpression;
    }

    public MethodInvocation createMethodInvocation(final Object pojo, final Exchange messageExchange) {
        final Object[] arguments = (Object[]) parametersExpression.evaluate(messageExchange);
        return new MethodInvocation() {
            public Method getMethod() {
                return method;
            }

            public Object[] getArguments() {
                return arguments;
            }

            public Object proceed() throws Throwable {
                return invoke(method, pojo, arguments, messageExchange);
            }

            public Object getThis() {
                return pojo;
            }

            public AccessibleObject getStaticPart() {
                return method;
            }
        };
    }

    public Class getType() {
        return type;
    }

    public Method getMethod() {
        return method;
    }

    public Expression getParametersExpression() {
        return parametersExpression;
    }

    protected Object invoke(Method mth, Object pojo, Object[] arguments, Exchange exchange) throws IllegalAccessException, InvocationTargetException {
        return mth.invoke(pojo, arguments);

    public Class getType() {
        return type;

FUNC_DECL RETURN PARAM PARAM PARAM PARAM CALL

FUNC_DECL PARAM PARAM PARAM ASSIGN ASSIGN ASSIGN


public class AreaFormatRecord
    extends Record
{
    public final static short      sid                             = 0x100a;
    private  int        field_1_foregroundColor;
    private  int        field_2_backgroundColor;
    private  short      field_3_pattern;
    private  short      field_4_formatFlags;
    private BitField   automatic                                  = new BitField(0x1);
    private BitField   invert                                     = new BitField(0x2);
    private  short      field_5_forecolorIndex;
    private  short      field_6_backcolorIndex;

    public AreaFormatRecord()
    {

    }

    /**
     * Constructs a AreaFormat record and sets its fields appropriately.
     *
     * @param id    id must be 0x100a or an exception
     *              will be throw upon validation
     * @param size  size the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     */

    public AreaFormatRecord(short id, short size, byte [] data)
    {
        super(id, size, data);
    }

    /**
     * Constructs a AreaFormat record and sets its fields appropriately.
     *
     * @param id    id must be 0x100a or an exception
     *              will be throw upon validation
     * @param size  size the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     * @param offset of the record's data
     */

    public AreaFormatRecord(short id, short size, byte [] data, int offset)
    {
        super(id, size, data, offset);
    }

    /**
     * Checks the sid matches the expected side for this record
     *
     * @param id   the expected sid.
     */
    protected void validateSid(short id)
    {
        if (id != sid)
        {
            throw new RecordFormatException("Not a AreaFormat record");
        }
    }

    protected void fillFields(byte [] data, short size, int offset)
    {
        field_1_foregroundColor         = LittleEndian.getInt(data, 0x0 + offset);
        field_2_backgroundColor         = LittleEndian.getInt(data, 0x4 + offset);
        field_3_pattern                 = LittleEndian.getShort(data, 0x8 + offset);
        field_4_formatFlags             = LittleEndian.getShort(data, 0xa + offset);
        field_5_forecolorIndex          = LittleEndian.getShort(data, 0xc + offset);
        field_6_backcolorIndex          = LittleEndian.getShort(data, 0xe + offset);

    }

    public String toString()
    {
        StringBuffer buffer = new StringBuffer();

        buffer.append("[AreaFormat]\n");

        buffer.append("    .foregroundColor      = ")
            .append("0x")
            .append(HexDump.toHex((int)getForegroundColor()))
            .append(" (").append(getForegroundColor()).append(" )\n");

        buffer.append("    .backgroundColor      = ")
            .append("0x")
            .append(HexDump.toHex((int)getBackgroundColor()))
            .append(" (").append(getBackgroundColor()).append(" )\n");

        buffer.append("    .pattern              = ")
            .append("0x")
            .append(HexDump.toHex((short)getPattern()))
            .append(" (").append(getPattern()).append(" )\n");

        buffer.append("    .formatFlags          = ")
            .append("0x")
            .append(HexDump.toHex((short)getFormatFlags()))
            .append(" (").append(getFormatFlags()).append(" )\n");
        buffer.append("         .automatic                = ").append(isAutomatic           ()).append('\n');
        buffer.append("         .invert                   = ").append(isInvert              ()).append('\n');

        buffer.append("    .forecolorIndex       = ")
            .append("0x")
            .append(HexDump.toHex((short)getForecolorIndex()))
            .append(" (").append(getForecolorIndex()).append(" )\n");

        buffer.append("    .backcolorIndex       = ")
            .append("0x")
            .append(HexDump.toHex((short)getBackcolorIndex()))
            .append(" (").append(getBackcolorIndex()).append(" )\n");

        buffer.append("[/AreaFormat]\n");
        return buffer.toString();
    }

    public int serialize(int offset, byte[] data)
    {
        LittleEndian.putShort(data, 0 + offset, sid);
        LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4));

        LittleEndian.putInt(data, 4 + offset, field_1_foregroundColor);
        LittleEndian.putInt(data, 8 + offset, field_2_backgroundColor);
        LittleEndian.putShort(data, 12 + offset, field_3_pattern);
        LittleEndian.putShort(data, 14 + offset, field_4_formatFlags);
        LittleEndian.putShort(data, 16 + offset, field_5_forecolorIndex);
        LittleEndian.putShort(data, 18 + offset, field_6_backcolorIndex);

        return getRecordSize();
    }

    /**
     * Size of record (exluding 4 byte header)
     */
    public int getRecordSize()
    {
        return 4 + 4 + 4 + 2 + 2 + 2 + 2;
    }

    public short getSid()
    {
        return this.sid;
    }

    /**
     * Get the foreground color field for the AreaFormat record.
     */
    public int getForegroundColor()
    {
        return field_1_foregroundColor;
    }

    /**
     * Set the foreground color field for the AreaFormat record.
     */
    public void setForegroundColor(int field_1_foregroundColor)
    {
        this.field_1_foregroundColor = field_1_foregroundColor;
    }

    /**
     * Get the background color field for the AreaFormat record.
     */
    public int getBackgroundColor()
    {
        return field_2_backgroundColor;
    }

    /**
     * Set the background color field for the AreaFormat record.
     */
    public void setBackgroundColor(int field_2_backgroundColor)
    {
        this.field_2_backgroundColor = field_2_backgroundColor;
    }

    /**
     * Get the pattern field for the AreaFormat record.
     */
    public short getPattern()
    {
        return field_3_pattern;
    }

    /**
     * Set the pattern field for the AreaFormat record.
     */
    public void setPattern(short field_3_pattern)
    {
        this.field_3_pattern = field_3_pattern;
    }

    /**
     * Get the format flags field for the AreaFormat record.
     */
    public short getFormatFlags()
    {
        return field_4_formatFlags;
    }

    /**
     * Set the format flags field for the AreaFormat record.
     */
    public void setFormatFlags(short field_4_formatFlags)
    {
        this.field_4_formatFlags = field_4_formatFlags;
    }

    /**
     * Get the forecolor index field for the AreaFormat record.
     */
    public short getForecolorIndex()
    {
        return field_5_forecolorIndex;
    }

    /**
     * Set the forecolor index field for the AreaFormat record.
     */
    public void setForecolorIndex(short field_5_forecolorIndex)
    {
        this.field_5_forecolorIndex = field_5_forecolorIndex;
    }

    /**
     * Get the backcolor index field for the AreaFormat record.
     */
    public short getBackcolorIndex()
    {
        return field_6_backcolorIndex;
    }

    /**
     * Set the backcolor index field for the AreaFormat record.
     */
    public void setBackcolorIndex(short field_6_backcolorIndex)
    {
        this.field_6_backcolorIndex = field_6_backcolorIndex;
    }

    /**
     * Sets the automatic field value.
     * automatic formatting
     */
    public void setAutomatic(boolean value)
    {
        field_4_formatFlags = automatic.setShortBoolean(field_4_formatFlags, value);
    }

    /**
     * automatic formatting
     * @return  the automatic field value.
     */
    public boolean isAutomatic()
    {
        return automatic.isSet(field_4_formatFlags);
    }

    /**
     * Sets the invert field value.
     * swap foreground and background colours when data is negative
     */
    public void setInvert(boolean value)
    {
        field_4_formatFlags = invert.setShortBoolean(field_4_formatFlags, value);
    }

    /**
     * swap foreground and background colours when data is negative
     * @return  the invert field value.
     */
    public boolean isInvert()
    {
        return invert.isSet(field_4_formatFlags);

FUNC_DECL RETURN VAR_DECL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL LITERAL_ANCHOR CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL


org.apache.camel.view.XmlGraphGenerator

public class XmlGraphGenerator extends GraphGeneratorSupport {
    private boolean addUrl = true;

    public XmlGraphGenerator(String dir) {
        super(dir, ".xml");
    }

    protected void generateFile(PrintWriter writer, Map<String, List<RouteType>> map) {
        writer.println("<?xml version='1.0' encoding='UTF-8'?>");
        writer.println("<Graph>");
        writer.println();

        if (map.size() > 0) {
            writer.println("<Node id='root' name='Camel Routes' description='Collection of Camel Routes' nodeType='root'/>");
        }
        printRoutes(writer, map);

        writer.println();
        writer.println("</Graph>");
    }

    protected void printRoutes(PrintWriter writer, Map<String, List<RouteType>> map) {
        Set<Map.Entry<String, List<RouteType>>> entries = map.entrySet();
        for (Map.Entry<String, List<RouteType>> entry : entries) {
            String group = entry.getKey();
            printRoutes(writer, group, entry.getValue());
        }
    }

    protected void printRoutes(PrintWriter writer, String group, List<RouteType> routes) {
        group = encode(group);
        if (group != null) {
            int idx = group.lastIndexOf('.');
            String name = group;
            if (idx > 0 && idx < group.length() - 1) {
                name = group.substring(idx + 1);
            }
            writer.println("<Node id='" + group + "' name='" + name + "' description='" + group + "' nodeType='group'/>");
            writer.println("<Edge fromID='root' toID='" + group + "'/>");
        }
        for (RouteType route : routes) {
            List<FromType> inputs = route.getInputs();
            boolean first = true;
            for (FromType input : inputs) {
                NodeData nodeData = getNodeData(input);
                if (first) {
                    first = false;
                    if (group != null) {
                        writer.println("<Edge fromID='" + group + "' toID='" + encode(nodeData.id) + "'/>");
                    }
                }
                printRoute(writer, route, nodeData);
            }
            writer.println();
        }
    }

    protected void printRoute(PrintWriter writer, final RouteType route, NodeData nodeData) {
        printNode(writer, nodeData);

        NodeData from = nodeData;
        for (ProcessorType output : route.getOutputs()) {
            NodeData newData = printNode(writer, from, output);
            from = newData;
        }
    }

    protected NodeData printNode(PrintWriter writer, NodeData fromData, ProcessorType node) {
        if (node instanceof MulticastType) {
            List<ProcessorType> outputs = node.getOutputs();
            for (ProcessorType output : outputs) {
                printNode(writer, fromData, output);
            }
            return fromData;
        }
        NodeData toData = getNodeData(node);

        printNode(writer, toData);

        if (fromData != null) {
            writer.print("<Edge fromID=\"");
            writer.print(encode(fromData.id));
            writer.print("\" toID=\"");
            writer.print(encode(toData.id));
            String association = toData.edgeLabel;
            if (isNullOrBlank(association)) {
                writer.print("\" association=\"");
                writer.print(encode(association));
            }
            writer.println("\"/>");
        }

        List<ProcessorType> outputs = toData.outputs;
        if (outputs != null) {
            for (ProcessorType output : outputs) {
                NodeData newData = printNode(writer, toData, output);
                if (!isMulticastNode(node)) {
                    toData = newData;
                }
            }
        }
        return toData;
    }

    protected void printNode(PrintWriter writer, NodeData data) {
        if (!data.nodeWritten) {
            data.nodeWritten = true;

            writer.println();
            writer.print("<Node id=\"");
            writer.print(encode(data.id));
            writer.print("\" name=\"");
            String name = data.label;
            if (isNullOrBlank(name)) {
                name = data.tooltop;
            }
            writer.print(encode(name));
            writer.print("\" nodeType=\"");
            String nodeType = data.image;
            if (isNullOrBlank(nodeType)) {
                nodeType = data.shape;
                if (isNullOrBlank(nodeType)) {
                    nodeType = "node";
                }
            }
            writer.print(encode(nodeType));
            writer.print("\" description=\"");
            writer.print(encode(data.tooltop));
            if (addUrl) {
                writer.print("\" url=\"");
                writer.print(encode(data.url));
            }
            writer.println("\"/>");
        }
    }

    protected String encode(String text) {
        if (text == null) {
            return "";
        }
        return text.replaceAll("\"", """).replaceAll("<", "<").
                replaceAll(">", ">").replaceAll("&", "&");

FUNC_DECL LOOP VAR_DECL PARAM PARAM VAR_DECL CALL CALL CALL CALL

FUNC_DECL LOOP VAR_DECL PARAM PARAM PARAM CALL VAR_DECL CALL ASSIGN CALL

FUNC_DECL RETURN IF VAR_DECL IF VAR_DECL IF PARAM PARAM PARAM BINARY_OP BINARY_OP CALL BINARY_OP LOOP LITERAL_ANCHOR IF VAR_DECL LITERAL_ANCHOR CALL RETURN LOOP VAR_DECL CALL CALL CALL CALL CALL CALL IF VAR_DECL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR ASSIGN

FUNC_DECL IF PARAM PARAM IF IF VAR_DECL IF VAR_DECL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL ASSIGN LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL IF LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL CALL ASSIGN ASSIGN CALL LITERAL_ANCHOR ASSIGN LITERAL_ANCHOR


public class MemAreaPtg
    extends Ptg
{
    public final static short sid  = 0x26;
    private final static int  SIZE = 7;
    private int               field_1_reserved;
    private short             field_2_subex_len;

    /** Creates new MemAreaPtg */

    public MemAreaPtg()
    {
    }

    public MemAreaPtg(RecordInputStream in)
    {
        field_1_reserved  = in.readInt();
        field_2_subex_len = in.readShort();
    }

    public void setReserved(int res)
    {
        field_1_reserved = res;
    }

    public int getReserved()
    {
        return field_1_reserved;
    }

    public void setSubexpressionLength(short subexlen)
    {
        field_2_subex_len = subexlen;
    }

    public short getSubexpressionLength()
    {
        return field_2_subex_len;
    }

    public void writeBytes(byte [] array, int offset)
    {
        array[offset] = (byte) (sid + ptgClass);
        LittleEndian.putInt(array, offset + 1, field_1_reserved);
        LittleEndian.putShort(array, offset + 5, field_2_subex_len);
    }

    public int getSize()
    {
        return SIZE;
    }

    public String toFormulaString(Workbook book)
    {
    }

    public byte getDefaultOperandClass() {return Ptg.CLASS_VALUE;}

    public Object clone() {
      MemAreaPtg ptg = new MemAreaPtg();
      ptg.field_1_reserved = field_1_reserved;
      ptg.field_2_subex_len = field_2_subex_len;
      return ptg;

    public int getSize()
    {
        return SIZE;

FUNC_DECL RETURN VAR_DECL ASSIGN ASSIGN CALL


public class JikesOutputParser implements ExecuteStreamHandler {
    protected Task task;
    protected int errors,warnings;
    protected boolean error = false;
    protected boolean emacsMode;

    protected BufferedReader br;

    /**
     * Ignore.
     */
    public void setProcessInputStream(OutputStream os) {}

    /**
     * Ignore.
     */
    public void setProcessErrorStream(InputStream is) {}

    /**
     * Set the inputstream
     */
    public void setProcessOutputStream(InputStream is) throws IOException {
        br = new BufferedReader(new InputStreamReader(is));
    }

    /**
     * Invokes parseOutput.
     */
    public void start() throws IOException {
        parseOutput(br);
    }

    /**
     * Ignore.
     */
    public void stop() {}

    /**
     * Construct a new Parser object
     * @param task - task in whichs context we are called
     */
    protected JikesOutputParser(Task task, boolean emacsMode) {
        super();
        this.task = task;
        this.emacsMode = emacsMode;
    }

    /**
     * Parse the output of a jikes compiler
     * @param reader - Reader used to read jikes's output
     */
    protected void parseOutput(BufferedReader reader) throws IOException {
       if (emacsMode)
           parseEmacsOutput(reader);
       else
           parseStandardOutput(reader);
    }

    private void parseStandardOutput(BufferedReader reader) throws IOException {
        String line;
        String lower;

        while ((line = reader.readLine()) != null) {
            lower = line.toLowerCase();
            if (line.trim().equals(""))
                continue;
            if (lower.indexOf("error") != -1)
                setError(true);
            else if (lower.indexOf("warning") != -1)
                setError(false);
            else {
                if (emacsMode)
                    setError(true);
            }
            log(line);
        }
    }

    private void parseEmacsOutput(BufferedReader reader) throws IOException {
       parseStandardOutput(reader);
    }

    private void setError(boolean err) {
        error = err;
        if(error)
            errorFlag = true;
    }

    private void log(String line) {
       if (!emacsMode) {
           task.log("", (error ? Project.MSG_ERR : Project.MSG_WARN));
       }
       task.log(line, (error ? Project.MSG_ERR : Project.MSG_WARN));
    }

    /**
     * Indicate if there were errors during the compile
     * @return if errors ocured
     */
    protected boolean getErrorFlag() {
        return errorFlag;

FUNC_DECL IF PARAM ASSIGN ASSIGN LITERAL_ANCHOR


public class Namespace {
    public static final Namespace SYSTEM_NAMESPACE;
    static {
        SYSTEM_NAMESPACE = new Namespace();
    }

    private List rules = new ArrayList();

    private String name;

    private boolean chainRules = false;

    private NamespaceTransformer fromSystemTransformer = new NamespaceTransformer() {
        public ModuleRevisionId transform(ModuleRevisionId mrid) {
            if (mrid == null) {
                return null;
            }
            for (Iterator iter = rules.iterator(); iter.hasNext();) {
                NamespaceRule rule = (NamespaceRule) iter.next();
                ModuleRevisionId nmrid = rule.getFromSystem().transform(mrid);
                if (chainRules) {
                    mrid = nmrid;
                } else if (!nmrid.equals(mrid)) {
                    return nmrid;
                }
            }
            return mrid;
        }

        public boolean isIdentity() {
            return rules.isEmpty();
        }
    };

    private NamespaceTransformer toSystemTransformer = new NamespaceTransformer() {
        public ModuleRevisionId transform(ModuleRevisionId mrid) {
            if (mrid == null) {
                return null;
            }
            for (Iterator iter = rules.iterator(); iter.hasNext();) {
                NamespaceRule rule = (NamespaceRule) iter.next();
                ModuleRevisionId nmrid = rule.getToSystem().transform(mrid);
                if (chainRules) {
                    mrid = nmrid;
                } else if (!nmrid.equals(mrid)) {
                    return nmrid;
                }
            }
            return mrid;
        }

        public boolean isIdentity() {
            return rules.isEmpty();
        }
    };

    public void addRule(NamespaceRule rule) {
        rules.add(rule);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public NamespaceTransformer getFromSystemTransformer() {
        return fromSystemTransformer;
    }

    public NamespaceTransformer getToSystemTransformer() {
        return toSystemTransformer;
    }

    public boolean isChainrules() {
        return chainRules;
    }

    public void setChainrules(boolean chainRules) {
        this.chainRules = chainRules;

    public String getName() {
        return name;


org.apache.tools.ant.types.Environment

public class Environment {

    /**
     * a vector of type Enviromment.Variable
     * @see Variable
     */
    protected Vector variables;

    /**
     * representation of a single env value
     */
    public static class Variable {

        /**
         * env key and value pair; everything gets expanded to a string
         * during assignment
         */
        private String key, value;

        /**
         * Constructor for variable
         *
         */
        public Variable() {
            super();
        }

        /**
         * set the key
         * @param key string
         */
        public void setKey(String key) {
            this.key = key;
        }

        /**
         * set the value
         * @param value string value
         */
        public void setValue(String value) {
            this.value = value;
        }

        /**
         * key accessor
         * @return key
         */
        public String getKey() {
            return this.key;
        }

        /**
         * value accessor
         * @return value
         */
        public String getValue() {
            return this.value;
        }

        /**
         * stringify path and assign to the value.
         * The value will contain all path elements separated by the appropriate
         * separator
         * @param path path
         */
        public void setPath(Path path) {
            this.value = path.toString();
        }

        /**
         * get the absolute path of a file and assign it to the value
         * @param file file to use as the value
         */
        public void setFile(java.io.File file) {
            this.value = file.getAbsolutePath();
        }

        /**
         * get the assigment string
         * This is not ready for insertion into a property file without following
         * the escaping rules of the properties class.
         * @return a string of the form key=value.
         * @throws BuildException if key or value are unassigned
         */
        public String getContent() throws BuildException {
            validate();
            StringBuffer sb = new StringBuffer(key.trim());
            sb.append("=").append(value.trim());
            return sb.toString();
        }

        /**
         * checks whether all required attributes have been specified.
         * @throws BuildException if key or value are unassigned
         */
        public void validate() {
            if (key == null || value == null) {
                throw new BuildException("key and value must be specified "
                    + "for environment variables.");
            }
        }
    }

    /**
     * constructor
     */
    public Environment() {
        variables = new Vector();
    }

    /**
     * add a variable.
     * Validity checking is <i>not</i> performed at this point. Duplicates
     * are not caught either.
     * @param var new variable.
     */
    public void addVariable(Variable var) {
        variables.addElement(var);
    }

    /**
     * get the variable list as an array
     * @return array of key=value assignment strings
     * @throws BuildException if any variable is misconfigured
     */
    public String[] getVariables() throws BuildException {
        if (variables.size() == 0) {
            return null;
        }
        String[] result = new String[variables.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = ((Variable) variables.elementAt(i)).getContent();
        }
        return result;


public class JmsMessage extends DefaultMessage {
    private static final transient Log LOG = LogFactory.getLog(JmsMessage.class);
    private Message jmsMessage;

    public JmsMessage() {
    }

    public JmsMessage(Message jmsMessage) {
        setJmsMessage(jmsMessage);
    }

    @Override
    public String toString() {
        if (jmsMessage != null) {
            return "JmsMessage: " + jmsMessage;
        } else {
            return "JmsMessage: " + getBody();
        }
    }

    /**
     * Returns the underlying JMS message
     *
     * @return the underlying JMS message
     */
    public Message getJmsMessage() {
        return jmsMessage;
    }

    public void setJmsMessage(Message jmsMessage) {
        this.jmsMessage = jmsMessage;
        try {
            String id = getDestinationAsString(jmsMessage.getJMSDestination());
            id += getSanitizedString(jmsMessage.getJMSMessageID());
            setMessageId(id);
        } catch (JMSException e) {
            LOG.error("Failed to get message id from message " + jmsMessage, e);
        }
    }

    public Object getHeader(String name) {
        Object answer = null;

        if (jmsMessage != null && !name.startsWith("JMS")) {
            try {
                answer = jmsMessage.getObjectProperty(name);
            } catch (JMSException e) {
                throw new MessagePropertyAccessException(name, e);
            }
        }
        if (answer == null) {
            answer = super.getHeader(name);
        }
        return answer;
    }

    @Override
    public JmsMessage newInstance() {
        return new JmsMessage();
    }

    @Override
    protected Object createBody() {
        if (jmsMessage != null && getExchange() instanceof JmsExchange) {
            JmsExchange exchange = (JmsExchange)getExchange();
            return exchange.getBinding().extractBodyFromJms(exchange, jmsMessage);
        }
        return null;
    }

    @Override
    protected void populateInitialHeaders(Map<String, Object> map) {
        if (jmsMessage != null) {
            try {
                map.put("JMSCorrelationID", jmsMessage.getJMSCorrelationID());
                map.put("JMSDeliveryMode", jmsMessage.getJMSDeliveryMode());
                map.put("JMSDestination", jmsMessage.getJMSDestination());
                map.put("JMSExpiration", jmsMessage.getJMSExpiration());
                map.put("JMSMessageID", jmsMessage.getJMSMessageID());
                map.put("JMSPriority", jmsMessage.getJMSPriority());
                map.put("JMSRedelivered", jmsMessage.getJMSRedelivered());
                map.put("JMSReplyTo", jmsMessage.getJMSReplyTo());
                map.put("JMSTimestamp", jmsMessage.getJMSTimestamp());
                map.put("JMSType", jmsMessage.getJMSType());

                map.put("JMSXGroupID", jmsMessage.getStringProperty("JMSXGroupID"));

            }
            catch (JMSException e) {
                throw new MessageJMSPropertyAccessException(e);
            }

            Enumeration names;
            try {
                names = jmsMessage.getPropertyNames();
            } catch (JMSException e) {
                throw new MessagePropertyNamesAccessException(e);
            }
            while (names.hasMoreElements()) {
                String name = names.nextElement().toString();
                try {
                    Object value = jmsMessage.getObjectProperty(name);
                    map.put(name, value);
                } catch (JMSException e) {
                    throw new MessagePropertyAccessException(name, e);
                }
            }
        }
    }

    private String getDestinationAsString(Destination destination) throws JMSException {
        String result = "";
        if (destination == null) {
            result = "null destination!";
        } else if (destination instanceof Topic) {
            result += "topic" + File.separator + getSanitizedString(((Topic)destination).getTopicName());
        } else {
            result += "queue" + File.separator + getSanitizedString(((Queue)destination).getQueueName());
        }
        result += File.separator;
        return result;
    }

    private String getSanitizedString(Object value) {
        return value != null ? value.toString().replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_") : "";

FUNC_DECL TRY PARAM CATCH VAR_DECL ASSIGN CALL ASSIGN CALL CALL CALL BINARY_OP CALL CALL LITERAL_ANCHOR


public class AntSoundPlayer implements LineListener, BuildListener {

    private File fileSuccess = null;
    private int loopsSuccess = 0;
    private Long durationSuccess = null;

    private File fileFail = null;
    private int loopsFail = 0;
    private Long durationFail = null;

    /** Constructor for AntSoundPlayer. */
    public AntSoundPlayer() {
    }

    /**
     * @param file the location of the audio file to be played when the
     *        build is successful
     * @param loops the number of times the file should be played when
     *        the build is successful
     * @param duration the number of milliseconds the file should be
     *        played when the build is successful
     */
    public void addBuildSuccessfulSound(File file, int loops, Long duration) {
        this.fileSuccess = file;
        this.loopsSuccess = loops;
        this.durationSuccess = duration;
    }

    /**
     * @param fileFail the location of the audio file to be played
     *        when the build fails
     * @param loopsFail the number of times the file should be played
     *        when the build is fails
     * @param durationFail the number of milliseconds the file should be
     *        played when the build fails
     */
    public void addBuildFailedSound(File fileFail, int loopsFail, Long durationFail) {
        this.fileFail = fileFail;
        this.loopsFail = loopsFail;
        this.durationFail = durationFail;
    }

    /**
     * Plays the file for duration milliseconds or loops.
     */
    private void play(Project project, File file, int loops, Long duration) {

        Clip audioClip = null;

        AudioInputStream audioInputStream = null;

        try {
            audioInputStream = AudioSystem.getAudioInputStream(file);
        } catch (UnsupportedAudioFileException uafe) {
            project.log("Audio format is not yet supported: "
                + uafe.getMessage());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        if (audioInputStream != null) {
            AudioFormat format = audioInputStream.getFormat();
            DataLine.Info   info = new DataLine.Info(Clip.class, format,
                                             AudioSystem.NOT_SPECIFIED);
            try {
                audioClip = (Clip) AudioSystem.getLine(info);
                audioClip.addLineListener(this);
                audioClip.open(audioInputStream);
            } catch (LineUnavailableException e) {
                project.log("The sound device is currently unavailable");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (duration != null) {
                playClip(audioClip, duration.longValue());
            } else {
                playClip(audioClip, loops);
            }
            audioClip.drain();
            audioClip.close();
        } else {
            project.log("Can't get data from file " + file.getName());
        }
    }

    private void playClip(Clip clip, int loops) {

        clip.loop(loops);
        while (clip.isRunning()) {
        }
    }

    private void playClip(Clip clip, long duration) {
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        try {
            Thread.sleep(duration);
        } catch (InterruptedException e) {
        }
    }

    /**
     * This is implemented to listen for any line events and closes the
     * clip if required.
     * @param event the line event to follow
     */
    public void update(LineEvent event) {
        if (event.getType().equals(LineEvent.Type.STOP)) {
            Line line = event.getLine();
            line.close();
        } else if (event.getType().equals(LineEvent.Type.CLOSE)) {
            /*
             *  There is a bug in JavaSound 0.90 (jdk1.3beta).
             *  It prevents correct termination of the VM.
             *  So we have to exit ourselves.
             */
        }
    }

    /**
     *  Fired before any targets are started.
     * @param event ignored
     */
    public void buildStarted(BuildEvent event) {
    }

    /**
     *  Fired after the last target has finished. This event
     *  will still be thrown if an error occurred during the build.
     * @param event the build finished event.
     *  @see BuildEvent#getException()
     */
    public void buildFinished(BuildEvent event) {
        if (event.getException() == null && fileSuccess != null) {
            play(event.getProject(), fileSuccess, loopsSuccess, durationSuccess);
        } else if (event.getException() != null && fileFail != null) {
            play(event.getProject(), fileFail, loopsFail, durationFail);
        }
    }

    /**
     *  Fired when a target is started.
     * @param event ignored.
     *  @see BuildEvent#getTarget()
     */
    public void targetStarted(BuildEvent event) {
    }

    /**
     *  Fired when a target has finished. This event will
     *  still be thrown if an error occurred during the build.
     * @param event ignored.
     *  @see BuildEvent#getException()
     */
    public void targetFinished(BuildEvent event) {
    }

    /**
     *  Fired when a task is started.
     * @param event ignored.
     *  @see BuildEvent#getTask()
     */
    public void taskStarted(BuildEvent event) {
    }

    /**
     *  Fired when a task has finished. This event will still
     *  be throw if an error occurred during the build.
     * @param event ignored.
     *  @see BuildEvent#getException()
     */
    public void taskFinished(BuildEvent event) {
    }

    /**
     *  Fired whenever a message is logged.
     *  @param event the build event
     *  @see BuildEvent#getMessage()
     *  @see BuildEvent#getPriority()
     */
    public void messageLogged(BuildEvent event) {

FUNC_DECL IF TRY VAR_DECL VAR_DECL PARAM PARAM PARAM PARAM BINARY_OP CATCH CATCH IF TRY VAR_DECL VAR_DECL LITERAL_ANCHOR ASSIGN LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL CALL BINARY_OP CATCH CATCH CALL CALL CALL BINARY_OP LITERAL_ANCHOR RETURN CALL CALL ASSIGN CALL CALL BINARY_OP CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL

FUNC_DECL TRY PARAM PARAM CATCH CALL CALL

FUNC_DECL IF PARAM IF CALL CALL VAR_DECL CALL CALL CALL CALL


org.apache.xml.utils.StringToIntTable

public class StringToIntTable
{

  public static final int INVALID_KEY = -10000;

  /** Block size to allocate          */
  private int m_blocksize;

  /** Array of strings this table points to. Associated with ints
   * in m_values         */
  private String m_map[];

  /** Array of ints this table points. Associated with strings from
   * m_map.         */
  private int m_values[];

  /** Number of ints in the table          */
  private int m_firstFree = 0;

  /** Size of this table         */
  private int m_mapSize;

  /**
   * Default constructor.  Note that the default
   * block size is very small, for small lists.
   */
  public StringToIntTable()
  {

    m_blocksize = 8;
    m_mapSize = m_blocksize;
    m_map = new String[m_blocksize];
    m_values = new int[m_blocksize];
  }

  /**
   * Construct a StringToIntTable, using the given block size.
   *
   * @param blocksize Size of block to allocate
   */
  public StringToIntTable(int blocksize)
  {

    m_blocksize = blocksize;
    m_mapSize = blocksize;
    m_map = new String[blocksize];
    m_values = new int[m_blocksize];
  }

  /**
   * Get the length of the list.
   *
   * @return the length of the list
   */
  public final int getLength()
  {
    return m_firstFree;
  }

  /**
   * Append a string onto the vector.
   *
   * @param key String to append
   * @param value The int value of the string
   */
  public final void put(String key, int value)
  {

    if ((m_firstFree + 1) >= m_mapSize)
    {
      m_mapSize += m_blocksize;

      String newMap[] = new String[m_mapSize];

      System.arraycopy(m_map, 0, newMap, 0, m_firstFree + 1);

      m_map = newMap;

      int newValues[] = new int[m_mapSize];

      System.arraycopy(m_values, 0, newValues, 0, m_firstFree + 1);

      m_values = newValues;
    }

    m_map[m_firstFree] = key;
    m_values[m_firstFree] = value;

    m_firstFree++;
  }

  /**
   * Tell if the table contains the given string.
   *
   * @param key String to look for
   *
   * @return The String's int value
   *
   */
  public final int get(String key)
  {

    for (int i = 0; i < m_firstFree; i++)
    {
      if (m_map[i].equals(key))
        return m_values[i];
    }

	return INVALID_KEY;
  }

  /**
   * Tell if the table contains the given string. Ignore case.
   *
   * @param key String to look for
   *
   * @return The string's int value
   */
  public final int getIgnoreCase(String key)
  {

    if (null == key)
        return INVALID_KEY;

    for (int i = 0; i < m_firstFree; i++)
    {
      if (m_map[i].equalsIgnoreCase(key))
        return m_values[i];
    }

    return INVALID_KEY;
  }

  /**
   * Tell if the table contains the given string.
   *
   * @param key String to look for
   *
   * @return True if the string is in the table
   */
  public final boolean contains(String key)
  {

    for (int i = 0; i < m_firstFree; i++)
    {
      if (m_map[i].equals(key))
        return true;
    }

    return false;
  }

  /**
   * Return array of keys in the table.
   *
   * @return Array of strings
   */
  public final String[] keys()
  {
    String [] keysArr = new String[m_firstFree];

    for (int i = 0; i < m_firstFree; i++)
    {
      keysArr[i] = m_map[i];
    }

    return keysArr;

FUNC_DECL RETURN LOOP PARAM BINARY_OP IF RETURN LITERAL_ANCHOR CALL

FUNC_DECL ASSIGN ASSIGN ASSIGN ASSIGN LITERAL_ANCHOR

FUNC_DECL PARAM ASSIGN ASSIGN ASSIGN ASSIGN


org.apache.xalan.lib.sql.ObjectArray

public class ObjectArray
{
  /**
   */
  private int m_minArraySize = 10;
  /**
   * The container of all the sub arrays
   */
  private Vector m_Arrays = new Vector(200);

  /**
   * An index that porvides the Vector entry for the current Array that is
   * being appended to.
   */
  private _ObjectArray m_currentArray;

  /**
   * The next offset in the current Array to append a new object
   */
  private int m_nextSlot;

  /**
   */
  public ObjectArray( )
  {
    init(10);
  }

  /**
   * @param minArraySize The size of the Arrays stored in the Vector
   */
  public ObjectArray( final int minArraySize )
  {
    init(minArraySize);
  }

  /**
   * @param size
   *
   */
  private void init( int size )
  {
    m_minArraySize = size;
    m_currentArray = new _ObjectArray(m_minArraySize);
  }

  /**
   * @param idx Index of the Object in the Array
   *
   */
  public Object getAt( final int idx )
  {
    int arrayIndx = idx / m_minArraySize;
    int arrayOffset = idx - (arrayIndx * m_minArraySize);

    if (arrayIndx < m_Arrays.size())
    {
      _ObjectArray a = (_ObjectArray)m_Arrays.elementAt(arrayIndx);
      return a.objects[arrayOffset];
    }
    else
    {

      return m_currentArray.objects[arrayOffset];
    }
  }

  /**
   * @param idx Index of the Object in the Array
   * @param obj , The value to set in the Array
   *
   */
  public void setAt( final int idx, final Object obj )
  {
    int arrayIndx = idx / m_minArraySize;
    int arrayOffset = idx - (arrayIndx * m_minArraySize);

    if (arrayIndx < m_Arrays.size())
    {
      _ObjectArray a = (_ObjectArray)m_Arrays.elementAt(arrayIndx);
      a.objects[arrayOffset] = obj;
    }
    else
    {

      m_currentArray.objects[arrayOffset] = obj;
    }
  }

  /**
   * @param o Object to be appended to the Array
   *
   */
  public int append( Object o )
  {
    if (m_nextSlot >= m_minArraySize)
    {
      m_Arrays.addElement(m_currentArray);
      m_nextSlot = 0;
      m_currentArray = new _ObjectArray(m_minArraySize);
    }

    m_currentArray.objects[m_nextSlot] = o;

    int pos = (m_Arrays.size() * m_minArraySize) + m_nextSlot;

    m_nextSlot++;

    return pos;
  }

  /**
   */
  class _ObjectArray
  {
    /**
     */
    public Object[] objects;
    /**
     * @param size
     */
    public _ObjectArray( int size )
    {
      objects = new Object[size];
    }
  }

  /**
   * @param args
   *
   */
  public static void main( String[] args )
  {
    String[] word={
      "Zero","One","Two","Three","Four","Five",
      "Six","Seven","Eight","Nine","Ten",
      "Eleven","Twelve","Thirteen","Fourteen","Fifteen",
      "Sixteen","Seventeen","Eighteen","Nineteen","Twenty",
      "Twenty-One","Twenty-Two","Twenty-Three","Twenty-Four",
      "Twenty-Five","Twenty-Six","Twenty-Seven","Twenty-Eight",
      "Twenty-Nine","Thirty","Thirty-One","Thirty-Two",
      "Thirty-Three","Thirty-Four","Thirty-Five","Thirty-Six",
      "Thirty-Seven","Thirty-Eight","Thirty-Nine"};

    ObjectArray m_ObjectArray = new ObjectArray();
    for (int x =0; x< word.length; x++)
    {
      System.out.print(" - " + m_ObjectArray.append(word[x]));
    }

    System.out.println("\n");
    for (int x =0; x< word.length; x++)
    {
      String s = (String) m_ObjectArray.getAt(x);
      System.out.println(s);
    }

    System.out.println((String) m_ObjectArray.getAt(5));
    System.out.println((String) m_ObjectArray.getAt(10));
    System.out.println((String) m_ObjectArray.getAt(20));
    System.out.println((String) m_ObjectArray.getAt(2));
    System.out.println((String) m_ObjectArray.getAt(15));
    System.out.println((String) m_ObjectArray.getAt(30));
    System.out.println((String) m_ObjectArray.getAt(6));
    System.out.println((String) m_ObjectArray.getAt(8));

    System.out.println((String) m_ObjectArray.getAt(40));

  public ObjectArray( )
  {
    init(10);


public class TextAreaOptionPane extends AbstractOptionPane
{
	//{{{ TextAreaOptionPane constructor
	public TextAreaOptionPane()
	{
		super("textarea");
	} //}}}

	//{{{ _init() method
	public void _init()
	{
		/* Font */
		font = new FontSelector(jEdit.getFontProperty("view.font"));

		addComponent(jEdit.getProperty("options.textarea.font"),font);

		/* Text color */
		addComponent(jEdit.getProperty("options.textarea.foreground"),
			foregroundColor = new ColorWellButton(
			jEdit.getColorProperty("view.fgColor")),
			GridBagConstraints.VERTICAL);

		/* Background color */
		addComponent(jEdit.getProperty("options.textarea.background"),
			backgroundColor = new ColorWellButton(
			jEdit.getColorProperty("view.bgColor")),
			GridBagConstraints.VERTICAL);

		/* Caret color, caret blink, block caret */
		blinkCaret = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".blinkCaret"));
		blinkCaret.setSelected(jEdit.getBooleanProperty("view.caretBlink"));

		blockCaret = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".blockCaret"));
		blockCaret.setSelected(jEdit.getBooleanProperty("view.blockCaret"));

		thickCaret = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".thickCaret"));
		thickCaret.setSelected(jEdit.getBooleanProperty("view.thickCaret"));

		Box caretSettings = new Box(BoxLayout.X_AXIS);
		caretSettings.add(new JLabel(jEdit.getProperty(
			"options.textarea.caret")));
		caretSettings.add(Box.createHorizontalStrut(6));
		caretSettings.add(blinkCaret);
		caretSettings.add(blockCaret);
		caretSettings.add(thickCaret);

		addComponent(caretSettings,caretColor = new ColorWellButton(
			jEdit.getColorProperty("view.caretColor")),
			GridBagConstraints.VERTICAL);

		/* Selection color */
		addComponent(jEdit.getProperty("options.textarea.selection"),
			selectionColor = new ColorWellButton(
			jEdit.getColorProperty("view.selectionColor")),
			GridBagConstraints.VERTICAL);

		/* Multiple selection color */
		addComponent(jEdit.getProperty("options.textarea.multipleSelection"),
			multipleSelectionColor = new ColorWellButton(
			jEdit.getColorProperty("view.multipleSelectionColor")),
			GridBagConstraints.VERTICAL);

		/* Line highlight */
		lineHighlight = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".lineHighlight"));
		lineHighlight.setSelected(jEdit.getBooleanProperty("view.lineHighlight"));
		addComponent(lineHighlight,lineHighlightColor = new ColorWellButton(
			jEdit.getColorProperty("view.lineHighlightColor")),
			GridBagConstraints.VERTICAL);

		/* Structure highlight */
		structureHighlight = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".structureHighlight"));
		structureHighlight.setSelected(jEdit.getBooleanProperty(
			"view.structureHighlight"));
		addComponent(structureHighlight,structureHighlightColor = new ColorWellButton(
			jEdit.getColorProperty("view.structureHighlightColor")),
			GridBagConstraints.VERTICAL);

		/* EOL markers */
		eolMarkers = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".eolMarkers"));
		eolMarkers.setSelected(jEdit.getBooleanProperty("view.eolMarkers"));
		addComponent(eolMarkers,eolMarkerColor =new ColorWellButton(
			jEdit.getColorProperty("view.eolMarkerColor")),
			GridBagConstraints.VERTICAL);

		/* Wrap guide */
		wrapGuide = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".wrapGuide"));
		wrapGuide.setSelected(jEdit.getBooleanProperty("view.wrapGuide"));
		addComponent(wrapGuide,wrapGuideColor = new ColorWellButton(
			jEdit.getColorProperty("view.wrapGuideColor")),
			GridBagConstraints.VERTICAL);

		/* Electric borders */
		electricBorders = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".electricBorders"));
		electricBorders.setSelected(!"0".equals(jEdit.getProperty(
			"view.electricBorders")));
		addComponent(electricBorders);

		/* Anti-aliasing */

		antiAlias = new JComboBox(AntiAlias.comboChoices);
		antiAlias.setToolTipText(jEdit.getProperty("options.textarea.antiAlias.tooltip"));
		AntiAlias antiAliasValue = new AntiAlias(jEdit.getProperty("view.antiAlias"));
		font.setAntiAliasEnabled(antiAliasValue.val()>0);
		antiAlias.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent evt)
				{
					int idx = antiAlias.getSelectedIndex();
					font.setAntiAliasEnabled(idx > 0);
					font.repaint();
				}
			});
		antiAlias.setSelectedIndex(antiAliasValue.val());
		addComponent(jEdit.getProperty("options.textarea"+ ".antiAlias"), antiAlias);

		/* Fractional font metrics */
		fracFontMetrics = new JCheckBox(jEdit.getProperty("options.textarea"
			+ ".fracFontMetrics"));
		fracFontMetrics.setSelected(jEdit.getBooleanProperty("view.fracFontMetrics"));
		addComponent(fracFontMetrics);

		/* Strip trailing EOL */
		stripTrailingEOL = new JCheckBox(jEdit.getProperty(
			"options.textArea.stripTrailingEOL"));
		stripTrailingEOL.setSelected(jEdit.getBooleanProperty("stripTrailingEOL"));
		addComponent(stripTrailingEOL);

		completeFromAllBuffers = new JCheckBox(jEdit.getProperty(
			"options.textArea.completeFromAllBuffers"));
		completeFromAllBuffers.setSelected(jEdit.getBooleanProperty("completeFromAllBuffers"));
		addComponent(completeFromAllBuffers);

	} //}}}

	//{{{ _save() method
	public void _save()
	{
		jEdit.setFontProperty("view.font",font.getFont());

		jEdit.setColorProperty("view.fgColor",foregroundColor
			.getSelectedColor());
		jEdit.setColorProperty("view.bgColor",backgroundColor
			.getSelectedColor());
		jEdit.setBooleanProperty("view.caretBlink",blinkCaret.isSelected());
		jEdit.setBooleanProperty("view.blockCaret",blockCaret.isSelected());
		jEdit.setBooleanProperty("view.thickCaret",thickCaret.isSelected());
		jEdit.setColorProperty("view.caretColor",caretColor
			.getSelectedColor());
		jEdit.setColorProperty("view.selectionColor",selectionColor
			.getSelectedColor());
		jEdit.setColorProperty("view.multipleSelectionColor",multipleSelectionColor
			.getSelectedColor());
		jEdit.setBooleanProperty("view.lineHighlight",lineHighlight
			.isSelected());
		jEdit.setColorProperty("view.lineHighlightColor",
			lineHighlightColor.getSelectedColor());
		jEdit.setBooleanProperty("view.structureHighlight",structureHighlight
			.isSelected());
		jEdit.setColorProperty("view.structureHighlightColor",
			structureHighlightColor.getSelectedColor());
		jEdit.setBooleanProperty("view.eolMarkers",eolMarkers
			.isSelected());
		jEdit.setColorProperty("view.eolMarkerColor",
			eolMarkerColor.getSelectedColor());
		jEdit.setBooleanProperty("view.wrapGuide",wrapGuide
			.isSelected());
		jEdit.setColorProperty("view.wrapGuideColor",
			wrapGuideColor.getSelectedColor());
		jEdit.setIntegerProperty("view.electricBorders",electricBorders
			.isSelected() ? 3 : 0);
		AntiAlias nv = new AntiAlias(jEdit.getProperty("view.antiAlias"));
		nv.set(antiAlias.getSelectedIndex());
		jEdit.setProperty("view.antiAlias", nv.toString());
		jEdit.setBooleanProperty("view.fracFontMetrics",fracFontMetrics.isSelected());
		jEdit.setBooleanProperty("stripTrailingEOL", stripTrailingEOL.isSelected());
		jEdit.setBooleanProperty("completeFromAllBuffers", completeFromAllBuffers.isSelected());
	} //}}}

	//{{{ Private members
	private FontSelector font;
	private ColorWellButton foregroundColor;
	private ColorWellButton backgroundColor;
	private JCheckBox blinkCaret;
	private JCheckBox blockCaret;
	private JCheckBox thickCaret;
	private ColorWellButton caretColor;
	private ColorWellButton selectionColor;
	private ColorWellButton multipleSelectionColor;
	private JCheckBox lineHighlight;
	private ColorWellButton lineHighlightColor;
	private JCheckBox structureHighlight;
	private ColorWellButton structureHighlightColor;
	private JCheckBox eolMarkers;
	private ColorWellButton eolMarkerColor;
	private JCheckBox wrapGuide;
	private ColorWellButton wrapGuideColor;
	private JCheckBox electricBorders;
	// private JCheckBox antiAlias;
	private JComboBox antiAlias;
	private JCheckBox fracFontMetrics;
	private JCheckBox stripTrailingEOL;
	private JCheckBox completeFromAllBuffers;