Ejemplo n.º 1
0
  /**
   * This method is called when a PCDATA element is encountered. A Java reader is supplied from
   * which you can read the data. The reader will only read the data of the element. You don't need
   * to check for boundaries. If you don't read the full element, the rest of the data is skipped.
   * You also don't have to care about entities; they are resolved by the parser.
   *
   * @param reader the Java reader from which you can retrieve the data
   * @param systemID the system ID of the XML data source
   * @param lineNr the line in the source where the element starts
   * @throws java.lang.Exception If an exception occurred while processing the event.
   */
  public void addPCData(Reader reader, String systemID, int lineNr) throws Exception {
    int bufSize = 2048;
    int sizeRead = 0;
    StringBuffer str = new StringBuffer(bufSize);
    char[] buf = new char[bufSize];

    for (; ; ) {
      if (sizeRead >= bufSize) {
        bufSize *= 2;
        str.ensureCapacity(bufSize);
      }

      int size = reader.read(buf);

      if (size < 0) {
        break;
      }

      str.append(buf, 0, size);
      sizeRead += size;
    }

    XMLElement elt = new XMLElement(null, systemID, lineNr);
    elt.setContent(str.toString());

    if (!this.stack.empty()) {
      XMLElement top = (XMLElement) this.stack.peek();
      top.addChild(elt);
    }
  }
Ejemplo n.º 2
0
 public static final void bytesToHexAppend(byte[] bs, int off, int length, StringBuffer sb) {
   sb.ensureCapacity(sb.length() + length * 2);
   for (int i = off; i < (off + length) && i < bs.length; i++) {
     sb.append(Character.forDigit((bs[i] >>> 4) & 0xf, 16));
     sb.append(Character.forDigit(bs[i] & 0xf, 16));
   }
 }
Ejemplo n.º 3
0
 public static String unescape(String src) {
   StringBuffer result = new StringBuffer();
   result.ensureCapacity(src.length());
   int lastPos = 0, pos = 0;
   char ch;
   while (lastPos < src.length()) {
     pos = src.indexOf("%", lastPos);
     if (pos == lastPos) {
       if (src.charAt(pos + 1) == 'u') {
         ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
         result.append(ch);
         lastPos = pos + 6;
       } else {
         ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
         result.append(ch);
         lastPos = pos + 3;
       }
     } else {
       if (pos == -1) {
         result.append(src.substring(lastPos));
         lastPos = src.length();
       } else {
         result.append(src.substring(lastPos, pos));
         lastPos = pos;
       }
     }
   }
   return result.toString();
 }
  /** A routine that knows how and when to quote and escape the given value. */
  private static String quote(String value) {
    boolean needsQuotes = false;

    //    check to see if we actually have to quote this thing
    int length = value.length();
    for (int i = 0; (i < length) && !needsQuotes; i++) {
      needsQuotes = !isTokenChar(value.charAt(i));
    }

    if (needsQuotes) {
      StringBuffer buffer = new StringBuffer();
      buffer.ensureCapacity((int) (length * 1.5));

      //    add the initial quote
      buffer.append('"');

      //    add the properly escaped text
      for (int i = 0; i < length; ++i) {
        char c = value.charAt(i);
        if ((c == '\\') || (c == '"')) buffer.append('\\');
        buffer.append(c);
      }

      //    add the closing quote
      buffer.append('"');

      return buffer.toString();
    } else {
      return value;
    }
  }
  public static String escape(String src) {
    int i;
    char j;
    StringBuffer tmp = new StringBuffer();
    tmp.ensureCapacity(src.length() * 6);

    for (i = 0; i < src.length(); i++) {

      j = src.charAt(i);

      if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j))
        tmp.append(j);
      else {
        if (j < 256) {
          tmp.append("%");
          if (j < 16) tmp.append("0");
          tmp.append(Integer.toString(j, 16));
        } else {
          tmp.append("%u");
          tmp.append(Integer.toString(j, 16));
        }
      }
    }
    return tmp.toString();
  }
