List of usage examples for java.io Writer toString
public String toString()
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step12GolDataExporter.java
/** * Serializes object to XML//from w ww . j av a 2s . com * * @param object object * @return xml as string * @throws IOException exception */ public static String toXML(Object object) throws IOException { Writer out = new StringWriter(); out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); XStream xStream = getXStream(); xStream.toXML(object, out); IOUtils.closeQuietly(out); return out.toString(); }
From source file:org.datavec.api.transform.ui.HtmlAnalysis.java
public static String createHtmlAnalysisString(DataAnalysis analysis) throws Exception { Configuration cfg = new Configuration(new Version(2, 3, 23)); // Where do we load the templates from: cfg.setClassForTemplateLoading(HtmlAnalysis.class, "/templates/"); // Some other recommended settings: cfg.setIncompatibleImprovements(new Version(2, 3, 23)); cfg.setDefaultEncoding("UTF-8"); cfg.setLocale(Locale.US);//w ww . j ava 2s. com cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Map<String, Object> input = new HashMap<>(); ObjectMapper ret = new ObjectMapper(); ret.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ret.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); ret.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); ret.enable(SerializationFeature.INDENT_OUTPUT); List<ColumnAnalysis> caList = analysis.getColumnAnalysis(); Schema schema = analysis.getSchema(); int n = caList.size(); String[][] table = new String[n][3]; List<DivObject> divs = new ArrayList<>(); List<String> histogramDivNames = new ArrayList<>(); for (int i = 0; i < n; i++) { ColumnAnalysis ca = caList.get(i); String name = schema.getName(i); //namesList.get(i); ColumnType type = schema.getType(i); table[i][0] = name; table[i][1] = type.toString(); table[i][2] = ca.toString().replaceAll(",", ", "); //Hacky work-around to improve display in HTML table double[] buckets; long[] counts; switch (type) { case String: StringAnalysis sa = (StringAnalysis) ca; buckets = sa.getHistogramBuckets(); counts = sa.getHistogramBucketCounts(); break; case Integer: IntegerAnalysis ia = (IntegerAnalysis) ca; buckets = ia.getHistogramBuckets(); counts = ia.getHistogramBucketCounts(); break; case Long: LongAnalysis la = (LongAnalysis) ca; buckets = la.getHistogramBuckets(); counts = la.getHistogramBucketCounts(); break; case Double: DoubleAnalysis da = (DoubleAnalysis) ca; buckets = da.getHistogramBuckets(); counts = da.getHistogramBucketCounts(); break; case Categorical: case Time: case Bytes: buckets = null; counts = null; break; default: throw new RuntimeException("Invalid/unknown column type: " + type); } if (buckets != null) { RenderableComponentHistogram.Builder histBuilder = new RenderableComponentHistogram.Builder(); for (int j = 0; j < counts.length; j++) { histBuilder.addBin(buckets[j], buckets[j + 1], counts[j]); } histBuilder.margins(60, 60, 90, 20); RenderableComponentHistogram hist = histBuilder.title(name).build(); String divName = "histdiv_" + name.replaceAll("\\W", ""); divs.add(new DivObject(divName, ret.writeValueAsString(hist))); histogramDivNames.add(divName); } } //Create the summary table RenderableComponentTable rct = new RenderableComponentTable.Builder().table(table) .header("Column Name", "Column Type", "Column Analysis").backgroundColor("#FFFFFF") .headerColor("#CCCCCC").colWidthsPercent(20, 10, 70).border(1).padLeftPx(4).padRightPx(4).build(); divs.add(new DivObject("tablesource", ret.writeValueAsString(rct))); input.put("divs", divs); input.put("histogramIDs", histogramDivNames); //Current date/time, UTC DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss zzz") .withZone(DateTimeZone.UTC); long currTime = System.currentTimeMillis(); String dateTime = formatter.print(currTime); input.put("datetime", dateTime); Template template = cfg.getTemplate("analysis.ftl"); //Process template to String Writer stringWriter = new StringWriter(); template.process(input, stringWriter); return stringWriter.toString(); }
From source file:Main.java
public static String readSource(final Source sourceToRead) throws TransformerException { // Create transformer final TransformerFactory tff = TransformerFactory.newInstance(); final Transformer tf = tff.newTransformer(); final Writer resultWriter = new StringWriter(); final Result result = new StreamResult(resultWriter); tf.transform(sourceToRead, result);/*www . ja va2s .c o m*/ return resultWriter.toString(); }
From source file:Main.java
public static String createString(Element element) { try {// w ww . ja v a2s. com TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DOMSource source = new DOMSource(element); Writer writer = new StringWriter(); Result result = new StreamResult(writer); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, result); return writer.toString(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return ""; }
From source file:org.nodatime.tzvalidate.DumpCoordinator.java
public static void dump(ZoneTransitionsProvider provider, boolean supportsSource, String[] args) throws ParseException, IOException { DumpOptions options = DumpOptions.parse(provider.getClass().getSimpleName(), args, supportsSource); if (options == null) { return;//from www. j ava 2 s . c o m } provider.initialize(options); List<String> zoneIds = new ArrayList<>(); // Urgh... not quite worth using Guava just for Iterables... for (String id : provider.getZoneIds()) { zoneIds.add(id); } Collections.sort(zoneIds); int fromYear = options.getFromYear(); int toYear = options.getToYear(); String zoneId = options.getZoneId(); boolean includeAbbreviations = options.includeAbbreviations(); // Single zone dump if (zoneId != null) { if (!zoneIds.contains(zoneId)) { System.out.println("Zone " + zoneId + " does not exist"); return; } try (Writer writer = new OutputStreamWriter(System.out, StandardCharsets.UTF_8)) { provider.getTransitions(zoneId, fromYear, toYear).writeTo(writer, includeAbbreviations); } } // All zones, with headers. Writer bodyWriter = new StringWriter(); for (String id : zoneIds) { provider.getTransitions(id, fromYear, toYear).writeTo(bodyWriter, includeAbbreviations); bodyWriter.write("\n"); } bodyWriter.flush(); String text = bodyWriter.toString(); try (Writer overallWriter = new OutputStreamWriter(System.out, StandardCharsets.UTF_8)) { writeHeaders(text, provider, options, overallWriter); overallWriter.write(text); } }
From source file:com.ln.methods.Getcalendar.java
public static void Main() { //TODO store file locally and check if file changed == redownload try {/*from ww w . j a va 2 s. c o m*/ //Get source // System.setProperty("http.agent", "lnrev2"); URL calendar = new URL(Calendarurl); HttpURLConnection getsource = (HttpURLConnection) calendar.openConnection(); InputStream in = new BufferedInputStream(getsource.getInputStream()); //Write source Writer sw = new StringWriter(); char[] b = new char[1024]; Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); int n; while ((n = reader.read(b)) != -1) { sw.write(b, 0, n); } //Source == String && Send source for parsing Parser.source = sw.toString(); Betaparser.source = sw.toString(); //String lol = sw.toString(); //lol = StringUtils.substringBetween(lol, "<month year=\"2012\" num=\"2\">", "</month>"); //Parser.parse(); Betaparser.parse(); } catch (MalformedURLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, e.getStackTrace(), "Error", JOptionPane.WARNING_MESSAGE); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, e.getStackTrace(), "Error", JOptionPane.WARNING_MESSAGE); } }
From source file:gr.abiss.calipso.util.XmlUtils.java
/** * Removes XSS threats from input HTML//from ww w. j a va 2s.com * * @param s the String to transform * @return the transformed String */ public static String removeXss(String s) { if (s == null) { return null; } Writer sw = new StringWriter(); // ignore output try { DeXSS xss = DeXSS.createInstance(null, sw); xss.process(s); sw.close(); s = sw.toString(); } catch (Exception e) { throw new RuntimeException(e); } //System.out.println("Output HTML: \n"+s); return s; }
From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java
/** * Format the given XML document.// w w w. j a v a 2s . c om * * @param xml * @return * @throws SiteWhereException */ public static String format(Document xml) throws SiteWhereException { try { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Writer out = new StringWriter(); tf.transform(new DOMSource(xml), new StreamResult(out)); return out.toString(); } catch (Exception e) { throw new SiteWhereException("Unable to format XML document.", e); } }
From source file:FileUtil.java
/** * Returns the full contents of the Reader as a String. * * @since 1.5.8/*from ww w . j a v a 2 s. co m*/ * @param in The reader from which the contents shall be read. * @return String read from the Reader * @throws IOException If reading fails. */ public static String readContents(Reader in) throws IOException { Writer out = null; try { out = new StringWriter(); copyContents(in, out); return out.toString(); } finally { try { out.close(); } catch (Exception e) { System.out.println("Not able to close the stream while reading contents."); } } }
From source file:io.selendroid.server.inspector.TreeUtil.java
public static String getXMLSource(JSONObject source) { Document document = JsonXmlUtil.buildXmlDocument(source); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = null; try {/*from ww w. j a v a 2s . c o m*/ transformer = tFactory.newTransformer(); } catch (TransformerConfigurationException e) { throw new SelendroidException(e); } transformer.setParameter("encoding", "UTF-8"); DOMSource domSource = new DOMSource(document); Writer outWriter = new StringWriter(); StreamResult result = new StreamResult(outWriter); try { transformer.transform(domSource, result); } catch (TransformerException e) { throw new SelendroidException(e); } return outWriter.toString(); }