java.io.PrintWriter Java Examples

The following examples show how to use java.io.PrintWriter. 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: gemfirexd-oss   Author: gemxd   File: PureLogWriter.java    License: Apache License 2.0 10 votes vote down vote up
/**
 * Logs a message and an exception to the specified log destination.
 * 
 * @param msgLevel
 *                a string representation of the level
 * @param msg
 *                the actual message to log
 * @param ex
 *                the actual Exception to log
 */
@Override
protected void put(int msgLevel, String msg, Throwable ex) {
  String exceptionText = null;
  if (ex != null) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    pw.close();
    try {
      sw.close();
    }
    catch (IOException ignore) {
    }
    exceptionText = sw.toString();
  }
  put(msgLevel, new Date(), this.connectionName, getThreadName(),
      getThreadId(), msg, exceptionText);
}
 
Example #2
Source Project: DesigniteJava   Author: tushartushar   File: SM_Type.java    License: Apache License 2.0 10 votes vote down vote up
@Override
public void printDebugLog(PrintWriter writer) {
	print(writer, "\tType: " + name);
	print(writer, "\tPackage: " + this.getParentPkg().getName());
	print(writer, "\tAccess: " + accessModifier);
	print(writer, "\tInterface: " + isInterface);
	print(writer, "\tAbstract: " + isAbstract);
	print(writer, "\tSupertypes: " + ((getSuperTypes().size() != 0) ? getSuperTypes().get(0).getName() : "Object"));
	print(writer, "\tNested class: " + nestedClass);
	if (nestedClass)
		print(writer, "\tContainer class: " + containerClass.getName());
	print(writer, "\tReferenced types: ");
	for (SM_Type type:referencedTypeList)
		print(writer, "\t\t" + type.getName());
	for (SM_Field field : fieldList)
		field.printDebugLog(writer);
	for (SM_Method method : methodList)
		method.printDebugLog(writer);
	print(writer, "\t----");
}
 
Example #3
Source Project: bluima   Author: BlueBrain   File: ConceptFileWriter.java    License: Apache License 2.0 10 votes vote down vote up
public static void writeConceptFile(File f, Collection<Concept> concepts,
        String msg) throws FileNotFoundException {

    PrintWriter w = new PrintWriter(f);
    w.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
    w.append("<!-- generated by ConceptFileWriter on " + nowToHuman()
            + " -->\n");
    if (msg != null && msg.length() > 0) {
        w.append("<!--  " + escape(msg) + " -->\n");
    }
    w.append("<synonym>\n");

    for (Concept c : concepts) {

        w.format("<token canonical=\"%s\" ref_id=\"%s\">\n",
                escape(c.canonical), escape(c.id));

        for (String v : c.variants) {
            w.format("  <variant base=\"%s\" />\n", escape(v));
        }
        w.append("</token>\n");
    }
    w.append("</synonym>\n");
    w.close();
}
 
Example #4
Source Project: gemfirexd-oss   Author: gemxd   File: Swarm.java    License: Apache License 2.0 9 votes vote down vote up
private static String getRootCause(Throwable t) {
  if (t.getCause() == null) {
    StringWriter sw = new StringWriter();
    t.printStackTrace(new PrintWriter(sw));
    return sw.toString();
  }
  else {
    return getRootCause(t.getCause());
  }
}
 
Example #5
Source Project: dragonwell8_jdk   Author: alibaba   File: ResourceBundleGenerator.java    License: GNU General Public License v2.0 9 votes vote down vote up
@Override
public void generateMetaInfo(Map<String, SortedSet<String>> metaInfo) throws IOException {
    String dirName = CLDRConverter.DESTINATION_DIR + File.separator + "sun" + File.separator + "util" + File.separator
            + "cldr" + File.separator;
    File dir = new File(dirName);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    File file = new File(dir, METAINFO_CLASS + ".java");
    if (!file.exists()) {
        file.createNewFile();
    }
    CLDRConverter.info("Generating file " + file);

    try (PrintWriter out = new PrintWriter(file, "us-ascii")) {
        out.println(CopyrightHeaders.getOpenJDKCopyright());

        out.println("package sun.util.cldr;\n\n"
                  + "import java.util.ListResourceBundle;\n");
        out.printf("public class %s extends ListResourceBundle {\n", METAINFO_CLASS);
        out.println("    @Override\n" +
                    "    protected final Object[][] getContents() {\n" +
                    "        final Object[][] data = new Object[][] {");
        for (String key : metaInfo.keySet()) {
            out.printf("            { \"%s\",\n", key);
            out.printf("              \"%s\" },\n", toLocaleList(metaInfo.get(key)));
        }
        out.println("        };\n        return data;\n    }\n}");
    }
}
 
