Java Code Examples for java.io.CharArrayWriter#reset()

The following examples show how to use java.io.CharArrayWriter#reset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FmHelper.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String checkAndConvertIfMybatisXml(JavaType javaType, CharArrayWriter charArrayWriter,
                                                  boolean isFileExits) throws IOException {
    String gerneratedText = null;
    if (javaType == null) {
        if (GenProperties.daoType == DaoType.mybatis) {
            gerneratedText = charArrayWriter.toString();
            if (gerneratedText.lastIndexOf("</sqlMap>") > 0) {
                gerneratedText = IbatisXmlToMybatis.transformXmlByXslt(gerneratedText);
                charArrayWriter.reset();
                charArrayWriter.write(gerneratedText);
            }
            return gerneratedText;
        }
    }
    
    if (isFileExits) {
        gerneratedText = charArrayWriter.toString(); 
    }
    return gerneratedText;
}
 
Example 2
Source File: ConsolePassword.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public char[] toCharArray()
   throws IOException
{
   System.err.print(PicketBoxMessages.MESSAGES.enterPasswordMessage());
   CharArrayWriter writer = new CharArrayWriter();
   int b;
   while( (b = System.in.read()) >= 0 )
   {
      if( b == '\r' || b == '\n' )
         break;
      writer.write(b);
   }
   char[] password = writer.toCharArray();
   writer.reset();
   for(int n = 0; n < password.length; n ++)
      writer.write('\0');
   return password;
}
 
Example 3
Source File: ScriptEngineTests.java    From luaj with MIT License 5 votes vote down vote up
public void testScriptRedirection() throws ScriptException {
          Reader input = new CharArrayReader("abcdefg\nhijk".toCharArray());
          CharArrayWriter output = new CharArrayWriter();
          CharArrayWriter errors = new CharArrayWriter();
          String script = 
          		"print(\"string written using 'print'\")\n" +
          		"io.write(\"string written using 'io.write()'\\n\")\n" +
          		"io.stdout:write(\"string written using 'io.stdout:write()'\\n\")\n" +
          		"io.stderr:write(\"string written using 'io.stderr:write()'\\n\")\n" +
          		"io.write([[string read using 'io.stdin:read(\"*l\")':]]..io.stdin:read(\"*l\")..\"\\n\")\n";

          // Evaluate script with redirection set
          e.getContext().setReader(input);
          e.getContext().setWriter(output);
          e.getContext().setErrorWriter(errors);
          e.eval(script);
          final String expectedOutput = "string written using 'print'\n"+
          		"string written using 'io.write()'\n"+
          		"string written using 'io.stdout:write()'\n"+
          		"string read using 'io.stdin:read(\"*l\")':abcdefg\n";
          assertEquals(expectedOutput, output.toString());
          final String expectedErrors = "string written using 'io.stderr:write()'\n";
          assertEquals(expectedErrors, errors.toString());

          // Evaluate script with redirection reset
          output.reset();
          errors.reset();
          // e.getContext().setReader(null); // This will block if using actual STDIN
          e.getContext().setWriter(null);
          e.getContext().setErrorWriter(null);
          e.eval(script);
          assertEquals("", output.toString());
          assertEquals("", errors.toString());			
}
 
Example 4
Source File: ScriptEngineTests.java    From luaj with MIT License 5 votes vote down vote up
public void testWriter() throws ScriptException {
          CharArrayWriter output = new CharArrayWriter();
          CharArrayWriter errors = new CharArrayWriter();
          e.getContext().setWriter(output);
          e.getContext().setErrorWriter(errors);
          e.eval("io.write( [[line]] )");
          assertEquals("line", output.toString());
          e.eval("io.write( [[ one\nline two\n]] )");
          assertEquals("line one\nline two\n", output.toString());
          output.reset();
}
 
Example 5
Source File: URLEncoder.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Translates a string into {@code application/x-www-form-urlencoded}
 * format using a specific {@linkplain java.nio.charset.Charset Charset}.
 * This method uses the supplied charset to obtain the bytes for unsafe
 * characters.
 * <p>
 * <em><strong>Note:</strong> The <a href=
 * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
 * World Wide Web Consortium Recommendation</a> states that
 * UTF-8 should be used. Not doing so may introduce incompatibilities.</em>
 *
 * @param   s   {@code String} to be translated.
 * @param charset the given charset
 * @return  the translated {@code String}.
 * @throws NullPointerException if {@code s} or {@code charset} is {@code null}.
 * @see URLDecoder#decode(java.lang.String, java.nio.charset.Charset)
 * @since 10
 */
