java.io.CharArrayWriter Java Examples

The following examples show how to use java.io.CharArrayWriter. 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 Project: openjdk-jdk9   Author: AdoptOpenJDK   File: DriverManagerTests.java    License: GNU General Public License v2.0 9 votes vote down vote up
/**
 * Create a PrintWriter and use to to send output via DriverManager.println
 * Validate that if you disable the writer, the output sent is not present
 */
@Test
public void tests18() throws Exception {
    CharArrayWriter cw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(cw);
    DriverManager.setLogWriter(pw);
    assertTrue(DriverManager.getLogWriter() == pw);

    DriverManager.println(results[0]);
    DriverManager.setLogWriter(null);
    assertTrue(DriverManager.getLogWriter() == null);
    DriverManager.println(noOutput);
    DriverManager.setLogWriter(pw);
    DriverManager.println(results[1]);
    DriverManager.println(results[2]);
    DriverManager.println(results[3]);
    DriverManager.setLogWriter(null);
    DriverManager.println(noOutput);

    /*
     * Check we do not get the output when the stream is disabled
     */
    BufferedReader reader
            = new BufferedReader(new CharArrayReader(cw.toCharArray()));
    for (String result : results) {
        assertTrue(result.equals(reader.readLine()));
    }
}
 
Example #2
Source Project: baratine   Author: baratine   File: LineMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Filter a stack trace, replacing names.
 */
public void printStackTrace(Throwable e, OutputStream os)
{
  CharArrayWriter writer = new CharArrayWriter();
  PrintWriter pw = new PrintWriter(writer);
  
  e.printStackTrace(pw);

  pw.close();
  char []array = writer.toCharArray();

  CharBuffer cb = filter(array);

  if (os != null) {
    byte []b = cb.toString().getBytes();

    try {
      os.write(b, 0, b.length);
    } catch (IOException e1) {
    }
  } else
    System.out.println(cb);
}
 
Example #3
Source Project: super-cloudops   Author: wl4g   File: SSH2Holders.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get local current user ssh authentication private key of default.
 * 
 * @param host
 * @param user
 * @return
 * @throws Exception
 */
protected final char[] getDefaultLocalUserPrivateKey() throws Exception {
	// Check private key.
	File privateKeyFile = new File(USER_HOME + "/.ssh/id_rsa");
	isTrue(privateKeyFile.exists(), String.format("Not found privateKey for %s", privateKeyFile));

	log.warn("Fallback use local user pemPrivateKey of: {}", privateKeyFile);
	try (CharArrayWriter cw = new CharArrayWriter(); FileReader fr = new FileReader(privateKeyFile.getAbsolutePath())) {
		char[] buff = new char[256];
		int len = 0;
		while ((len = fr.read(buff)) != -1) {
			cw.write(buff, 0, len);
		}
		return cw.toCharArray();
	}
}
 
Example #4
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AbstractAccessLogValve.java    License: MIT License 6 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    String value = null;
    if (requestAttributesEnabled) {
        Object host = request.getAttribute(REMOTE_HOST_ATTRIBUTE);
        if (host != null) {
            value = host.toString();
        }
    }
    if (value == null || value.length() == 0) {
        value = request.getRemoteHost();
    }
    if (value == null || value.length() == 0) {
        value = "-";
    }

    if (ipv6Canonical) {
        value = IPv6Utils.canonize(value);
    }
    buf.append(value);
}
 
Example #5
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: bug8005391.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    int N = 10;

    for (int i = 0; i < N; i++) {
        HTMLEditorKit kit = new HTMLEditorKit();
        Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
        HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
        HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
        HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0);
        parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true);
        htmlReader.flush();
        CharArrayWriter writer = new CharArrayWriter(1000);
        kit.write(writer, doc, 0, doc.getLength());
        writer.flush();

        String result = writer.toString();
        if (!result.contains("<tt><a")) {
            throw new RuntimeException("The <a> and <tt> tags are swapped");
        }
    }
}
 
Example #6
Source Project: Tomcat7.0.67   Author: tryandcatch   File: PageDataImpl.java    License: Apache License 2.0 6 votes vote down vote up
private String escapeCDATA(String text) {
    if( text==null ) return "";
    int len = text.length();
    CharArrayWriter result = new CharArrayWriter(len);
    for (int i=0; i<len; i++) {
        if (((i+2) < len)
                && (text.charAt(i) == ']')
                && (text.charAt(i+1) == ']')
                && (text.charAt(i+2) == '>')) {
            // match found
            result.write(']');
            result.write(']');
            result.write('&');
            result.write('g');
            result.write('t');
            result.write(';');
            i += 2;
        } else {
            result.write(text.charAt(i));
        }
    }
    return result.toString();
}
 