Ejemplo n.º 6
0
  public Object getValue() {
    String text = ((JTextField) editor).getText();
    if (text == null || text.trim().length() == 0) {
      return getDefaultValue();
    }

    // collect all numbers from this textfield
    StringBuffer number = new StringBuffer();
    number.ensureCapacity(text.length());
    for (int i = 0, c = text.length(); i < c; i++) {
      char character = text.charAt(i);
      if ('.' == character
          || '-' == character
          || 'E' == character
          || Character.isDigit(character)) {
        number.append(character);
      } else if (' ' == character) {
        continue;
      } else {
        break;
      }
    }

    try {
      lastGoodValue = Double.parseDouble(number.toString());
    } catch (Exception e) {
      UIManager.getLookAndFeel().provideErrorFeedback(editor);
    }

    return lastGoodValue;
  }
Ejemplo n.º 7
0
 /**
  * Appends a String representation of this to the given {@link StringBuffer} or creates a new one
  * if none is given.
  *
  * @param in the StringBuffer to append to, may be <code>null</code>
  * @return a StringBuffer, never <code>null</code>
  * @see #toAppendable(Appendable)
  */
 public StringBuffer toStringBuffer(StringBuffer in) {
   StringBuffer out = in;
   if (out == null) {
     out = new StringBuffer(36);
   } else {
     out.ensureCapacity(out.length() + 36);
   }
   return (StringBuffer) toAppendable(out);
 }
Ejemplo n.º 8
0
  public void test_capacity() {
    StringBuffer buf1 = new StringBuffer("");
    StringBuffer buf2 = new StringBuffer("pentiumpentiumpentium");

    harness.check(!(buf1.capacity() != 16), "test_capacity - 1");

    int cap = buf2.capacity();
    harness.check(!(cap != 37), "test_capacity - 2");

    buf1.ensureCapacity(17);

    // CYGNUS: This is a test for JDK 1.2 conformance
    harness.check(!(buf1.capacity() != 34), "test_capacity - 3");
  }
  /** Return a string representation of this object. */
  public String toString() {
    StringBuffer buffer = new StringBuffer();
    buffer.ensureCapacity(parameters.size() * 16);
    //    heuristic: 8 characters per field

    Enumeration keys = parameters.keys();
    while (keys.hasMoreElements()) {
      String key = (String) keys.nextElement();
      buffer.append("; ");
      buffer.append(key);
      buffer.append('=');
      buffer.append(quote((String) parameters.get(key)));
    }

    return buffer.toString();
  }
  public final void convertToCharacters(byte[] data, int offset, int length, StringBuffer s) {
    if (data == null) {
      return;
    }
    final byte[] value = data;
    if (length == 0) {
      return;
    }

    final int partialBlockLength = length % 3;
    final int blockCount = (partialBlockLength != 0) ? length / 3 + 1 : length / 3;

    final int encodedLength = blockCount * 4;
    final int originalBufferSize = s.length();
    s.ensureCapacity(encodedLength + originalBufferSize);

    int idx = offset;
    int lastIdx = offset + length;
    for (int i = 0; i < blockCount; ++i) {
      int b1 = value[idx++] & 0xFF;
      int b2 = (idx < lastIdx) ? value[idx++] & 0xFF : 0;
      int b3 = (idx < lastIdx) ? value[idx++] & 0xFF : 0;

      s.append(encodeBase64[b1 >> 2]);

      s.append(encodeBase64[((b1 & 0x03) << 4) | (b2 >> 4)]);

      s.append(encodeBase64[((b2 & 0x0f) << 2) | (b3 >> 6)]);

      s.append(encodeBase64[b3 & 0x3f]);
    }

    switch (partialBlockLength) {
      case 1:
        s.setCharAt(originalBufferSize + encodedLength - 1, '=');
        s.setCharAt(originalBufferSize + encodedLength - 2, '=');
        break;
      case 2:
        s.setCharAt(originalBufferSize + encodedLength - 1, '=');
        break;
    }
  }
  /** A routine that knows how to strip the quotes and escape sequences from the given value. */
  private static String unquote(String value) {
    int valueLength = value.length();
    StringBuffer buffer = new StringBuffer();
    buffer.ensureCapacity(valueLength);

    boolean escaped = false;
    for (int i = 0; i < valueLength; ++i) {
      char currentChar = value.charAt(i);
      if (!escaped && (currentChar != '\\')) {
        buffer.append(currentChar);
      } else if (escaped) {
        buffer.append(currentChar);
        escaped = false;
      } else {
        escaped = true;
      }
    }

    return buffer.toString();
  }
