List of usage examples for java.io StringWriter StringWriter
public StringWriter()
From source file:com.websocket.server.commons.JsonPojoMapper.java
public static String toJson(Object pojo, boolean prettyPrint) throws JsonMappingException, JsonGenerationException, IOException { StringWriter sw = new StringWriter(); JsonGenerator jsonGen = jsonFactory.createJsonGenerator(sw); if (prettyPrint) { jsonGen.useDefaultPrettyPrinter(); }//w w w . ja v a 2 s . c o m mapper.writeValue(jsonGen, pojo); return sw.toString(); }
From source file:Main.java
public static final void prettyPrint(Document xml) throws Exception { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(xml), new StreamResult(out)); System.out.println(out.toString()); }
From source file:Main.java
public static String nodeListToString(NodeList nodeList) throws TransformerException { StringWriter stringWriter = new StringWriter(); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); if (node instanceof Element) { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(stringWriter)); } else {//from ww w . j a va 2s . c o m stringWriter.append(node.getTextContent()); } } return stringWriter.toString(); }
From source file:Main.java
/** * ***************************************** * Convert XML document to string//from w w w.j a v a 2s . c o m * ******************************************. * * @param xmlDocument the xml document * @return the string * @throws IOException Signals that an I/O exception has occurred. * @throws TransformerException the transformer exception */ public static String converXmlDocToString(Document xmlDocument) throws IOException, TransformerException { String xmlString = ""; TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer)); xmlString = writer.getBuffer().toString().replaceAll("\n|\r", ""); return xmlString; }
From source file:com.kaaprotech.satu.util.CmdLineUtil.java
public static String getCommandLineUsageMessage() { final HelpFormatter formatter = new HelpFormatter(); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); pw.println();/* ww w. j a v a 2 s .c o m*/ formatter.printHelp(pw, 120, "Satu", null, getOptions(), 2, 10, null); return sw.getBuffer().toString(); }
From source file:Main.java
public static String getStringFromXmlDoc(org.w3c.dom.Node node) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.getBuffer().toString().replaceAll("\n|\r", ""); }
From source file:fr.inria.atlanmod.instantiator.neoEMF.Launcher.java
public static void main(String[] args) throws GenerationException, IOException { ResourceSetImpl resourceSet = new ResourceSetImpl(); { // initializing the registry resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX, new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME, NeoEMFResourceFactory.eINSTANCE); }/*from ww w .j a v a 2s. com*/ Options options = new Options(); configureOptions(options); CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS); LOGGER.info("Start loading the package"); Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class); EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null); Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy")); metamodelResource.getContents().add(_package); LOGGER.info("Finish loading the package"); int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE; if (commandLine.hasOption(SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(SIZE); size = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } float variation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION, number.floatValue())); } variation = number.floatValue(); } float propVariation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(PROP_VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", PROP_VARIATION, number.floatValue())); } propVariation = number.floatValue(); } long seed = System.currentTimeMillis(); if (commandLine.hasOption(SEED)) { seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue(); } Range<Integer> range = Range.between(Math.round(size * (1 - variation)), Math.round(size * (1 + variation))); GenericMetamodelConfig config = new GenericMetamodelConfig(metamodelResource, range, seed); GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(config); if (commandLine.hasOption(OUTPUT_PATH)) { String outDir = commandLine.getOptionValue(OUTPUT_PATH); //java.net.URI intermediateURI = java.net.URI.create(outDir); modelGen.setSamplesPath(outDir); } int numberOfModels = 1; if (commandLine.hasOption(N_MODELS)) { numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue(); } int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE); valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(DEGREE); referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } config.setValuesRange(Math.round(valuesSize * (1 - propVariation)), Math.round(valuesSize * (1 + propVariation))); config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); long start = System.currentTimeMillis(); modelGen.runGeneration(resourceSet, numberOfModels, size, variation); long end = System.currentTimeMillis(); LOGGER.info( MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000))); if (commandLine.hasOption(DIAGNOSE)) { for (Resource resource : resourceSet.getResources()) { LOGGER.info( MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI())); BasicDiagnostic diagnosticChain = diagnoseResource(resource); if (!isFailed(diagnosticChain)) { LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''", resource.getURI())); } else { LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''", diagnosticChain.getChildren().size(), resource.getURI())); for (Diagnostic diagnostic : diagnosticChain.getChildren()) { LOGGER.fine(diagnostic.getMessage()); } } } LOGGER.info("Validation finished"); } } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new OptionComarator<Option>()); try { formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80)); } catch (Throwable t) { LOGGER.warning("Unable to get console information"); } ; formatter.printHelp("java -jar <this-file.jar>", options, true); System.exit(ERROR); } catch (ClassNotFoundException t) { System.err.println("ERROR: Unable to load class" + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(stringWriter.toString()); } catch (Throwable t) { System.err.println("ERROR: " + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(t); LOGGER.severe(stringWriter.toString()); System.exit(ERROR); } }
From source file:Main.java
/** * Returns the content of the given node as string */// w ww . j a va 2 s .co m public static String toString(final Node node) { final StringWriter out = new StringWriter(); write(node, new StreamResult(out)); return out.toString(); }
From source file:Main.java
private static String getIndented(Document aDoc) { String outputXml = ""; try {/*from w w w.j a v a 2 s. c o m*/ TransformerFactory tf = TransformerFactory.newInstance(); // tf.setAttribute("indent-number", new Integer(4)); Transformer transformer; transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(aDoc); transformer.transform(source, result); outputXml = result.getWriter().toString(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return outputXml; }
From source file:net.fizzl.redditengine.data.ListMapValue.java
public static List<String> fromInputStream(InputStream is, String name) throws IOException { StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); return fromInputStream(writer.toString(), name); }