Java Code Examples for java.io.StringWriter

The following examples show how to use java.io.StringWriter. These examples are extracted from open source projects. 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: netbeans   Source File: CountingSecurityManager.java    License: Apache License 2.0 8 votes vote down vote up
public static void initialize(String prefix, Mode mode, Set<String> allowedFiles) {
    System.setProperty("counting.security.disabled", "true");

    if (System.getSecurityManager() instanceof CountingSecurityManager) {
        // ok
    } else {
        System.setSecurityManager(new CountingSecurityManager());
    }
    setCnt(0);
    msgs = new StringWriter();
    pw = new PrintWriter(msgs);
    if (prefix != null && Utilities.isWindows()) {
        prefix = prefix.toUpperCase();
    }
    CountingSecurityManager.prefix = prefix;
    CountingSecurityManager.mode = mode;
    allowed = allowedFiles;

    Logger.getLogger("org.netbeans.TopSecurityManager").setLevel(Level.OFF);
    System.setProperty("org.netbeans.TopSecurityManager.level", "3000");
    System.setProperty("counting.security.disabled", "false");
}
 
Example 2
Source Project: Bytecoder   Source File: ModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFunctionImportBinary() throws IOException {
    final Module module = new Module("mod", "mod.wasm.map");
    final Function function = module.getImports().importFunction(new ImportReference("mod","obj"),"label", PrimitiveType.i32);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final StringWriter theSourceMap = new StringWriter();
    final Exporter exporter = new Exporter(debugOptions());
    exporter.export(module, bos, theSourceMap);

    //try (FileOutputStream fos = new FileOutputStream("/home/sertic/Development/Projects/Bytecoder/core/src/test/resources/de/mirkosertic/bytecoder/backend/wasm/ast/testFunctionImport.wasm")) {
    //    exporter.export(module, fos, theSourceMap);
    //}

    final byte[] expected = IOUtils.toByteArray(getClass().getResource("testFunctionImport.wasm"));
    Assert.assertArrayEquals(expected, bos.toByteArray());
    Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString());
}
 
Example 3
@Test(groups = {
        "wso2.esb" }, description = "WithoutStream B&F, json format, xml evaluators, incoming json, outgoing json ")
public void transformPayloadByArgsValue() throws Exception {

    SimpleHttpClient httpClient = new SimpleHttpClient();
    String payload =
            "{\n" + "    \"id_str\": \"84315710834212866\",\n" + "    \"entities\": {\n" + "        \"urls\": [\n"
                    + "\n" + "        ],\n" + "        \"hashtags\": [\n" + "            {\n"
                    + "                \"text\": \"wso2\",\n" + "                \"indices\": [\n"
                    + "                    35,\n" + "                    45\n" + "                ]\n"
                    + "            }\n" + "        ],\n" + "        \"user_mentions\": [\n" + "\n" + "        ]\n"
                    + "    },\n" + "\n" + "    \"text\": \"Maybe he'll finally find his keys. #peterfalk\",\n"
                    + "    \"user\": {\n" + "        \"id_str\": \"819797\",\n" + "        \"id\": 819797\n"
                    + "    }\n" + "}";

    String contentType = "application/json";
    String url = "http://localhost:8480/services/Dummy";
    Reader data = new StringReader(payload);
    Writer writer = new StringWriter();

    String responsePayload = HttpURLConnectionClient
            .sendPostRequestAndReadResponse(data, new URL(url), writer, contentType);

    assertTrue(responsePayload.contains("wso2"), "Symbol wso2 not found in response message"); // fail

}
 
