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

The following examples show how to use java.io.CharArrayWriter#write() . 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: Parser.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private String parseScriptText(String tx) {
    CharArrayWriter cw = new CharArrayWriter();
    int size = tx.length();
    int i = 0;
    while (i < size) {
        char ch = tx.charAt(i);
        if (i + 2 < size && ch == '%' && tx.charAt(i + 1) == '\\'
                && tx.charAt(i + 2) == '>') {
            cw.write('%');
            cw.write('>');
            i += 3;
        } else {
            cw.write(ch);
            ++i;
        }
    }
    cw.close();
    return cw.toString();
}
 
Example 2
Source File: PathFilter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
		throws IOException, ServletException {
	if (req instanceof HttpServletRequest) {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String path = request.getContextPath();

		PrintWriter out = response.getWriter();
		CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
		filterChain.doFilter(request, wrapper);
		CharArrayWriter caw = new CharArrayWriter();
		caw.write(wrapper.toString().replace("${path}", path));
		String result = caw.toString();
		response.setContentLength(result.length());
		out.write(result);
	}
}
 
Example 3
Source File: cfFile.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private static boolean isCFENCODED(Reader _inFile) throws IOException {
	CharArrayWriter buffer = new CharArrayWriter(CFENCODE_HEADER_LEN);

	_inFile.mark(CFENCODE_HEADER_LEN);

	for (int i = 0; i < CFENCODE_HEADER_LEN; i++) {
		buffer.write(_inFile.read());
	}

	if (buffer.toString().equals(CFENCODE_HEADER)) {
		return true;
	}

	_inFile.reset();
	return false;
}
 
Example 4
Source File: Parser.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private String parseScriptText(String tx) {
CharArrayWriter cw = new CharArrayWriter();
int size = tx.length();
int i = 0;
while (i < size) {
    char ch = tx.charAt(i);
    if (i+2 < size && ch == '%' && tx.charAt(i+1) == '\\'
	    && tx.charAt(i+2) == '>') {
	cw.write('%');
	cw.write('>');
	i += 3;
    } else {
	cw.write(ch);
	++i;
    }
}
cw.close();
return cw.toString();
   }
 
Example 5
Source File: JsonParserTest.java    From gson with Apache License 2.0 6 votes vote down vote up
public void testReadWriteTwoObjects() throws Exception {
  Gson gson = new Gson();
  CharArrayWriter writer = new CharArrayWriter();
  BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one");
  writer.write(gson.toJson(expectedOne).toCharArray());
  BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two");
  writer.write(gson.toJson(expectedTwo).toCharArray());
  CharArrayReader reader = new CharArrayReader(writer.toCharArray());

  JsonReader parser = new JsonReader(reader);
  parser.setLenient(true);
  JsonElement element1 = Streams.parse(parser);
  JsonElement element2 = Streams.parse(parser);
  BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
  assertEquals("one", actualOne.stringValue);
  BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
  assertEquals("two", actualTwo.stringValue);
}
 
Example 6
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 7
Source File: Parser.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private String parseScriptText(String tx) {
    CharArrayWriter cw = new CharArrayWriter();
    int size = tx.length();
    int i = 0;
    while (i < size) {
        char ch = tx.charAt(i);
        if (i + 2 < size && ch == '%' && tx.charAt(i + 1) == '\\'
                && tx.charAt(i + 2) == '>') {
            cw.write('%');
            cw.write('>');
            i += 3;
        } else {
            cw.write(ch);
            ++i;
        }
    }
    cw.close();
    return cw.toString();
}
 
Example 8
Source File: JspReader.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
String getText(Mark start, Mark stop) throws JasperException {
Mark oldstart = mark();
reset(start);
CharArrayWriter caw = new CharArrayWriter();
while (!stop.equals(mark()))
    caw.write(nextChar());
caw.close();
reset(oldstart);
return caw.toString();
   }
 