Example #7
Source Project: ccu-historian   Author: mdzio   File: Base64.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static char[] readChars(final File file) {
    final CharArrayWriter caw = new CharArrayWriter();
    try {
        final Reader fr = new FileReader(file);
        final Reader in = new BufferedReader(fr);
        int count;
        final char[] buf = new char[16384];
        while ((count = in.read(buf)) != -1) {
            if (count > 0) {
                caw.write(buf, 0, count);
            }
        }
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return caw.toCharArray();
}
 
Example #8
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AbstractAccessLogValve.java    License: MIT License 6 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    Object value = null;
    if (null != request) {
        HttpSession sess = request.getSession(false);
        if (null != sess) {
            value = sess.getAttribute(header);
        }
    } else {
        value = "??";
    }
    if (value != null) {
        if (value instanceof String) {
            buf.append((String) value);
        } else {
            buf.append(value.toString());
        }
    } else {
        buf.append('-');
    }
}
 
Example #9
Source Project: Tomcat7.0.67   Author: tryandcatch   File: JspC.java    License: Apache License 2.0 6 votes vote down vote up
protected void initWebXml() {
    try {
        if (webxmlLevel >= INC_WEBXML) {
            mapout = openWebxmlWriter(new File(webxmlFile));
            servletout = new CharArrayWriter();
            mappingout = new CharArrayWriter();
        } else {
            mapout = null;
            servletout = null;
            mappingout = null;
        }
        if (webxmlLevel >= ALL_WEBXML) {
            mapout.write(Localizer.getMessage("jspc.webxml.header"));
            mapout.flush();
        } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) {
            mapout.write(Localizer.getMessage("jspc.webinc.header"));
            mapout.flush();
        }
    } catch (IOException ioe) {
        mapout = null;
        servletout = null;
        mappingout = null;
    }
}
 
Example #10
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: ExtendedAccessLogValve.java    License: MIT License 6 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    if (null != response) {
        Iterator<String> iter = response.getHeaders(header).iterator();
        if (iter.hasNext()) {
            StringBuilder buffer = new StringBuilder();
            boolean first = true;
            while (iter.hasNext()) {
                if (first) {
                    first = false;
                } else {
                    buffer.append(",");
                }
                buffer.append(iter.next());
            }
            buf.append(wrap(buffer.toString()));
        }
        return ;
    }
    buf.append("-");
}
 
Example #11
Source Project: openbd-core   Author: OpenBD   File: cfFile.java    License: 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 #12
Source Project: openbd-core   Author: OpenBD   File: cfWDDX.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String cfml2Wddx( cfData _input, int version ) {
 	
	CharArrayWriter	outChar	= new CharArrayWriter( 1024 );
	PrintWriter					out	= new PrintWriter( outChar );

   if ( version > 10 ){
     out.write( "<wddxPacket version='1.1'><h></h><d>" );
     _input.dumpWDDX( version, out );
     out.write( "</d></wddxPacket>" );
   }else{
     out.write( "<wddxPacket version='1.0'><header></header><data>" );
     _input.dumpWDDX( version, out );
     out.write( "</data></wddxPacket>" );
   }
   
	out.flush();
	return outChar.toString();
}
 
Example #13
Source Project: baratine   Author: baratine   File: LineMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Filter a stack trace, replacing names.
 */
public void printStackTrace(Throwable e, PrintWriter os)
{
  CharArrayWriter writer = new CharArrayWriter();
  PrintWriter pw = new PrintWriter(writer);
  
  e.printStackTrace(pw);

  pw.close();
  char []array = writer.toCharArray();

  CharBuffer cb = filter(array);

  if (os != null)
    os.print(cb.toString());
  else
    System.out.println(cb);
}
 
Example #14
Source Project: TrakEM2   Author: trakem2   File: IJError.java    License: GNU General Public License v3.0 6 votes vote down vote up
static public final void print(Throwable e, final boolean stdout) {
	StringBuilder sb = new StringBuilder("==================\nERROR:\n");
	while (null != e) {
		CharArrayWriter caw = new CharArrayWriter();
		PrintWriter pw = new PrintWriter(caw);
		e.printStackTrace(pw);
		String s = caw.toString();
		if (isMacintosh()) {
			if (s.indexOf("ThreadDeath")>0)
				;//return null;
			else s = fixNewLines(s);
		}
		sb.append(s);

		Throwable t = e.getCause();
		if (e == t || null == t) break;
		sb.append("==> Caused by:\n");
		e = t;
	}
	sb.append("==================\n");
	if (stdout) Utils.log2(sb.toString());
	else Utils.log(sb.toString());
}
 