Example 4
Source Project: sunbird-lms-service   Source File: ProjectUtil.java    License: MIT License 6 votes vote down vote up
public static String getSMSBody(Map<String, String> smsTemplate) {
  try {
    Properties props = new Properties();
    props.put("resource.loader", "class");
    props.put(
        "class.resource.loader.class",
        "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

    VelocityEngine ve = new VelocityEngine();
    ve.init(props);
    smsTemplate.put("newline", "\n");
    smsTemplate.put(
        "instanceName",
        StringUtils.isBlank(smsTemplate.get("instanceName"))
            ? ""
            : smsTemplate.get("instanceName"));
    Template t = ve.getTemplate("/welcomeSmsTemplate.vm");
    VelocityContext context = new VelocityContext(smsTemplate);
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    return writer.toString();
  } catch (Exception ex) {
    ProjectLogger.log("Exception occurred while formating and sending SMS " + ex);
  }
  return "";
}
 
Example 5
Source Project: TencentKona-8   Source File: T6873849.java    License: GNU General Public License v2.0 6 votes vote down vote up
void test(String opt, String expect) throws Exception {
    List<String> args = new ArrayList<String>();
    if (opt != null)
        args.add(opt);
    args.add("-d");
    args.add(testClasses.getPath());
    args.add("-XDrawDiagnostics");
    args.add(new File(testSrc, "T6873849.java").getPath());
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    System.err.println("compile: " + args);
    int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()]), pw);
    pw.close();
    String out = sw.toString();
    System.out.println(out);
    if (rc != 0)
        throw new Exception("compilation failed unexpectedly");
    if (!out.equals(expect))
        throw new Exception("unexpected output from compiler");
}
 
Example 6
Source Project: neoscada   Source File: DebianPackageWriter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected ContentProvider createConfFilesContent () throws IOException
{
    if ( this.confFiles.isEmpty () )
    {
        return ContentProvider.NULL_CONTENT;
    }

    final StringWriter sw = new StringWriter ();

    for ( final String confFile : this.confFiles )
    {
        sw.append ( confFile ).append ( '\n' );
    }

    sw.close ();
    return new StaticContentProvider ( sw.toString () );
}
 
Example 7
Source Project: virtualview_tools   Source File: Log.java    License: MIT License 6 votes vote down vote up
/**
 * Handy function to get a loggable stack trace from a Throwable
 * @param tr An exception to log
 * @return throwable string.
 */
public static String getStackTraceString(Throwable tr) {
    if (tr == null) {
        return "";
    }

    // This is to reduce the amount of log spew that apps do in the non-error
    // condition of the network being unavailable.
    Throwable t = tr;
    while (t != null) {
        if (t instanceof UnknownHostException) {
            return "";
        }
        t = t.getCause();
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    tr.printStackTrace(pw);
    pw.flush();
    return sw.toString();
}
 
Example 8
/**
 * Returns the String representation of an AlloyRelation's settings.
 */
private static String writeEdgeViz(VizState view, VizState defaultView, AlloyRelation x) throws IOException {
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    writeDotColor(out, view.edgeColor.get(x), defaultView.edgeColor.get(x));
    writeDotStyle(out, view.edgeStyle.get(x), defaultView.edgeStyle.get(x));
    writeBool(out, "visible", view.edgeVisible.get(x), defaultView.edgeVisible.get(x));
    writeBool(out, "merge", view.mergeArrows.get(x), defaultView.mergeArrows.get(x));
    writeBool(out, "layout", view.layoutBack.get(x), defaultView.layoutBack.get(x));
    writeBool(out, "attribute", view.attribute.get(x), defaultView.attribute.get(x));
    writeBool(out, "constraint", view.constraint.get(x), defaultView.constraint.get(x));
    if (view.weight.get(x) != defaultView.weight.get(x))
        out.write(" weight=\"" + view.weight.get(x) + "\"");
    if (x != null && !view.label.get(x).equals(defaultView.label.get(x)))
        Util.encodeXMLs(out, " label=\"", view.label.get(x), "\"");
    if (out.checkError())
        throw new IOException("PrintWriter IO Exception!");
    return sw.toString();
}
 
Example 9
Source Project: dremio-oss   Source File: PrelSequencer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate readable text and json plans and set them in <code>planHolder</code>
 * @param rel
 * @param explainlevel explain plan level.
 * @param observer
 */
public static String setPlansWithIds(final Prel rel, final SqlExplainLevel explainlevel, final AttemptObserver observer, final long millisTaken) {
  if (rel == null) {
    return null;
  }

  Map<Prel, OpId> relIdMap = getIdMap(rel);
  final StringWriter sw = new StringWriter();
  final RelWriter textPlanWriter = new NumberingRelWriter(relIdMap, new PrintWriter(sw), explainlevel);
  rel.explain(textPlanWriter);

  final String textPlan = sw.toString();
  observer.planText(sw.toString(), millisTaken);
  final RelJsonWriter jsonPlanWriter = new RelJsonWriter(getIdMap(rel), explainlevel);
  rel.explain(jsonPlanWriter);
  observer.planJsonPlan(jsonPlanWriter.asString());
  return textPlan;
}
 
Example 10
public void setHdf5File(RandomAccessFile raf) throws IOException {
  closeOpenFiles();

  this.location = raf.getLocation();
  List<ObjectBean> beanList = new ArrayList<>();

  iosp = new H5iospNew();
  NetcdfFile ncfile = new NetcdfFileSubclass(iosp, location);
  ncfile.sendIospMessage(H5iospNew.IOSP_MESSAGE_INCLUDE_ORIGINAL_ATTRIBUTES);

  try {
    iosp.open(raf, ncfile, null);
  } catch (Throwable t) {
    StringWriter sw = new StringWriter(20000);
    PrintWriter s = new PrintWriter(sw);
    t.printStackTrace(s);
    dumpTA.setText(sw.toString());
  }

  H5headerNew header = iosp.getHeader();
  for (H5objects.DataObject dataObj : header.getDataObjects()) {
    beanList.add(new ObjectBean(dataObj));
  }

  objectTable.setBeans(beanList);
}
 
Example 11
Source Project: hop   Source File: RemoveWorkflowServletTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@PrepareForTest( { Encode.class } )
public void testRemoveWorkflowServletEscapesHtmlWhenPipelineNotFound() throws ServletException, IOException {
  HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class );
  HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class );

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

  PowerMockito.spy( Encode.class );
  when( mockHttpServletRequest.getContextPath() ).thenReturn( RemoveWorkflowServlet.CONTEXT_PATH );
  when( mockHttpServletRequest.getParameter( anyString() ) ).thenReturn( ServletTestUtils.BAD_STRING_TO_TEST );
  when( mockHttpServletResponse.getWriter() ).thenReturn( printWriter );

  removeWorkflowServlet.doGet( mockHttpServletRequest, mockHttpServletResponse );
  assertFalse( ServletTestUtils.hasBadText( ServletTestUtils.getInsideOfTag( "H1", out.toString() ) ) );

  PowerMockito.verifyStatic( atLeastOnce() );
  Encode.forHtml( anyString() );
}
 
