Java Code Examples for java.io.StringWriter#toString()

The following examples show how to use java.io.StringWriter#toString() . 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: PathsTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void compile(String... args) {
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-d")) {
            new File(args[++i]).mkdirs();
            break;
        }
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    int rc = com.sun.tools.javac.Main.compile(args, pw);
    pw.close();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (rc != 0)
        error("compilation failed: rc=" + rc);
}
 
Example 2
Source File: XML10IOTest.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
public void testLoadXML10Model() throws ParserConfigurationException, SAXException, IOException,
		TransformerException {

	XMLUtils theUtils = XMLUtils.getInstance();

	DocumentBuilderFactory theFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder theBuilder = theFactory.newDocumentBuilder();
	Document theDoc = theBuilder.parse(getClass().getResourceAsStream("examplemodel.mxm"));
	AbstractXMLModelSerializer theSerializer = new XMLModel10Serializer(theUtils);
	Model theModel = theSerializer.deserializeModelFromXML(theDoc);

	StringWriter theStringWriter = new StringWriter();
	theSerializer.serializeModelToXML(theModel, theStringWriter);

	String theOriginalFile = readResourceFile("examplemodel.mxm");
	String theNewFile = theStringWriter.toString();

	assertTrue(compareStrings(theOriginalFile, theNewFile));
}
 
Example 3
Source File: ExceptionUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Makes a string representation of the exception's stack trace, or "(null)", if the
 * exception is null.
 *
 * <p>This method makes a best effort and never fails.
 *
 * @param e The exception to stringify.
 * @return A string with exception name and call stack.
 */
public static String stringifyException(final Throwable e) {
	if (e == null) {
		return STRINGIFIED_NULL_EXCEPTION;
	}

	try {
		StringWriter stm = new StringWriter();
		PrintWriter wrt = new PrintWriter(stm);
		e.printStackTrace(wrt);
		wrt.close();
		return stm.toString();
	}
	catch (Throwable t) {
		return e.getClass().getName() + " (error while printing stack trace)";
	}
}
 
Example 4
Source File: AlertFactory.java    From Motion_Profile_Generator with MIT License 5 votes vote down vote up
public static Alert createExceptionAlert( Exception e, String msg )
{
    Alert alert = new Alert(Alert.AlertType.ERROR);
    alert.setTitle("Exception Dialog");
    alert.setHeaderText("Whoops!");
    alert.setContentText(msg);

    // Create expandable Exception.
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    String exceptionText = sw.toString();

    Label label = new Label("The exception stacktrace was:");

    TextArea textArea = new TextArea(exceptionText);
    textArea.setEditable(false);
    textArea.setWrapText(true);

    textArea.setMaxWidth(Double.MAX_VALUE);
    textArea.setMaxHeight(Double.MAX_VALUE);
    GridPane.setVgrow(textArea, Priority.ALWAYS);
    GridPane.setHgrow(textArea, Priority.ALWAYS);

    GridPane expContent = new GridPane();
    expContent.setMaxWidth(Double.MAX_VALUE);
    expContent.add(label, 0, 0);
    expContent.add(textArea, 0, 1);

    // Set expandable Exception into the dialog pane.
    alert.getDialogPane().setExpandableContent(expContent);

    return alert;
}
 
Example 5
Source File: XMLUtil.java    From EasyML with Apache License 2.0 5 votes vote down vote up
/** Transform a XML Document to String */
public static String toString(Document doc) {
	try {
		DOMSource domSource = new DOMSource(doc);
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.transform(domSource, result);
		return writer.toString();
	} catch (Exception e) {
		e.printStackTrace();
		return "";
	}
}
 
Example 6
Source File: HTMLHostManagerServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Add a host using the specified parameters.
 *
 * @param request The Servlet request
 * @param name Host name
 * @param smClient StringManager for the client's locale
 * @return output
 */
protected String add(HttpServletRequest request,String name,
        StringManager smClient) {

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    super.add(request,printWriter,name,true, smClient);

    return stringWriter.toString();
}
 
Example 7
Source File: WSEndpointReference.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Dumps the EPR infoset in a human-readable string.
 */