Example #15
Source Project: goclipse   Author: GoClipse   File: StreamUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/** Reads and returns all chars from given reader until an EOF is read.
 * Closes reader afterwards. */
public static CharArrayWriter readAllCharsFromReader(Reader reader) throws IOException {
	try {
		final int BUFFER_SIZE = 1024;
		char[] buffer = new char[BUFFER_SIZE];
		CharArrayWriter chars = new CharArrayWriter();
		
		int read;
		while((read = reader.read(buffer)) != EOF) {
			chars.write(buffer, 0, read);
		}
		return chars;
	} finally {
		reader.close();
	}
}
 
Example #16
Source Project: gson   Author: google   File: JsonParserTest.java    License: 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 #17
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: CR6689809Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public final void testTransform() {

    try {
        StreamSource input = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xml"));
        StreamSource stylesheet = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xsl"));
        CharArrayWriter buffer = new CharArrayWriter();
        StreamResult output = new StreamResult(buffer);

        TransformerFactory.newInstance().newTransformer(stylesheet).transform(input, output);

        Assert.assertEquals(buffer.toString(), "0|1|2|3", "XSLT xsl:key implementation is broken!");
        // expected success
    } catch (Exception e) {
        // unexpected failure
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example #18
Source Project: sofa-hessian   Author: sofastack   File: TestHessian2Servlet.java    License: Apache License 2.0 5 votes vote down vote up
protected String getInputDebug()
{
    CharArrayWriter writer = _threadWriter.get();
    if (writer != null)
        return writer.toString();
    else
        return null;
}
 
Example #19
Source Project: development   Author: servicecatalog   File: OperatorClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleException() {
    final CharArrayWriter err = new CharArrayWriter();
    final OperatorClient client = new OperatorClient(null, null,
            new PrintWriter(err, true));

    final Exception cause1 = new Exception("Cause 1");
    final Exception cause2 = new Exception("Cause 2", cause1);
    final Exception exception = new Exception("Bumm", cause2);
    client.handleException(exception);

    final String expected = "Bumm\ncaused by: Cause 2\ncaused by: Cause 1";
    assertEquals(String.format(expected), err.toString());
}
 
Example #20
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AbstractAccessLogValve.java    License: MIT License 5 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    if (requestAttributesEnabled) {
        Object proto = request.getAttribute(PROTOCOL_ATTRIBUTE);
        if (proto == null) {
            buf.append(request.getProtocol());
        } else {
            buf.append(proto.toString());
        }
    } else {
        buf.append(request.getProtocol());
    }
}
 
Example #21
Source Project: jasperreports   Author: TIBCOSoftware   File: JRResultSetDataSource.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
protected CharArrayReader getArrayReader(Reader reader, long size) throws IOException
{
	char[] buf = new char[8192];
	CharArrayWriter bufWriter = new CharArrayWriter((size > 0) ? (int) size : 8192);
	
	BufferedReader bufReader = new BufferedReader(reader, 8192);
	for (int read = bufReader.read(buf); read > 0; read = bufReader.read(buf))
	{
		bufWriter.write(buf, 0, read);
	}
	bufWriter.flush();
	
	return new CharArrayReader(bufWriter.toCharArray());
}
 
Example #22
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AbstractAccessLogValve.java    License: MIT License 5 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    String query = null;
    if (request != null) {
        query = request.getQueryString();
    }
    if (query != null) {
        buf.append('?');
        buf.append(query);
    }
}
 
Example #23
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AbstractAccessLogValve.java    License: MIT License 5 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    if (request == null) {
        buf.append('-');
    } else {
        Session session = request.getSessionInternal(false);
        if (session == null) {
            buf.append('-');
        } else {
            buf.append(session.getIdInternal());
        }
    }
}
 
Example #24
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AbstractAccessLogValve.java    License: MIT License 5 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    if (request != null) {
        buf.append(request.getRequestURI());
    } else {
        buf.append('-');
    }
}
 
Example #25
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: InjectBytecodes.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Print an integer so that it takes 'length' characters in
 * the output.  Temporary until formatting code is stable.
 */