Example 12
Source Project: TencentKona-8   Source File: ToolBox.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * A helper method for executing langtools commands.
 */
private static int genericJavaCMD(
        JavaCMD cmd,
        JavaToolArgs params)
        throws CommandExecutionException, IOException {
    int rc = 0;
    StringWriter sw = null;
    try (PrintWriter pw = (params.errOutput == null) ?
            null : new PrintWriter(sw = new StringWriter())) {
        rc = cmd.run(params, pw);
    }
    String out = (sw == null) ? null : sw.toString();

    if (params.errOutput != null && (out != null) && !out.isEmpty()) {
        params.errOutput.addAll(splitLines(out, lineSeparator));
    }

    if ( (rc == 0 && params.whatToExpect == Expect.SUCCESS) ||
         (rc != 0 && params.whatToExpect == Expect.FAIL) ) {
        return rc;
    }

    throw new CommandExecutionException(cmd.getExceptionMsgContent(params),
            params.whatToExpect);
}
 
Example 13
Source Project: openjdk-jdk8u   Source File: T7190862.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
Example 14
Source Project: netbeans   Source File: TemplateUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String expandTemplate(Reader reader, Map<String, Object> values) {
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    try {
        eng.eval(reader);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}
 
Example 15
Source Project: jdmn   Source File: JsonSerializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonSerialization() throws IOException {
    Person person = new Person();
    person.setFirstName("Amy");
    person.setLastName("Smith");
    person.setId(decision.number("38"));
    person.setGender("female");
    person.setList(Arrays.asList("Late payment"));
    person.setMarried(true);
    person.setDateOfBirth(decision.date("2017-01-03"));
    person.setTimeOfBirth(decision.time("11:20:30Z"));
    person.setDateTimeOfBirth(decision.dateAndTime("2016-08-01T12:00:00Z"));
    person.setDateTimeList(Arrays.asList(decision.dateAndTime("2016-08-01T12:00:00Z")));
    person.setYearsAndMonthsDuration(decision.duration("P1Y1M"));
    person.setDaysAndTimeDuration(decision.duration("P2DT20H"));

    Writer writer = new StringWriter();
    JsonSerializer.OBJECT_MAPPER.writeValue(writer, person);
    writer.close();

    assertEquals(personText, writer.toString());
}
 
Example 16
@Override
public String decompile(InputStream inputStream, String entryName) throws IOException {
  logger.debug("Decompiling... {}", entryName);
  File tempFile = createTempFile(entryName, inputStream);
  tempFile.deleteOnExit();

  String decompiledFileName = getDecompiledFileName(entryName);
  File decompiledFile = new File(decompiledFileName);
  decompiledFile.getParentFile().mkdirs();

  StringWriter pw = new StringWriter();
  try {
    com.strobel.decompiler.Decompiler.decompile(tempFile.getAbsolutePath(), new PlainTextOutput(pw));
  } catch (Exception e) {
    logger.info("Error while decompiling {}. " , entryName);
    throw e;
  }
  pw.flush();

  String decompiledFileContent = pw.toString();
  FileUtils.writeStringToFile(decompiledFile, decompiledFileContent);
  return decompiledFileContent;
}
 
Example 17
Source Project: htmlunit   Source File: DomNode.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a string representation of the XML document from this element and all it's children (recursively).
 * The charset used is the current page encoding.
 * @return the XML string
 */
public String asXml() {
    Charset charsetName = null;
    final HtmlPage htmlPage = getHtmlPageOrNull();
    if (htmlPage != null) {
        charsetName = htmlPage.getCharset();
    }

    final StringWriter stringWriter = new StringWriter();
    try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
        if (charsetName != null && this instanceof HtmlHtml) {
            printWriter.print("<?xml version=\"1.0\" encoding=\"");
            printWriter.print(charsetName);
            printWriter.print("\"?>\r\n");
        }
        printXml("", printWriter);
        return stringWriter.toString();
    }
}
 
