List of usage examples for java.io ByteArrayOutputStream toString
@Deprecated public synchronized String toString(int hibyte)
From source file:net.sourceforge.fenixedu.util.tests.ResponseExternalization.java
public static String externalize(Response source) { ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder(out); encoder.writeObject(source);// w w w . j a v a 2 s. c o m encoder.close(); try { // I think that this is wrong and that we should get the // bytes of the ByteArrayOutputStream interpreted as // UTF-8, which is what the XMLEncoder produces in the // first place. // WARNING: If this is changed, the internalize method // should be changed accordingly. return out.toString(Charset.defaultCharset().name()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block logger.error(e.getMessage(), e); return out.toString(); } }
From source file:dk.hippogrif.prettyxml.PrettyPrint.java
/** * Do the prettyprint according to properties. * * @param input holds xml document as text if present * @return prettyprinted document as text if input param present * @throws Exception if something goes wrong *///from w w w . j av a2 s .c o m public static String execute(Properties prop, String input) throws Exception { try { checkProperties(prop, true); logger.log(Level.FINEST, "input=" + input + " properties=" + prop); Format format = initFormat(prop); PrettyXMLOutputter outp = new PrettyXMLOutputter(format); outp.setSortAttributes(prop.containsKey(SORT_ATTRIBUTES)); outp.setIndentAttributes(prop.containsKey(INDENT_ATTRIBUTES)); SAXBuilder builder = new SAXBuilder(); Document doc; if (input != null) { doc = builder.build(new StringReader(input)); } else if (prop.containsKey(INPUT)) { doc = builder.build(new File(prop.getProperty(INPUT))); } else if (prop.containsKey(URL)) { doc = builder.build(new URL(prop.getProperty(URL))); } else { doc = builder.build(System.in); } if (prop.containsKey(TRANSFORM)) { String[] sa = prop.getProperty(TRANSFORM).split(";"); for (int i = 0; i < sa.length; i++) { XSLTransformer transformer = mkTransformer(sa[i].trim()); doc = transformer.transform(doc); } } if (prop.containsKey(OUTPUT)) { FileOutputStream fos = null; try { fos = new FileOutputStream(new File(prop.getProperty(OUTPUT))); outp.output(doc, fos); } finally { IOUtils.closeQuietly(fos); } } else if (input != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); outp.output(doc, baos); return baos.toString(prop.getProperty(ENCODING, "UTF-8")); } else { outp.output(doc, System.out); } return null; } catch (Exception e) { logger.log(Level.FINER, "properties=" + prop, e); throw e; } }
From source file:Main.java
public static String convertBean2Xml(Object obj) throws IOException { String result = null;/* w w w .j av a2s . c o m*/ try { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos, (String) marshaller.getProperty(Marshaller.JAXB_ENCODING)); xmlStreamWriter.writeStartDocument((String) marshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0"); marshaller.marshal(obj, xmlStreamWriter); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.close(); result = baos.toString("UTF-8"); } catch (JAXBException e) { e.printStackTrace(); return null; } catch (XMLStreamException e) { e.printStackTrace(); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } return result; }
From source file:org.thialfihar.android.apg.pgp.HkpKeyServer.java
private static String readAll(InputStream in, String encoding) throws IOException { ByteArrayOutputStream raw = new ByteArrayOutputStream(); byte buffer[] = new byte[1 << 16]; int n = 0;/*from ww w . j a va 2 s. co m*/ while ((n = in.read(buffer)) != -1) { raw.write(buffer, 0, n); } if (encoding == null) { encoding = "utf8"; } return raw.toString(encoding); }
From source file:dk.statsbiblioteket.util.Files.java
/** * Read a String from the file system, assuming UTF-8. * * @param source where to load the String. * @return the String as stored in the source. * @throws IOException if the String could not be read. *//* w ww .j av a 2s . c o m*/ public static String loadString(File source) throws IOException { if (source.isDirectory()) { throw new IOException("The source '" + source + "' is a folder, while it should be a file"); } InputStream in = new FileInputStream(source); ByteArrayOutputStream out = new ByteArrayOutputStream((int) source.length()); Streams.pipe(in, out); return out.toString("UTF-8"); }
From source file:com.portfolio.data.utils.DomUtils.java
public static String cleanXMLData(String data) throws UnsupportedEncodingException { // data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+data; Tidy tidy = new Tidy(); tidy.setInputEncoding("UTF-8"); tidy.setOutputEncoding("UTF-8"); tidy.setWraplen(Integer.MAX_VALUE); // tidy.setPrintBodyOnly(true); tidy.setXmlOut(true);// w ww .j a va 2 s . co m tidy.setXmlTags(true); tidy.setSmartIndent(true); tidy.setMakeClean(true); tidy.setForceOutput(true); ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes("UTF-8")); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); tidy.parseDOM(inputStream, outputStream); return outputStream.toString("UTF-8"); }
From source file:Main.java
public static String transferXmlToString(Document doc) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try {/*from w w w. j ava 2 s.c o m*/ TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); Properties p = t.getOutputProperties(); p.setProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperties(p); t.transform(new DOMSource(doc), new StreamResult(bos)); } catch (NullPointerException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } String xmlStr = ""; try { xmlStr = bos.toString("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return xmlStr; }
From source file:com.ms.commons.utilities.HttpClientUtils.java
public static String getResponseBodyAsString(HttpMethod method, Integer tryTimes, String responseCharSet, Integer maximumResponseByteSize, Integer soTimeoutMill) { init();/* www . j a v a 2s . c o m*/ if (tryTimes == null) { tryTimes = 1; } if (StringUtils.isBlank(responseCharSet)) { responseCharSet = "utf-8"; } if (maximumResponseByteSize == null) { maximumResponseByteSize = 50 * 1024 * 1024; } if (soTimeoutMill == null) { soTimeoutMill = 20000; } method.getParams().setSoTimeout(soTimeoutMill); InputStream httpInputStream = null; for (int i = 0; i < tryTimes; i++) { try { int responseCode = client.executeMethod(method); if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { if (method instanceof HttpMethodBase) { responseCharSet = ((HttpMethodBase) method).getResponseCharSet(); } int read = 0; byte[] cbuf = new byte[4096]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpInputStream = method.getResponseBodyAsStream(); while ((read = httpInputStream.read(cbuf)) >= 0) { baos.write(cbuf, 0, read); if (baos.size() >= maximumResponseByteSize) { break; } } String content = baos.toString(responseCharSet); return content; } logger.error(String.format( "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode)); return ""; } catch (Exception e) { logger.error("getResponseBodyAsString failed", e); } finally { IOUtils.closeQuietly(httpInputStream); method.releaseConnection(); } } return ""; }
From source file:com.evolveum.midpoint.common.LoggingConfigurationManager.java
public static void configure(LoggingConfigurationType config, String version, OperationResult result) { OperationResult res = result.createSubresult(LoggingConfigurationManager.class.getName() + ".configure"); if (InternalsConfig.avoidLoggingChange) { LOGGER.info(/* w ww . j ava 2s . co m*/ "IGNORING change of logging configuration (current config version: {}, new version {}) because avoidLoggingChange=true", currentlyUsedVersion, version); res.recordNotApplicableIfUnknown(); return; } if (currentlyUsedVersion != null) { LOGGER.info("Applying logging configuration (currently applied version: {}, new version: {})", currentlyUsedVersion, version); } else { LOGGER.info("Applying logging configuration (version {})", version); } currentlyUsedVersion = version; // JUL Bridge initialization was here. (SLF4JBridgeHandler) // But it was moved to a later phase as suggested by http://jira.qos.ch/browse/LOGBACK-740 // Initialize JUL bridge SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); //Get current log configuration LoggerContext lc = (LoggerContext) TraceManager.getILoggerFactory(); //Prepare configurator in current context JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); //Generate configuration file as string String configXml = prepareConfiguration(config); if (LOGGER.isTraceEnabled()) { LOGGER.trace("New logging configuration:"); LOGGER.trace(configXml); } InputStream cis = new ByteArrayInputStream(configXml.getBytes()); LOGGER.info("Resetting current logging configuration"); lc.getStatusManager().clear(); //Set all loggers to error for (Logger l : lc.getLoggerList()) { LOGGER.trace("Disable logger: {}", l); l.setLevel(Level.ERROR); } // Reset configuration lc.reset(); //Switch to new logging configuration lc.setName("MidPoint"); try { configurator.doConfigure(cis); LOGGER.info("New logging configuration applied"); } catch (JoranException e) { System.out.println("Error during applying logging configuration: " + e.getMessage()); LOGGER.error("Error during applying logging configuration: " + e.getMessage(), e); result.createSubresult("Applying logging configuration.").recordFatalError(e.getMessage(), e); } catch (NumberFormatException e) { System.out.println("Error during applying logging configuration: " + e.getMessage()); LOGGER.error("Error during applying logging configuration: " + e.getMessage(), e); result.createSubresult("Applying logging configuration.").recordFatalError(e.getMessage(), e); } //Get messages if error occurred; ByteArrayOutputStream baos = new ByteArrayOutputStream(); StatusPrinter.setPrintStream(new PrintStream(baos)); StatusPrinter.print(lc); String internalLog = null; try { internalLog = baos.toString("UTF8"); } catch (UnsupportedEncodingException e) { // should never happen LOGGER.error("Woops?", e); } if (!StringUtils.isEmpty(internalLog)) { //Parse internal log res.recordSuccess(); String internalLogLines[] = internalLog.split("\n"); for (int i = 0; i < internalLogLines.length; i++) { if (internalLogLines[i].contains("|-ERROR")) res.recordPartialError(internalLogLines[i]); res.appendDetail(internalLogLines[i]); } LOGGER.trace("LogBack internal log:\n{}", internalLog); } else { res.recordSuccess(); } // Initialize JUL bridge SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); return; }
From source file:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java
/** * Utility method which converts an InputStream to a String. * * @param stream/*from w ww.j av a 2s . c om*/ * the InputStream to convert. * @return a String with the InputStream content. * @throws IOException * Signals that an I/O exception has occurred. */ private static String inputStreamToString(InputStream stream) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; String resultString = null; while ((length = stream.read(buffer)) != -1) { result.write(buffer, 0, length); } resultString = result.toString("UTF-8"); return resultString; }