Example #6
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: SOAPExceptionImpl.java    License: GNU General Public License v2.0 9 votes vote down vote up
@Override
public void printStackTrace(PrintWriter s) {
    super.printStackTrace(s);
    if (cause != null) {
        s.println("\nCAUSE:\n");
        cause.printStackTrace(s);
    }
}
 
Example #7
Source Project: beam   Author: apache   File: DataflowWorkerLoggingHandler.java    License: Apache License 2.0 9 votes vote down vote up
/**
 * Formats the throwable as per {@link Throwable#printStackTrace()}.
 *
 * @param thrown The throwable to format.
 * @return A string containing the contents of {@link Throwable#printStackTrace()}.
 */
public static String formatException(Throwable thrown) {
  if (thrown == null) {
    return null;
  }
  StringWriter sw = new StringWriter();
  try (PrintWriter pw = new PrintWriter(sw)) {
    thrown.printStackTrace(pw);
  }
  return sw.toString();
}
 
Example #8
@Override
protected void writeLoginPageLink(ServletContext context, HttpServletRequest req, HttpServletResponse resp)
        throws IOException
{
    resp.setContentType("text/html; charset=UTF-8");
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    
    try (PrintWriter out = resp.getWriter())
    {
        out.println("<html><head>");
        // Removed the auto refresh to avoid refresh loop, MNT-16931
        // Removed the link to the login page, MNT-20200
        out.println("</head><body><p>Login failed. Please try again.</p>");
        out.println("</body></html>");
    }
}
 
Example #9
Source Project: GeoTriples   Author: LinkedEOData   File: WP2RDFXMLWriter.java    License: Apache License 2.0 9 votes vote down vote up
private void writeRDFHeader(Model model, PrintWriter writer) {
	String xmlns = xmlnsDecl();
	writer.print("<" + rdfEl("RDF") + xmlns);
	if (null != xmlBase && xmlBase.length() > 0)
		writer.print("\n  xml:base=" + substitutedAttribute(xmlBase));
	writer.println(" > ");
}
 
Example #10
Source Project: RADL   Author: restful-api-description-language   File: RadlToSpringServerTest.java    License: Apache License 2.0 9 votes vote down vote up
@Test
public void generatesSpringServerSourceFilesFromRadl() throws IOException {
  String lower = "f";
  String upper = lower.toUpperCase(Locale.getDefault());
  String name = RANDOM.string();
  Document radlDocument = RadlBuilder.aRadlDocument()
      .withResource()
          .named(lower + name)
      .end()
  .build();
  try (PrintWriter writer = new PrintWriter(radlFile, "UTF8")) {
    writer.print(Xml.toString(radlDocument));
  }
  String packagePrefix = somePackage();
  String generatedSourceSetDir = someSourceSetDir();
  String mainSourceSetDir = someSourceSetDir();
  SourceCodeManagementSystem scm = mock(SourceCodeManagementSystem.class);
  String header = RANDOM.string();

  generator.generate(radlFile, baseDir, packagePrefix, generatedSourceSetDir, mainSourceSetDir, scm, header);

  Collection<File> files = generatedFiles();
  File controller = find(files, upper + name + "Controller.java");
  assertNotNull("Missing controller: " + files, controller);
  String expectedPath = expectedFilePath(generatedSourceSetDir, packagePrefix, lower + name, controller);
  assertEquals("Controller path", expectedPath, controller.getAbsolutePath());
  JavaCode javaCode = toJava(controller);
  TestUtil.assertCollectionEquals("Header for " + controller.getName(), Arrays.asList(header),
      javaCode.fileComments());

  File controllerSupport = find(files, upper + name + "ControllerSupport.java");
  assertNotNull("Missing controller support: " + files, controllerSupport);
  expectedPath = expectedFilePath(mainSourceSetDir, packagePrefix, lower + name, controllerSupport);
  assertEquals("Controller support path", expectedPath, controllerSupport.getAbsolutePath());
}
 