Example 18
Source Project: staedi   Source File: StaEDIXMLStreamReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testReadXml() throws Exception {
    XMLStreamReader xmlReader = getXmlReader("/x12/extraDelimiter997.edi");
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example 19
Source Project: seckill-rocketmq   Source File: LogExceptionWapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取完整栈轨迹
 *
 * @param aThrowable
 * @return
 */
public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
}
 
Example 20
Source Project: TencentKona-8   Source File: TestSuperclass.java    License: GNU General Public License v2.0 5 votes vote down vote up
String javap(File file) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    String[] args = { file.getPath() };
    int rc = com.sun.tools.javap.Main.run(args, pw);
    pw.close();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (rc != 0)
        throw new Error("javap failed: rc=" + rc);
    return out;
}
 
Example 21
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access
 *            the method's access flags.
 * @param name
 *            the method's name.
 * @param desc
 *            the method's descriptor (see {@link Type Type}).
 * @param cmv
 *            the method visitor to which this adapter must delegate calls.
 * @param labels
 *            a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name,
        final String desc, final MethodVisitor cmv,
        final Map<Label, Integer> labels) {
    this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(
                    new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0) {
                    throw new RuntimeException(
                            "Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    }, labels);
    this.access = access;
}
 
Example 22
Source Project: FuzzDroid   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {		
	Timer timer = new Timer();
       timer.schedule(new TimerTask() {        	
           @Override
           public void run() {
           	LoggerHelper.logEvent(MyLevel.TIMEOUT, "-1 | Complete analysis stopped due to timeout of 40 minutes");
               System.exit(0);
           }
       }, 40 * 60000);
	
	
	try{
		Main.v().run(args);
		AndroidDebugBridge.terminate();
	}catch(Exception ex) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);			
		LoggerHelper.logEvent(MyLevel.EXCEPTION_ANALYSIS, sw.toString());
		UtilMain.writeToFile("mainException.txt", FrameworkOptions.apkPath + "\n");
	}
	LoggerHelper.logEvent(MyLevel.EXECUTION_STOP, "Analysis successfully terminated");
	//this is necessary otherwise we will wait for a max of 20 minutes for the TimerTask
	System.exit(0);
}
 