@Override
public String toString() {
    try {
        // debug convenience
        StringWriter sw = new StringWriter();
        XmlUtil.newTransformer().transform(asSource("EndpointReference"),new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        return e.toString();
    }
}
 
Example 8
Source File: GradebookUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static String getStringFromDocument(Document document) throws TransformerException {
DOMSource domSource = new DOMSource(document);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
   }
 
Example 9
Source File: AppExceptionHandler.java    From FakeWeather with Apache License 2.0 5 votes vote down vote up
/**
 * 获取系统未捕捉的错误信息
 *
 * @param throwable
 * @return
 */
private String obtainExceptionInfo(Throwable throwable) {
    StringWriter mStringWriter = new StringWriter();
    PrintWriter mPrintWriter = new PrintWriter(mStringWriter);
    throwable.printStackTrace(mPrintWriter);
    mPrintWriter.close();
    return mStringWriter.toString();
}
 
Example 10
Source File: NodeHandler.java    From smithy with Apache License 2.0 5 votes vote down vote up
@SmithyInternalApi
public static String prettyPrint(Node node, String indentString) {
    StringWriter writer = new StringWriter();
    JsonWriter jsonWriter = new PrettyPrintWriter(writer, indentString);
    node.accept(new NodeWriter(jsonWriter));
    return writer.toString();
}
 
Example 11
Source File: ExceptionUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String formatStackTrace(@Nullable StackTraceElement[] trace, Predicate<StackTraceElement> skipWhile) {
    if(trace == null || trace.length == 0) return "";

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    int i = 0;
    for(; i < trace.length && skipWhile.test(trace[i]); i++);
    for(; i < trace.length; i++) {
        pw.println("\tat " + trace[i]);
    }
    return sw.toString();
}
 
Example 12
Source File: TagletPathTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verify that a taglet can be specified, and located via
 * the file manager's TAGLET_PATH.
 */
@Test
public void testTagletPath() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File tagletSrcFile = new File(testSrc, "taglets/UnderlineTaglet.java");
    File tagletDir = getOutDir("classes");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager cfm = compiler.getStandardFileManager(null, null, null);
    cfm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tagletDir));
    Iterable<? extends JavaFileObject> cfiles = cfm.getJavaFileObjects(tagletSrcFile);
    if (!compiler.getTask(null, cfm, null, null, null, cfiles).call())
        throw new Exception("cannot compile taglet");

    JavaFileObject srcFile = createSimpleJavaFileObject("pkg/C", testSrcText);
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    File outDir = getOutDir("api");
    fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
    fm.setLocation(DocumentationTool.Location.TAGLET_PATH, Arrays.asList(tagletDir));
    Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
    Iterable<String> options = Arrays.asList("-taglet", "UnderlineTaglet");
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    DocumentationTask t = tool.getTask(pw, fm, null, null, options, files);
    boolean ok = t.call();
    String out = sw.toString();
    System.err.println(">>" + out + "<<");
    if (ok) {
        File f = new File(outDir, "pkg/C.html");
        List<String> doc = Files.readAllLines(f.toPath(), Charset.defaultCharset());
        for (String line: doc) {
            if (line.contains("<u>" + TEST_STRING + "</u>")) {
                System.err.println("taglet executed as expected");
                return;
            }
        }
        error("expected text not found in output " + f);
    } else {
        error("task failed");
    }
}
 