Example 9
Source File: Bug2928673.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (response instanceof HttpServletResponse) {
        final PrintWriter out = response.getWriter();
        final HttpServletResponse wrapper = (HttpServletResponse) response;
        chain.doFilter(request, wrapper);
        final String origData = wrapper.getContentType();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Hello");
        }
        if ("text/html".equals(wrapper.getContentType())) {
            final CharArrayWriter caw = new CharArrayWriter();
            final int bodyIndex = origData.indexOf("</body>");
            if (-1 != bodyIndex) {
                caw.write(origData.substring(0, bodyIndex - 1));
                caw.write("\n<p>My custom footer</p>");
                caw.write("\n</body></html>");
                response.setContentLength(caw.toString().length());
                out.write(caw.toString());
            } else {
                out.write(origData);
            }
        } else {
            out.write(origData);
        }
        out.close();
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 10
Source File: ReadersWritersTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testReadWriteTwoObjects() throws IOException {
  Gson gson= new Gson();
  CharArrayWriter writer= new CharArrayWriter();
  BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one");
  writer.write(gson.toJson(expectedOne).toCharArray());
  BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two");
  writer.write(gson.toJson(expectedTwo).toCharArray());
  CharArrayReader reader = new CharArrayReader(writer.toCharArray());
  JsonStreamParser parser = new JsonStreamParser(reader);
  BagOfPrimitives actualOne = gson.fromJson(parser.next(), BagOfPrimitives.class);
  assertEquals("one", actualOne.stringValue);
  BagOfPrimitives actualTwo = gson.fromJson(parser.next(), BagOfPrimitives.class);
  assertEquals("two", actualTwo.stringValue);
  assertFalse(parser.hasNext());
}
 
Example 11
Source File: SettingsRecognizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Read a maximal string until delim is encountered (which will be removed from stream).
 * This impl reads only ASCII, for speed.
 * Newline conventions are normalized to Unix \n.
 * @return the read string, or null if the delim is not encountered before EOF.
 */
private String readTo(InputStream is, char delim) throws IOException {
    if (delim == 10) {
        // Not implemented - stream might have "foo\r\n" and we would
        // return "foo" and leave "\n" in the stream.
        throw new IOException("Not implemented"); // NOI18N
    }
    CharArrayWriter caw = new CharArrayWriter(100);
    boolean inNewline = false;
    while (true) {
        int c = is.read();
        if (c == -1) return null;
        if (c > 126) return null;
        if (c == 10 || c == 13) {
            // Normalize: s/[\r\n]+/\n/g
            if (inNewline) {
                continue;
            } else {
                inNewline = true;
                c = 10;
            }
        } else if (c < 32 && c != 9) {
            // Random control character!
            return null;
        } else {
            inNewline = false;
        }
        if (c == delim) {
            return caw.toString();
        } else {
            caw.write(c);
        }
    }
}
 
Example 12
Source File: IOUtils.java    From JMCCC with MIT License 5 votes vote down vote up
public static String toString(InputStream in) throws IOException {
	CharArrayWriter w = new CharArrayWriter();
	Reader reader = new InputStreamReader(in, "UTF-8");
	char[] buf = new char[4096]; // 8192 bytes
	int read;
	while ((read = reader.read(buf)) != -1) {
		w.write(buf, 0, read);
	}
	return new String(w.toCharArray());
}
 
Example 13
Source File: JFCParser.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static String readContent(Reader r) throws IOException {
    CharArrayWriter writer = new CharArrayWriter(1024);
    int count = 0;
    int ch;
    while ((ch = r.read()) != -1) {
        writer.write(ch);
        count++;
        if (count >= MAXIMUM_FILE_SIZE) {
            throw new IOException("Presets with more than " + MAXIMUM_FILE_SIZE + " characters can't be read.");
        }
    }
    return new String(writer.toCharArray());
}
 
Example 14
Source File: JFCParser.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static String readContent(Reader r) throws IOException {
    CharArrayWriter writer = new CharArrayWriter(1024);
    int count = 0;
    int ch;
    while ((ch = r.read()) != -1) {
        writer.write(ch);
        count++;
        if (count >= MAXIMUM_FILE_SIZE) {
            throw new IOException("Presets with more than " + MAXIMUM_FILE_SIZE + " characters can't be read.");
        }
    }
    return new String(writer.toCharArray());
}
 