Ejemplo n.º 12
0
  /**
   * Print one row of a result set, padding each field to the display width and separating them with
   * '|'s
   *
   * @param out the place to write to
   * @param rs the ResultSet to use
   * @param rsmd the ResultSetMetaData to use
   * @param rowLen
   * @param nestedResults
   * @param conn
   * @param indentLevel number of tab stops to indent line
   * @param displayColumns A list of column numbers to display
   * @param displayColumnWidths If displayColumns is set, the width of columns to display, in
   *     characters.
   * @exception SQLException thrown on JDBC access failure
   */
  private static void DisplayRow(
      PrintWriter out,
      ResultSet rs,
      ResultSetMetaData rsmd,
      int rowLen,
      Vector nestedResults,
      Connection conn,
      int indentLevel,
      int[] displayColumns,
      int[] displayColumnWidths)
      throws SQLException {
    StringBuffer buf = new StringBuffer();
    buf.ensureCapacity(rowLen);

    int numCols = displayColumnWidths.length;
    int i;

    // get column header info
    // truncate it to the column display width
    // add a bar between each item.
    for (i = 1; i <= numCols; i++) {
      int colnum = displayColumns == null ? i : displayColumns[i - 1];
      if (i > 1) buf.append('|');

      String s;
      switch (rsmd.getColumnType(colnum)) {
        default:
          s = LocalizedResource.getInstance().getLocalizedString(rs, rsmd, colnum);
          break;
        case Types.JAVA_OBJECT:
        case Types.OTHER:
          {
            Object o = rs.getObject(colnum);
            if (o == null) {
              s = "NULL";
            } else if (o instanceof ResultSet && nestedResults != null) {
              s =
                  LocalizedResource.getMessage(
                      "UT_Resul0_20", LocalizedResource.getNumber(nestedResults.size()));
              nestedResults.addElement(o);
            } else {
              try {
                s = rs.getString(colnum);
              } catch (SQLException se) {
                // oops, they don't support refetching the column
                s = o.toString();
              }
            }
          }
          break;
      }
      if (s == null) s = "NULL";

      int w = displayColumnWidths[i - 1];
      if (s.length() < w) {
        StringBuffer fullS = new StringBuffer(s);
        fullS.ensureCapacity(w);
        for (int k = s.length(); k < w; k++) fullS.append(' ');
        s = fullS.toString();
      } else if (s.length() > w)
        // add the & marker to know it got cut off
        s = s.substring(0, w - 1) + "&";

      buf.append(s);
    }
    indentedPrintLine(out, indentLevel, buf);
  } // DisplayRow
Ejemplo n.º 13
0
  private static int indent_DisplayBanner(
      PrintWriter out,
      ResultSetMetaData rsmd,
      int indentLevel,
      int[] displayColumns,
      int[] displayColumnWidths)
      throws SQLException {

    StringBuffer buf = new StringBuffer();

    int numCols = displayColumnWidths.length;
    int rowLen;

    // do some precalculation so the buffer is allocated only once
    // buffer is twice as long as the display length plus one for a newline
    rowLen = (numCols - 1); // for the column separators
    for (int i = 1; i <= numCols; i++) rowLen += displayColumnWidths[i - 1];
    buf.ensureCapacity(rowLen);

    // get column header info
    // truncate it to the column display width
    // add a bar between each item.
    for (int i = 1; i <= numCols; i++) {
      int colnum = displayColumns == null ? i : displayColumns[i - 1];

      if (i > 1) buf.append('|');

      String s = rsmd.getColumnLabel(colnum);

      int w = displayColumnWidths[i - 1];

      if (s.length() < w) {

        buf.append(s);

        // try to paste on big chunks of space at a time.
        int k = w - s.length();
        for (; k >= 64; k -= 64)
          buf.append("                                                                ");
        for (; k >= 16; k -= 16) buf.append("                ");
        for (; k >= 4; k -= 4) buf.append("    ");
        for (; k > 0; k--) buf.append(' ');
      } else if (s.length() > w) {
        if (w > 1) buf.append(s.substring(0, w - 1));
        if (w > 0) buf.append('&');
      } else {
        buf.append(s);
      }
    }

    buf.setLength(Math.min(rowLen, 1024));
    indentedPrintLine(out, indentLevel, buf);

    // now print a row of '-'s
    for (int i = 0; i < Math.min(rowLen, 1024); i++) buf.setCharAt(i, '-');
    indentedPrintLine(out, indentLevel, buf);

    buf = null;

    return rowLen;
  } // DisplayBanner