Example 13
Source File: TestTableMetadataJson.java    From iceberg with Apache License 2.0 4 votes vote down vote up
public static String toJsonWithoutSpecList(TableMetadata metadata) {
  StringWriter writer = new StringWriter();
  try {
    JsonGenerator generator = JsonUtil.factory().createGenerator(writer);

    generator.writeStartObject(); // start table metadata object

    generator.writeNumberField(FORMAT_VERSION, TableMetadata.TABLE_FORMAT_VERSION);
    generator.writeStringField(LOCATION, metadata.location());
    generator.writeNumberField(LAST_UPDATED_MILLIS, metadata.lastUpdatedMillis());
    generator.writeNumberField(LAST_COLUMN_ID, metadata.lastColumnId());

    generator.writeFieldName(SCHEMA);
    SchemaParser.toJson(metadata.schema(), generator);

    // mimic an old writer by writing only partition-spec and not the default ID or spec list
    generator.writeFieldName(PARTITION_SPEC);
    PartitionSpecParser.toJsonFields(metadata.spec(), generator);

    generator.writeObjectFieldStart(PROPERTIES);
    for (Map.Entry<String, String> keyValue : metadata.properties().entrySet()) {
      generator.writeStringField(keyValue.getKey(), keyValue.getValue());
    }
    generator.writeEndObject();

    generator.writeNumberField(CURRENT_SNAPSHOT_ID,
        metadata.currentSnapshot() != null ? metadata.currentSnapshot().snapshotId() : -1);

    generator.writeArrayFieldStart(SNAPSHOTS);
    for (Snapshot snapshot : metadata.snapshots()) {
      SnapshotParser.toJson(snapshot, generator);
    }
    generator.writeEndArray();

    // skip the snapshot log

    generator.writeEndObject(); // end table metadata object

    generator.flush();
  } catch (IOException e) {
    throw new RuntimeIOException(e, "Failed to write json for: %s", metadata);
  }
  return writer.toString();
}
 
Example 14
Source File: TagletPathTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verify that a taglet can be specified, and located via
 * the file manager's TAGLET_PATH.
 */
@Test
public void testTagletPath() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File tagletSrcFile = new File(testSrc, "taglets/UnderlineTaglet.java");
    File tagletDir = getOutDir("classes");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager cfm = compiler.getStandardFileManager(null, null, null)) {
        cfm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tagletDir));
        Iterable<? extends JavaFileObject> cfiles = cfm.getJavaFileObjects(tagletSrcFile);
        if (!compiler.getTask(null, cfm, null, null, null, cfiles).call())
            throw new Exception("cannot compile taglet");
    }

    JavaFileObject srcFile = createSimpleJavaFileObject("pkg/C", testSrcText);
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File outDir = getOutDir("api");
        fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
        fm.setLocation(DocumentationTool.Location.TAGLET_PATH, Arrays.asList(tagletDir));
        Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
        Iterable<String> options = Arrays.asList("-taglet", "UnderlineTaglet");
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        DocumentationTask t = tool.getTask(pw, fm, null, com.sun.tools.doclets.standard.Standard.class, options, files);
        boolean ok = t.call();
        String out = sw.toString();
        System.err.println(">>" + out + "<<");
        if (ok) {
            File f = new File(outDir, "pkg/C.html");
            List<String> doc = Files.readAllLines(f.toPath(), Charset.defaultCharset());
            for (String line: doc) {
                if (line.contains("<u>" + TEST_STRING + "</u>")) {
                    System.err.println("taglet executed as expected");
                    return;
                }
            }
            error("expected text not found in output " + f);
        } else {
            error("task failed");
        }
    }
}
 