Example 15
Source File: cfStringData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public static cfStringData getString( Reader in ) throws IOException {
	CharArrayWriter out = new CharArrayWriter();
	char temp[] = new char[ 2048 ];
	int charsRead;
       
	while ( ( charsRead = in.read( temp ) ) != -1 )
		out.write( temp, 0, charsRead );
       
	return new cfStringData( out.toCharArray() );
}
 
Example 16
Source File: JspReader.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
String getText(Mark start, Mark stop) {
    Mark oldstart = mark();
    reset(start);
    CharArrayWriter caw = new CharArrayWriter();
    while (!markEquals(stop)) {
        caw.write(nextChar());
    }
    caw.close();
    setCurrent(oldstart);
    return caw.toString();
}
 
Example 17
Source File: JspReader.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Constructor: same as above constructor but with initialized reader
 * to the file given.
 *
 * @param ctxt   The compilation context
 * @param fname  The file name
 * @param reader A reader for the JSP source file
 * @param err The error dispatcher
 *
 * @throws JasperException If an error occurs parsing the JSP file
 */
public JspReader(JspCompilationContext ctxt,
                 String fname,
                 InputStreamReader reader,
                 ErrorDispatcher err)
        throws JasperException {

    this.context = ctxt;
    this.err = err;

    try {
        CharArrayWriter caw = new CharArrayWriter();
        char buf[] = new char[1024];
        for (int i = 0 ; (i = reader.read(buf)) != -1 ;)
            caw.write(buf, 0, i);
        caw.close();
        current = new Mark(this, caw.toCharArray(), fname);
    } catch (Throwable ex) {
        ExceptionUtils.handleThrowable(ex);
        log.error("Exception parsing file ", ex);
        err.jspError("jsp.error.file.cannot.read", fname);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception any) {
                if(log.isDebugEnabled()) {
                    log.debug("Exception closing reader: ", any);
                }
            }
        }
    }
}
 
Example 18
Source File: cfParseTag.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
private cfTag createCFOutputRails(tagReader _inFile, CharArrayWriter _tagBuffer) {
	cfTag	tagInst	= new cfOUTPUTRails();
	tagClass.tagList.add(tagInst);
	_tagBuffer.write(cfTag.TAG_MARKER);
	return tagInst;
}
 
Example 19
Source File: CreateXML.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void processPlan(
    CharArrayWriter out, 
    boolean isLocalPlanExtracted) throws SQLException, IOException {

  final boolean current = ds.setRuntimeStatisticsMode(false);

  try {
    if (!ds.verifySchemaExistance()) {
      throw GemFireXDRuntimeException.newRuntimeException(
          "CreateXML: specified Schema does not exist",
          null);
    }

    if (!ds.initializeDataArray()) {
      if (ds.isRemote()) {
        return;
      }
      if (SanityManager.DEBUG) {
        if (GemFireXDUtils.TracePlanGeneration) {
          SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_PLAN_GENERATION,
              "No statistics were captured in this distributed member for "
                  + ds.getQueryID());
        }
      }
      return;
    }

    ds.createXMLFragment();

    writeToStream(
        out,
        ds.statement(),
        ds.time(),
        ds.begin_end_exe_time(), 
        isLocalPlanExtracted);
    
    // to avoid recursion further.
    if (!isLocalPlanExtracted) {
      BasicUUID locallyExecutedId = new BasicUUID(ds.getQueryID());
      locallyExecutedId.setLocallyExecuted(1);
      if (SanityManager.DEBUG) {
        if (GemFireXDUtils.TracePlanGeneration) {
          SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_PLAN_GENERATION,
              "Now determining locally Executed Plan if any for "
                  + ds.getQueryID() + " with local stmtUUID="
                  + locallyExecutedId.toString());
        }
      }

      new CreateXML(ds.getClone(locallyExecutedId.toString()), true, xmlForm, embedXslFileName)
          .processPlan(out, true);
    }
    else {
      return;
    }

    out.write(parentTagEnd);
    
    if (SanityManager.DEBUG) {
      if (GemFireXDUtils.TracePlanGeneration) {
        SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_PLAN_GENERATION,
            "Returning  " + out.toString());
      }
    }
  } finally {
    ds.closeConnection();
    ds.setRuntimeStatisticsMode(current);
  }
  
}
 
Example 20
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 );
}