private void traceFixedWidthInt(int x, int length) {
    if (Inject.verbose) {
        CharArrayWriter baStream = new CharArrayWriter();
        PrintWriter pStream = new PrintWriter(baStream);
        pStream.print(x);
        String str = baStream.toString();
        for (int cnt = length - str.length(); cnt > 0; --cnt)
            trace(" ");
        trace(str);
    }
}
 
Example #26
Source Project: logbook   Author: zalando   File: JacksonJsonFieldBodyFilter.java    License: MIT License 5 votes vote down vote up
public String filter(final String body) {
    try {
        final JsonParser parser = factory.createParser(body);
        
        final CharArrayWriter writer = new CharArrayWriter(body.length() * 2); // rough estimate of final size
        
        final JsonGenerator generator = factory.createGenerator(writer);
        try {
            while(true) {
                JsonToken nextToken = parser.nextToken();
                if(nextToken == null) {
                    break;
                }

                generator.copyCurrentEvent(parser);
                if(nextToken == JsonToken.FIELD_NAME && fields.contains(parser.getCurrentName())) {
                    nextToken = parser.nextToken();
                    generator.writeString(replacement);
                    if(!nextToken.isScalarValue()) {
                        parser.skipChildren(); // skip children
                    }
                }
            }                    
        } finally {
            parser.close();
            
            generator.close();
        }
        
        return writer.toString();
    } catch(final Exception e) {
        log.trace("Unable to filter body for fields {}, compacting result. `{}`", fields, e.getMessage()); 
        return fallbackCompactor.compact(body);
    }
}
 
Example #27
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: AbstractAccessLogValve.java    License: MIT License 5 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    Enumeration<String> iter = request.getHeaders(header);
    if (iter.hasMoreElements()) {
        buf.append(iter.nextElement());
        while (iter.hasMoreElements()) {
            buf.append(',').append(iter.nextElement());
        }
        return;
    }
    buf.append('-');
}
 
Example #28
Source Project: ironjacamar   Author: ironjacamar   File: Tracer.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Throwable to string
 * @param exception The exception
 * @return The string representation
 */
private static synchronized String toString(Throwable exception)
{
   CharArrayWriter caw = new CharArrayWriter();
   PrintWriter pw = new PrintWriter(caw, true);
   exception.printStackTrace(pw);
   pw.flush();

   char[] data = caw.toCharArray();
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < data.length; i++)
   {
      char c = data[i];
      if (c == '\n')
      {
         sb = sb.append('|');
      }
      else if (c == '\r')
      {
         sb = sb.append('/');
      }
      else if (c == '\t')
      {
         sb = sb.append('\\');
      }
      else if (c == ' ')
      {
         sb = sb.append('_');
      }
      else
      {
         sb = sb.append(c);
      }
   }

   return sb.toString();
}
 
Example #29
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: ExtendedAccessLogValve.java    License: MIT License 5 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    ElementTimestampStruct eds = currentDate.get();
    long millis = eds.currentTimestamp.getTime();
    if (date.getTime() > (millis + INTERVAL -1) ||
            date.getTime() < millis) {
        eds.currentTimestamp.setTime(
                date.getTime() - (date.getTime() % INTERVAL));
        eds.currentTimestampString =
            eds.currentTimestampFormat.format(eds.currentTimestamp);
    }
    buf.append(eds.currentTimestampString);
}
 
Example #30
Source Project: framework   Author: ww20081120   File: XmlBeanUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param object 对象
 * @return 返回xmlStr
 * @throws UtilException
 */
public static String object2Xml(final Object object) throws UtilException {
    try {
        JAXBContext context = JAXBContext.newInstance(object.getClass());

        Marshaller marshaller = context.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化输出
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 编码格式,默认为utf-8o
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // 是否省略xml头信息
        Writer writer = new CharArrayWriter();
        XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(writer);
        xmlStreamWriter.writeStartDocument((String) marshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0");

        marshaller.marshal(object, xmlStreamWriter);
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.close();
        String xml = writer.toString();
        xml = StringUtils.replace(xml, "&lt;", "<");
        xml = StringUtils.replace(xml, "&gt;", ">");
        xml = StringUtils.replace(xml, "&amp;", "&");
        xml = StringUtils.replace(xml, "&#xd;", GlobalConstants.BLANK);
        return xml;
    }
    catch (Exception e) {
        throw new UtilException(ErrorCodeDef.XML_TRANS_ERROR, e);
    }

}