Example 15
Source File: GenerateRaw.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void doOne(TestCase tc) throws Exception {
  String inputpath = tc.inputpath();
  String dappath;
  String dmrpath;
  if (USEDAPDMR) {
    dappath = tc.generatepath(DAPDIR) + ".dap";
    dmrpath = tc.generatepath(DMRDIR) + ".dmr";
  } else {
    dappath = tc.generatepath(RAWDIR) + ".dap";
    dmrpath = tc.generatepath(RAWDIR) + ".dmr";
  }

  String url = tc.makeurl();

  String ce = tc.makequery();

  System.err.println("Input: " + inputpath);
  System.err.println("Generated (DMR):" + dmrpath);
  System.err.println("Generated (DAP):" + dappath);
  System.err.println("URL: " + url);
  if (ce != null)
    System.err.println("CE: " + ce);

  if (CEPARSEDEBUG)
    CEParserImpl.setGlobalDebugLevel(1);

  String little = tc.bigendian ? "0" : "1";
  String nocsum = tc.nochecksum ? "1" : "0";
  MvcResult result;
  if (ce == null) {
    result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum,
        DapTestCommon.TRANSLATETAG, "nc4");
  } else {
    result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.CONSTRAINTTAG, ce, DapTestCommon.ORDERTAG, little,
        DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TRANSLATETAG, "nc4");
  }

  // Collect the output
  MockHttpServletResponse res = result.getResponse();
  byte[] byteresult = res.getContentAsByteArray();

  if (prop_debug || DEBUGDATA) {
    DapDump.dumpbytestream(byteresult, ByteOrder.nativeOrder(), "GenerateRaw");
  }

  // Dump the dap serialization into a file
  if (prop_generate || GENERATE)
    writefile(dappath, byteresult);

  // Dump the dmr into a file by extracting from the dap serialization
  ByteArrayInputStream bytestream = new ByteArrayInputStream(byteresult);
  ChunkInputStream reader = new ChunkInputStream(bytestream, RequestMode.DAP, ByteOrder.nativeOrder());
  String sdmr = reader.readDMR(); // Read the DMR
  if (prop_generate || GENERATE)
    writefile(dmrpath, sdmr);

  if (prop_visual) {
    visual(tc.dataset + ".dmr", sdmr);
    FileDSP src = new FileDSP();
    src.open(byteresult);
    StringWriter writer = new StringWriter();
    DSPPrinter printer = new DSPPrinter(src, writer);
    printer.print();
    printer.close();
    writer.close();
    String sdata = writer.toString();
    visual(tc.dataset + ".dap", sdata);
  }
}
 
Example 16
Source File: SourceModel.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public String toString() {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    generate(pw);
    return sw.toString();
}
 
Example 17
Source File: Utils.java    From smart-cache with Apache License 2.0 4 votes vote down vote up
public static String getStackTrace(Throwable ex) {
    StringWriter buf = new StringWriter();
    ex.printStackTrace(new PrintWriter(buf));

    return buf.toString();
}
 
Example 18
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "crawler")
public void testFile(String fileName) throws IOException {
    File file = getSourceFile(fileName);
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    boolean success = true;
    StringWriter writer = new StringWriter();
    writer.write("Testing : " + file.toString() + "\n");
    String text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    Trees trees = Trees.instance(task);
    SourcePositions sp = trees.getSourcePositions();

    for (CompilationUnitTree cut : asts) {
        for (ImportTree imp : cut.getImports()) {
            success &= testStatement(writer, sp, text, cut, imp);
        }
        for (Tree decl : cut.getTypeDecls()) {
            success &= testStatement(writer, sp, text, cut, decl);
            if (decl instanceof ClassTree) {
                ClassTree ct = (ClassTree) decl;
                for (Tree mem : ct.getMembers()) {
                    if (mem instanceof MethodTree) {
                        MethodTree mt = (MethodTree) mem;
                        BlockTree bt = mt.getBody();
                        // No abstract methods or constructors
                        if (bt != null && mt.getReturnType() != null) {
                            // The modifiers synchronized, abstract, and default are not allowed on
                            // top-level declarations and are errors.
                            Set<Modifier> modifier = mt.getModifiers().getFlags();
                            if (!modifier.contains(Modifier.ABSTRACT)
                                    && !modifier.contains(Modifier.SYNCHRONIZED)
                                    && !modifier.contains(Modifier.DEFAULT)) {
                                success &= testStatement(writer, sp, text, cut, mt);
                            }
                            testBlock(writer, sp, text, cut, bt);
                        }
                    }
                }
            }
        }
    }
    fileManager.close();
    if (!success) {
        throw new AssertionError(writer.toString());
    }
}
 
Example 19
Source File: EosioRpcProviderInstrumentedTest.java    From eosio-java-android-example-app with MIT License 4 votes vote down vote up
private String getStackTraceString(Exception ex) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    ex.printStackTrace(printWriter);
    return stringWriter.toString();
}
 
Example 20
Source File: HTMLHostManagerServlet.java    From Tomcat7.0.67 with Apache License 2.0 3 votes vote down vote up
/**
 * Remove the specified host.
 *
 * @param name host name
 */
protected String remove(String name, StringManager smClient) {

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    super.remove(printWriter, name, smClient);

    return stringWriter.toString();
}