Example #11
Source Project: yGuard   Author: yWorks   File: LogParserView.java    License: MIT License 9 votes vote down vote up
static String toErrorMessage( final File file, final Exception ex ) {
  final StringWriter sw = new StringWriter();
  sw.write("Could not read ");
  sw.write(file.getAbsolutePath());
  sw.write(":\n");
  ex.printStackTrace(new PrintWriter(sw));
  return sw.toString();
}
 
Example #12
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: BasicWriter.java    License: GNU General Public License v2.0 9 votes vote down vote up
protected LineWriter(Context context) {
    context.put(LineWriter.class, this);
    Options options = Options.instance(context);
    indentWidth = options.indentWidth;
    tabColumn = options.tabColumn;
    out = context.get(PrintWriter.class);
    buffer = new StringBuilder();
}
 
Example #13
Source Project: cpsolver   Author: UniTime   File: CSVFile.java    License: GNU Lesser General Public License v3.0 9 votes vote down vote up
public void debug(int offset, PrintWriter out) {
    int idx = 0;
    for (Iterator<CSVField> i = iFields.iterator(); i.hasNext();) {
        CSVField field = i.next();
        if (field == null || field.toString().length() == 0)
            continue;
        for (int j = 0; j < offset; j++)
            out.print(" ");
        out.println(iHeader.getField(idx) + "=" + (iQuotationMark == null ? "" : iQuotationMark) + field
                + (iQuotationMark == null ? "" : iQuotationMark));
    }
}
 
Example #14
Source Project: j2objc   Author: google   File: UCharacterCompare.java    License: Apache License 2.0 9 votes vote down vote up
/**
 * Difference writing to file
 * 
 * @param f
 *            file outputstream
 * @param ch
 *            code point
 * @param method
 *            for testing
 * @param ucharval
 *            UCharacter value after running method
 * @param charval
 *            Character value after running method
 */
private static void trackDifference(PrintWriter f, int ch, String method, String ucharval, String charval)
        throws Exception {
    if (m_hashtable_.containsKey(method)) {
        Integer value = m_hashtable_.get(method);
        m_hashtable_.put(method, new Integer(value.intValue() + 1));
    } else
        m_hashtable_.put(method, new Integer(1));

    String temp = Integer.toHexString(ch);
    StringBuffer s = new StringBuffer(temp);
    for (int i = 0; i < 6 - temp.length(); i++)
        s.append(' ');
    temp = UCharacter.getExtendedName(ch);
    if (temp == null)
        temp = " ";
    s.append(temp);
    for (int i = 0; i < 73 - temp.length(); i++)
        s.append(' ');

    s.append(method);
    for (int i = 0; i < 27 - method.length(); i++)
        s.append(' ');
    s.append(ucharval);
    for (int i = 0; i < 11 - ucharval.length(); i++)
        s.append(' ');
    s.append(charval);
    f.println(s.toString());
}
 
Example #15
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: QueriesTest.java    License: Apache License 2.0 9 votes vote down vote up
@Test
public void queryInterface_orFilter_printsMatchedEntities() throws Exception {
  // Arrange
  Entity a = new Entity("Person", "a");
  a.setProperty("height", 100);
  Entity b = new Entity("Person", "b");
  b.setProperty("height", 150);
  Entity c = new Entity("Person", "c");
  c.setProperty("height", 200);
  datastore.put(ImmutableList.<Entity>of(a, b, c));

  StringWriter buf = new StringWriter();
  PrintWriter out = new PrintWriter(buf);
  long minHeight = 125;
  long maxHeight = 175;

  // Act
  // [START gae_java8_datastore_interface_3]
  Filter tooShortFilter = new FilterPredicate("height", FilterOperator.LESS_THAN, minHeight);

  Filter tooTallFilter = new FilterPredicate("height", FilterOperator.GREATER_THAN, maxHeight);

  Filter heightOutOfRangeFilter = CompositeFilterOperator.or(tooShortFilter, tooTallFilter);

  Query q = new Query("Person").setFilter(heightOutOfRangeFilter);
  // [END gae_java8_datastore_interface_3]

  // Assert
  List<Entity> results =
      datastore.prepare(q.setKeysOnly()).asList(FetchOptions.Builder.withDefaults());
  assertWithMessage("query results").that(results).containsExactly(a, c);
}
 