Ejemplo n.º 14
0
  private static int indent_DisplayBanner(
      PrintStream out,
      ResultSetMetaData rsmd,
      int indentLevel,
      int[] displayColumns,
      int[] displayColumnWidths)
      throws SQLException {

    StringBuffer buf = new StringBuffer();

    int numCols = displayColumnWidths.length;
    int rowLen;

    // do some precalculation so the buffer is allocated only once
    // buffer is twice as long as the display length plus one for a newline
    rowLen = (numCols - 1); // for the column separators
    for (int i = 1; i <= numCols; i++) {
      rowLen += displayColumnWidths[i - 1];
    }
    buf.ensureCapacity(rowLen);

    // get column header info
    // truncate it to the column display width
    // add a bar between each item.
    for (int i = 1; i <= numCols; i++) {
      int colnum = displayColumns == null ? i : displayColumns[i - 1];

      if (i > 1) buf.append('|');

      String s = rsmd.getColumnLabel(colnum);

      int w = displayColumnWidths[i - 1];

      if (s.length() < w) {
        // build a string buffer to hold the whitespace
        StringBuffer blanks = new StringBuffer(s);
        blanks.ensureCapacity(w);

        // try to paste on big chunks of space at a time.
        for (int k = blanks.length() + 64; k <= w; k += 64)
          blanks.append("                                                                ");
        for (int k = blanks.length() + 16; k <= w; k += 16) blanks.append("                ");
        for (int k = blanks.length() + 4; k <= w; k += 4) blanks.append("    ");
        for (int k = blanks.length(); k < w; k++) blanks.append(' ');

        buf.append(blanks);
        // REMIND: could do more cleverness, like keep around
        // past buffers to reuse...
      } else if (s.length() > w) {
        if (w > 1) buf.append(s.substring(0, w - 1));
        if (w > 0) buf.append('&');
      } else {
        buf.append(s);
      }
    }

    buf.setLength(Math.min(rowLen, 1024));
    indentedPrintLine(out, indentLevel, buf);

    // now print a row of '-'s
    for (int i = 0; i < Math.min(rowLen, 1024); i++) buf.setCharAt(i, '-');
    indentedPrintLine(out, indentLevel, buf);

    buf = null;

    return rowLen;
  } // DisplayBanner
Ejemplo n.º 15
0
  /*
   * Analog of replace_glob() in jsstr.c
   */
  private static void replace_glob(
      GlobData rdata, Context cx, Scriptable scope, RegExpImpl reImpl, int leftIndex, int leftlen) {
    int replen;
    String lambdaStr;
    if (rdata.lambda != null) {
      // invoke lambda function with args lastMatch, $1, $2, ... $n,
      // leftContext.length, whole string.
      SubString[] parens = reImpl.parens;
      int parenCount = (parens == null) ? 0 : parens.length;
      Object[] args = new Object[parenCount + 3];
      args[0] = reImpl.lastMatch.toString();
      for (int i = 0; i < parenCount; i++) {
        SubString sub = parens[i];
        if (sub != null) {
          args[i + 1] = sub.toString();
        } else {
          args[i + 1] = Undefined.instance;
        }
      }
      args[parenCount + 1] = new Integer(reImpl.leftContext.length);
      args[parenCount + 2] = rdata.str;
      // This is a hack to prevent expose of reImpl data to
      // JS function which can run new regexps modifing
      // regexp that are used later by the engine.
      // TODO: redesign is necessary
      if (reImpl != ScriptRuntime.getRegExpProxy(cx)) Kit.codeBug();
      RegExpImpl re2 = new RegExpImpl();
      re2.multiline = reImpl.multiline;
      re2.input = reImpl.input;
      ScriptRuntime.setRegExpProxy(cx, re2);
      try {
        Scriptable parent = ScriptableObject.getTopLevelScope(scope);
        Object result = rdata.lambda.call(cx, parent, parent, args);
        lambdaStr = ScriptRuntime.toString(result);
      } finally {
        ScriptRuntime.setRegExpProxy(cx, reImpl);
      }
      replen = lambdaStr.length();
    } else {
      lambdaStr = null;
      replen = rdata.repstr.length();
      if (rdata.dollar >= 0) {
        int[] skip = new int[1];
        int dp = rdata.dollar;
        do {
          SubString sub = interpretDollar(cx, reImpl, rdata.repstr, dp, skip);
          if (sub != null) {
            replen += sub.length - skip[0];
            dp += skip[0];
          } else {
            ++dp;
          }
          dp = rdata.repstr.indexOf('$', dp);
        } while (dp >= 0);
      }
    }

    int growth = leftlen + replen + reImpl.rightContext.length;
    StringBuffer charBuf = rdata.charBuf;
    if (charBuf == null) {
      charBuf = new StringBuffer(growth);
      rdata.charBuf = charBuf;
    } else {
      charBuf.ensureCapacity(rdata.charBuf.length() + growth);
    }

    charBuf.append(reImpl.leftContext.charArray, leftIndex, leftlen);
    if (rdata.lambda != null) {
      charBuf.append(lambdaStr);
    } else {
      do_replace(rdata, cx, reImpl);
    }
  }