Example 23
Source Project: netbeans   Source File: ErrorManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void notify(int severity, Throwable t) {
    StringWriter w = new StringWriter();
    w.write(prefix);
    w.write(' ');
    t.printStackTrace(new PrintWriter(w));
    
    System.err.println(w.toString());
    
    if (running == null) {
        return;
    }
    running.getLog().println(w.toString());
}
 
Example 24
Source Project: openjdk-jdk9   Source File: TestSuperclass.java    License: GNU General Public License v2.0 5 votes vote down vote up
String javap(File file) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    String[] args = { file.getPath() };
    int rc = com.sun.tools.javap.Main.run(args, pw);
    pw.close();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (rc != 0)
        throw new Error("javap failed: rc=" + rc);
    return out;
}
 
Example 25
Source Project: EasyRouter   Source File: EasyRouterLogUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void e(Exception ex) {
    if (!debug) {
        return;
    }
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    ex.printStackTrace(pw);
    String string = writer.toString();
    Log.e(DEFAULT_TAG, string);
}
 
Example 26
Source Project: RxJava2RetrofitDemo   Source File: Timber.java    License: Apache License 2.0 5 votes vote down vote up
private String getStackTraceString(Throwable t) {
    // Don't replace this bindDisposable Log.getStackTraceString() - it hides
    // UnknownHostException, which is not what we want.
    StringWriter sw = new StringWriter(256);
    PrintWriter pw = new PrintWriter(sw, false);
    t.printStackTrace(pw);
    pw.flush();
    return sw.toString();
}
 
Example 27
Source Project: dragonwell8_jdk   Source File: NTypePrinter.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected String printStruct(NStruct nt, char open, char close){
    StringWriter sw = new StringWriter();
    sw.append(open);
    sw.append(nt.name);
    if(nt.fields.size() > 0){
        sw.append('=');
        for(NField f : nt.fields){
            if(f.name != null && f.name.length() > 0)
                sw.append("\"" + f.name + "\"");
            sw.append(print(f.type));
        }
    }
    sw.append(close);
    return sw.toString();
}
 
Example 28
private static String xform(final String xml, final String xsl) throws Exception {
    final TransformerFactory tf = TransformerFactory.newInstance();
    final Source xslsrc = new StreamSource(new File(xsl));
    final Templates tmpl = tf.newTemplates(xslsrc);
    final Transformer t = tmpl.newTransformer();

    StringWriter writer = new StringWriter();
    final Source src = new StreamSource(new File(xml));
    final Result res = new StreamResult(writer);

    t.transform(src, res);
    return writer.toString();
}
 
Example 29
Source Project: jdk8u60   Source File: DescriptorTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
void javac(String... args) throws Exception {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    int rc = com.sun.tools.javac.Main.compile(args, pw);
    pw.flush();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (rc != 0)
        throw new Exception("compilation failed");
}
 
Example 30
Source Project: openjdk-jdk8u   Source File: DocLintTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
void test(List<String> opts, Main.Result expectResult, Set<Message> expectMessages) {
        System.err.println("test: " + opts);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        List<JavaFileObject> files = Arrays.asList(file);
        try {
            DocumentationTask t = javadoc.getTask(pw, fm, null, null, opts, files);
            boolean ok = t.call();
            pw.close();
            String out = sw.toString().replaceAll("[\r\n]+", "\n");
            if (!out.isEmpty())
                System.err.println(out);
            if (ok && expectResult != Main.Result.OK) {
                error("Compilation succeeded unexpectedly");
            } else if (!ok && expectResult != Main.Result.ERROR) {
                error("Compilation failed unexpectedly");
            } else
                check(out, expectMessages);
        } catch (IllegalArgumentException e) {
            System.err.println(e);
            String expectOut = expectMessages.iterator().next().text;
            if (expectResult != Main.Result.CMDERR)
                error("unexpected exception caught");
            else if (!e.getMessage().equals(expectOut)) {
                error("unexpected exception message: "
                        + e.getMessage()
                        + " expected: " + expectOut);
            }
        }

//        if (errors > 0)
//            throw new Error("stop");
    }