Example #16
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: DriverManagerTests.java    License: GNU General Public License v2.0 9 votes vote down vote up
/**
 * Create a PrintWriter and use to to send output via DriverManager.println
 * Validate that if you disable the writer, the output sent is not present
 */
@Test
public void tests18() throws Exception {
    CharArrayWriter cw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(cw);
    DriverManager.setLogWriter(pw);
    assertTrue(DriverManager.getLogWriter() == pw);

    DriverManager.println(results[0]);
    DriverManager.setLogWriter(null);
    assertTrue(DriverManager.getLogWriter() == null);
    DriverManager.println(noOutput);
    DriverManager.setLogWriter(pw);
    DriverManager.println(results[1]);
    DriverManager.println(results[2]);
    DriverManager.println(results[3]);
    DriverManager.setLogWriter(null);
    DriverManager.println(noOutput);

    /*
     * Check we do not get the output when the stream is disabled
     */
    BufferedReader reader
            = new BufferedReader(new CharArrayReader(cw.toCharArray()));
    for (String result : results) {
        assertTrue(result.equals(reader.readLine()));
    }
}
 
Example #17
Source Project: google-java-format   Author: google   File: DiagnosticTest.java    License: Apache License 2.0 9 votes vote down vote up
@Test
public void lexError() throws Exception {
  String input = "\\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuu00not-actually-a-unicode-escape-sequence";

  StringWriter stdout = new StringWriter();
  StringWriter stderr = new StringWriter();
  Main main = new Main(new PrintWriter(stdout, true), new PrintWriter(stderr, true), System.in);

  Path tmpdir = testFolder.newFolder().toPath();
  Path path = tmpdir.resolve("InvalidSyntax.java");
  Files.write(path, input.getBytes(UTF_8));

  int result = main.format(path.toString());
  assertThat(stdout.toString()).isEmpty();
  assertThat(stderr.toString())
      .contains("InvalidSyntax.java:1:35: error: illegal unicode escape");
  assertThat(result).isEqualTo(1);
}
 
Example #18
Source Project: nifi   Author: apache   File: TestInvokeAWSGatewayApiCommon.java    License: Apache License 2.0 9 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
                   HttpServletResponse response) throws IOException, ServletException {
    baseRequest.setHandled(true);

    if ("Get".equalsIgnoreCase(request.getMethod())) {
        String headerValue = request.getHeader("Foo");
        response.setHeader("dynamicHeader", request.getHeader("dynamicHeader"));
        final int status = Integer.valueOf(target.substring("/status".length() + 1));
        response.setStatus(status);
        response.setContentLength(headerValue.length());
        response.setContentType("text/plain");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(headerValue);
            writer.flush();
        }
    } else {
        response.setStatus(404);
        response.setContentType("text/plain");
        response.setContentLength(0);
    }
}
 
Example #19
Source Project: openjdk-8   Author: bpupadhyaya   File: JavapTask.java    License: GNU General Public License v2.0 8 votes vote down vote up
private static PrintWriter getPrintWriterForWriter(Writer w) {
    if (w == null)
        return getPrintWriterForStream(null);
    else if (w instanceof PrintWriter)
        return (PrintWriter) w;
    else
        return new PrintWriter(w, true);
}
 
Example #20
Source Project: big-c   Author: yncxcw   File: TestNodesPage.java    License: Apache License 2.0 8 votes vote down vote up
@Test
public void testNodesBlockRender() throws Exception {
  injector.getInstance(NodesBlock.class).render();
  PrintWriter writer = injector.getInstance(PrintWriter.class);
  WebAppTests.flushOutput(injector);

  Mockito.verify(writer,
      Mockito.times(numberOfActualTableHeaders + numberOfThInMetricsTable))
      .print("<th");
  Mockito.verify(
      writer,
      Mockito.times(numberOfRacks * numberOfNodesPerRack
          * numberOfActualTableHeaders + numberOfThInMetricsTable)).print(
      "<td");
}
 