public static String encode(String s, Charset charset) {
    Objects.requireNonNull(charset, "charset");

    boolean needToChange = false;
    StringBuilder out = new StringBuilder(s.length());
    CharArrayWriter charArrayWriter = new CharArrayWriter();

    for (int i = 0; i < s.length();) {
        int c = (int) s.charAt(i);
        //System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
                needToChange = true;
            }
            //System.out.println("Storing: " + c);
            out.append((char)c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
                 * If this character represents the start of a Unicode
                 * surrogate pair, then pass in two characters. It's not
                 * clear what should be done if a byte reserved in the
                 * surrogate pairs range occurs outside of a legal
                 * surrogate pair. For now, just treat it as if it were
                 * any other character.
                 */
                if (c >= 0xD800 && c <= 0xDBFF) {
                    /*
                      System.out.println(Integer.toHexString(c)
                      + " is high surrogate");
                    */
                    if ( (i+1) < s.length()) {
                        int d = (int) s.charAt(i+1);
                        /*
                          System.out.println("\tExamining "
                          + Integer.toHexString(d));
                        */
                        if (d >= 0xDC00 && d <= 0xDFFF) {
                            /*
                              System.out.println("\t"
                              + Integer.toHexString(d)
                              + " is low surrogate");
                            */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));

            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // converting to use uppercase letter as part of
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange = true;
        }
    }

    return (needToChange? out.toString() : s);
}
 
Example 6
Source File: URLEncoder.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Encode a string according to RFC 1738.
 * <p/>
 * <quote> "...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed],
 * and reserved characters used for their reserved purposes may be used unencoded within a URL."</quote>
 * <p/>
 * <ul> <li><p>The ASCII characters 'a' through 'z', 'A' through 'Z', and '0' through '9' remain the same.
 * <p/>
 * <li><p>The unreserved characters - _ . ! ~ * ' ( ) remain the same.
 * <p/>
 * <li><p>All other ASCII characters are converted into the 3-character string "%xy", where xy is the two-digit
 * hexadecimal representation of the character code
 * <p/>
 * <li><p>All non-ASCII characters are encoded in two steps: first to a sequence of 2 or 3 bytes, using the UTF-8
 * algorithm; secondly each of these bytes is encoded as "%xx". </ul>
 * <p/>
 * This method was adapted from http://www.w3.org/International/URLUTF8Encoder.java Licensed under
 * http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
 *
 * @param s The string to be encoded
 * @return The encoded string
 */

public static String encode( final String s, String enc )
  throws UnsupportedEncodingException {
  boolean needToChange = false;
  final StringBuffer sbuf = new StringBuffer( s.length() );
  final char[] sChars = s.toCharArray();
  final int len = sChars.length;
  Charset charset = charset = Charset.forName( enc );
  CharArrayWriter charArrayWriter = new CharArrayWriter();

  for ( int i = 0; i < len; ) {
    int c = sChars[ i ];
    if ( dontNeedEncoding.get( c ) ) {
      sbuf.append( (char) c );
      i++;
    } else {    // other ASCII
      // convert to external encoding before hex conversion
      do {
        charArrayWriter.write( c );
                  /*
                   * If this character represents the start of a Unicode
                   * surrogate pair, then pass in two characters. It's not
                   * clear what should be done if a bytes reserved in the
                   * surrogate pairs range occurs outside of a legal
                   * surrogate pair. For now, just treat it as if it were
                   * any other character.
                   */
        if ( c >= 0xD800 && c <= 0xDBFF ) {
                      /*
                        System.out.println(Integer.toHexString(c)
                        + " is high surrogate");
                      */
          if ( ( i + 1 ) < s.length() ) {
            int d = (int) s.charAt( i + 1 );
                          /*
                            System.out.println("\tExamining "
                            + Integer.toHexString(d));
                          */
            if ( d >= 0xDC00 && d <= 0xDFFF ) {
                              /*
                                System.out.println("\t"
                                + Integer.toHexString(d)
                                + " is low surrogate");
                              */
              charArrayWriter.write( d );
              i++;
            }
          }
        }
        i++;
      } while ( i < s.length() && !dontNeedEncoding.get( ( c = (int) s.charAt( i ) ) ) );

      charArrayWriter.flush();
      String str = new String( charArrayWriter.toCharArray() );
      byte[] ba = str.getBytes( charset );
      for ( int j = 0; j < ba.length; j++ ) {
        sbuf.append( '%' );
        char ch = Character.forDigit( ( ba[ j ] >> 4 ) & 0xF, 16 );
        // converting to use uppercase letter as part of
        // the hex value if ch is a letter.
        if ( Character.isLetter( ch ) ) {
          ch -= caseDiff;
        }
        sbuf.append( ch );
        ch = Character.forDigit( ba[ j ] & 0xF, 16 );
        if ( Character.isLetter( ch ) ) {
          ch -= caseDiff;
        }
        sbuf.append( ch );
      }
      charArrayWriter.reset();
      needToChange = true;
    }
  }
  return ( needToChange ? sbuf.toString() : s );
}