Ejemplo n.º 16
0
  /** @param args */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String thisLine = "";
      String numstr = "";
      StringBuffer buf = new StringBuffer();
      buf.ensureCapacity(10000);
      int newLineCountForTerm = 0;

      while ((thisLine = br.readLine()) != null) {
        if (!thisLine.trim().isEmpty()) {
          buf.append(thisLine.replaceAll(",", ""));
          // System.out.println("\n appended" + buf.length());
          newLineCountForTerm = 0;
          thisLine = "";
        } else {
          newLineCountForTerm++;
          if (newLineCountForTerm >= 1) break;
        }
      }

      numstr = buf.toString();
      // numstr = new String(charBuf);
      // System.out.println("\nread string: " + numstr + "\nlength of the number is " +
      // numstr.length() + " digits");

      if (numstr == null || numstr.length() == 0) {
        System.err.println("Please enter a valid number");
        return;
      }

      if (numstr.length() <= 2 && Integer.parseInt(numstr) <= 20) {
        System.out.println(lessthan20[Integer.parseInt(numstr)]);
        return;
      }
      System.out.println("length of the number is " + numstr.length() + " digits");

      // Split the numbers as 3 position numbers and put them in an array
      String numToWord = "";

      // split the numbers as sets of 3 digit numbers and store them in a string array
      ArrayList<String> threedigitSet = new ArrayList<String>();
      String runningNum = numstr, temp = "";
      int runningCount = 0;
      while (runningCount < runningNum.length()) {
        temp = String.valueOf(runningNum.charAt(runningNum.length() - (runningCount + 1))) + temp;
        runningCount++;
        if (runningCount % 3 == 0) {
          threedigitSet.add(temp);
          temp = "";
        }
      }
      if (runningCount % 3 != 0) {
        threedigitSet.add(temp);
      }

      Iterator<String> itr = threedigitSet.iterator();
      int threedigitSetCount = 0;
      boolean nonzero = false;
      while (itr.hasNext()) {
        String numObj = (String) itr.next();
        String threeDigitWord = returnWord(numObj);
        threedigitSetCount++;
        if (Integer.parseInt(numObj) > 0) {
          nonzero = true;
          if (threedigitSetCount == 1) numToWord = threeDigitWord;
          else if (threedigitSetCount > 1)
            numToWord =
                threeDigitWord + " " + Words.highs[threedigitSetCount - 1] + " " + numToWord;
        }
      }
      if (nonzero) {
        int i = 0, len = 20;
        String printStr = "";
        StringTokenizer tokens = new StringTokenizer(numToWord, " ");
        while (tokens.hasMoreTokens()) {
          if (i == 0) printStr = tokens.nextToken();
          else printStr = printStr + " " + tokens.nextToken();
          i++;
          if (i == len) {
            System.out.print(printStr + "\n");
            printStr = "";
            i = 0;
          }
        }

        if (printStr.length() > 0) System.out.print(printStr + "\n");

        // System.out.println(numToWord);
      } else System.out.println("zero");
    } catch (Exception e) {
      System.out.println(
          "Dont you know what an integer is? it doesn't look like you know it.. you Einstein!");
      return;
    }
  }