Example #21
Source Project: jeewx   Author: zhangdaiscott   File: WeixinCoreController.java    License: Apache License 2.0 8 votes vote down vote up
@RequestMapping(params="wechat", method = RequestMethod.POST)
public void wechatPost(HttpServletResponse response,
		HttpServletRequest request,
		@RequestParam(value = "msg_signature") String msg_signature,
		@RequestParam(value = "timestamp") String timestamp,
		@RequestParam(value = "nonce") String nonce) throws Exception {
	try {
		String sReqData = MessageUtil.readStrFromInputStream(request);
		Map<String, String> dealMap = MessageUtil.parseXml(sReqData);
		String appid = dealMap.get("AgentID");
		String corpid = dealMap.get("ToUserName");
		String sEncryptMsg = "";
		QywxAgent appInfo = qywxAgentDao.getQywxAgentByCorpidAndAppid(corpid, appid);
		WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(appInfo.getToken(),appInfo.getEncodingAESKey(),corpid);
		String sMsg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, sReqData);
		logger.info("[WECHAT]", "wechat msg:\n{}", new Object[]{sMsg});
		String respMessage = weixinCoreService.processRequest(sMsg);
		logger.info("[WECHAT]", "wechat resmsg:\n{}", new Object[]{respMessage});
		sEncryptMsg = wxcpt.EncryptMsg(respMessage, timestamp, nonce);
		logger.info("[WECHAT]", "wechat EncryptMsg:\n{}", new Object[]{sEncryptMsg});
		PrintWriter out = response.getWriter();
		out.print(sEncryptMsg);
		out.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #22
Source Project: jvm-sandbox   Author: alibaba   File: ModuleMgrModule.java    License: GNU Lesser General Public License v3.0 8 votes vote down vote up
@Command("detail")
public void detail(final Map<String, String> param,
                   final PrintWriter writer) throws ModuleException {
    final String uniqueId = param.get("id");
    if (StringUtils.isBlank(uniqueId)) {
        // 如果参数不对,则认为找不到对应的沙箱模块,返回400
        writer.println("id parameter was required.");
        return;
    }

    final Module module = moduleManager.get(uniqueId);
    if (null == module) {
        writer.println(String.format("module[id=%s] is not existed.", uniqueId));
        return;
    }

    final Information info = module.getClass().getAnnotation(Information.class);
    final boolean isActivated = moduleManager.isActivated(info.id());
    final int cCnt = moduleManager.cCnt(info.id());
    final int mCnt = moduleManager.mCnt(info.id());
    final File jarFile = moduleManager.getJarFile(info.id());
    String sb = "" +
            "      ID : " + info.id() + "\n" +
            " VERSION : " + info.version() + "\n" +
            "  AUTHOR : " + info.author() + "\n" +
            "JAR_FILE : " + jarFile.getPath() + "\n" +
            "   STATE : " + (isActivated ? "ACTIVE" : "FROZEN") + "\n" +
            "    MODE : " + ArrayUtils.toString(info.mode()) + "\n" +
            "   CLASS : " + module.getClass().getName() + "\n" +
            "  LOADER : " + module.getClass().getClassLoader() + "\n" +
            "    cCnt : " + cCnt + "\n" +
            "    mCnt : " + mCnt;

    output(writer, sb);

}
 
Example #23
Source Project: spork   Author: sigmoidanalytics   File: TestEmptyInputDir.java    License: Apache License 2.0 8 votes vote down vote up
@Test
public void testSkewedJoin() throws Exception {
    PrintWriter w = new PrintWriter(new FileWriter(PIG_FILE));
    w.println("A = load '" + INPUT_FILE + "';");
    w.println("B = load '" + EMPTY_DIR + "';");
    w.println("C = join B by $0, A by $0 using 'skewed';");
    w.println("store C into '" + OUTPUT_FILE + "';");
    w.close();
    
    try {
        String[] args = { PIG_FILE };
        PigStats stats = PigRunner.run(args, null);
 
        assertTrue(stats.isSuccessful());
        // the sampler job has zero maps
        MRJobStats js = (MRJobStats)stats.getJobGraph().getSources().get(0);
        
        // This assert fails on 205 due to MAPREDUCE-3606
        if (!Util.isHadoop205()&&!Util.isHadoop1_x())
            assertEquals(0, js.getNumberMaps()); 
        
        FileSystem fs = cluster.getFileSystem();
        FileStatus status = fs.getFileStatus(new Path(OUTPUT_FILE));
        assertTrue(status.isDir());
        assertEquals(0, status.getLen());
        // output directory isn't empty
        assertTrue(fs.listStatus(status.getPath()).length > 0);
    } finally {
        new File(PIG_FILE).delete();
        Util.deleteFile(cluster, OUTPUT_FILE);
    }
}
 
Example #24
Source Project: openjdk-8-source   Author: keerath   File: MethodGenClone24.java    License: GNU General Public License v2.0 8 votes vote down vote up
/**
 * <d62023> - delete method templates for valuetypes
 **/
protected void interfaceMethod (Hashtable symbolTable, MethodEntry m, PrintWriter stream)
{
  this.symbolTable = symbolTable;
  this.m           = m;
  this.stream      = stream;
  if (m.comment () != null)
    m.comment ().generate ("  ", stream);
  stream.print ("  ");
  writeMethodSignature ();
  stream.println (";");
}
 
Example #25
Source Project: jdk8u-jdk   Author: frohoff   File: Printer.java    License: GNU General Public License v2.0 8 votes vote down vote up
/**
 * Prints the given string tree.
 *
 * @param pw
 *            the writer to be used to print the tree.
 * @param l
 *            a string tree, i.e., a string list that can contain other
 *            string lists, and so on recursively.
 */
static void printList(final PrintWriter pw, final List<?> l) {
    for (int i = 0; i < l.size(); ++i) {
        Object o = l.get(i);
        if (o instanceof List) {
            printList(pw, (List<?>) o);
        } else {
            pw.print(o.toString());
        }
    }
}
 
Example #26
Source Project: rcrs-server   Author: roborescue   File: LiveLogExtractor.java    License: BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
private static void writeFile(String filename, String content) {
    try {
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
        out.print(content);
        out.close();
    }
    catch (IOException e) {
        System.out.println("Error writing file: " + e.getMessage());
    }
    
}
 
Example #27
Source Project: hortonmachine   Author: TheHortonMachine   File: MOCOM.java    License: GNU General Public License v3.0 8 votes vote down vote up
void init() throws FileNotFoundException {
    writer = new PrintWriter(fileName);
    for (int p = 0; p < this.parameterNames.length; p++) {
        writer.print(this.parameterNames[p] + " ");
    }
    for (int p = 0; p < this.effNames.length; p++) {
        writer.print(this.effNames[p] + " ");
    }
    writer.flush();
}
 
Example #28
Source Project: fabric-sdk-java   Author: hyperledger   File: HFCAClient.java    License: Apache License 2.0 8 votes vote down vote up
String toJson(JsonObject toJsonFunc) {
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
    jsonWriter.writeObject(toJsonFunc);
    jsonWriter.close();
    return stringWriter.toString();
}
 
Example #29
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: XPreferTest.java    License: GNU General Public License v2.0 7 votes vote down vote up
String compile() throws IOException {

            // Create a class that references classId
            File explicit = new File("ExplicitClass.java");
            FileWriter filewriter = new FileWriter(explicit);
            filewriter.append("class ExplicitClass { " + classId + " implicit; }");
            filewriter.close();

            StringWriter sw = new StringWriter();

            com.sun.tools.javac.Main.compile(new String[] {
                    "-verbose",
                    option.optionString,
                    "-source", "8", "-target", "8",
                    "-sourcepath", Dir.SOURCE_PATH.file.getPath(),
                    "-classpath", Dir.CLASS_PATH.file.getPath(),
                    "-Xbootclasspath/p:" + Dir.BOOT_PATH.file.getPath(),
                    "-d", XPreferTest.OUTPUT_DIR.getPath(),
                    explicit.getPath()
            }, new PrintWriter(sw));

            return sw.toString();
        }
 
Example #30
Source Project: cxf   Author: apache   File: WSDLToIDLGenerationTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void testExceptionIdlgen() throws Exception {

    try {
        String fileName = getClass().getResource("/idlgen/exceptions.wsdl").toString();
        idlgen.setWsdlFile(fileName);

        idlgen.setBindingName("TestException.ExceptionTestCORBABinding");
        idlgen.setOutputFile("exceptiontypes.idl");
        idlgen.setPrintWriter(new PrintWriter(idloutput));
        idlgen.generateIDL(null);

        InputStream origstream = getClass().getResourceAsStream("/idlgen/expected_exceptions.idl");
        byte[] orig = inputStreamToBytes(origstream);

        checkIDLStrings(orig, idloutput.toByteArray());
    } finally {
        new File("exceptiontypes.idl").deleteOnExit();
    }
}