Java Code Examples for java.io.StringWriter.flush()

The following are Jave code examples for showing how to use flush() of the java.io.StringWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: VASSAL-src   File: SVGImageUtils.java   View Source Code Vote up 6 votes
/**
 * Rewrites external references contained in SVG files.
 *
 * @param path the path of the file to be processed
 */
public static byte[] relativizeExternalReferences(String path)
                                                         throws IOException {
  // use the GenericDOMImplementation here because
  // SVGDOMImplementation adds unwanted attributes to SVG elements
  final SAXDocumentFactory fac = new SAXDocumentFactory(
    new GenericDOMImplementation(),
    XMLResourceDescriptor.getXMLParserClassName());

  final URL here = new URL("file", null, new File(path).getCanonicalPath());
  final StringWriter sw = new StringWriter();

  try {
    final Document doc = fac.createDocument(here.toString());
    relativizeElement(doc.getDocumentElement());
    DOMUtilities.writeDocument(doc, sw);
  }
  catch (DOMException e) {
    throw (IOException) new IOException().initCause(e);
  }

  sw.flush();
  return sw.toString().getBytes();
}
 
Example 2
Project: uavstack   File: Logger.java   View Source Code Vote up 6 votes
private String exception2String(Throwable e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();

        return sw.toString();
    }
 
Example 3
Project: beaker-notebook-archive   File: GetCodeCellsHandler.java   View Source Code Vote up 6 votes
private List<BeakerCodeCell> getBeakerCodeCells(Object value) {
  List<BeakerCodeCell> beakerCodeCellList = null;
  StringWriter sw = new StringWriter();
  JsonGenerator jgen = null;
  try {
    jgen = objectMapper.getFactory().createGenerator(sw);
    objectSerializer.writeObject(value, jgen, true);
    jgen.flush();
    sw.flush();
    beakerCodeCellList = Arrays.asList(objectMapper.readValue(sw.toString(), BeakerCodeCell[].class));
  } catch (IOException e) {
    e.printStackTrace();
  }

  return beakerCodeCellList;
}
 
Example 4
Project: custom-bytecode-analyzer   File: ZipEntryDecompiler.java   View Source Code Vote up 6 votes
@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 5
Project: MMORPG_Prototype   File: JsonUserType.java   View Source Code Vote up 6 votes
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
        throws HibernateException, SQLException
{
    if (value == null)
    {
        st.setNull(index, Types.VARCHAR);
        return;
    }
    try
    {
        final ObjectMapper mapper = new ObjectMapper();
        final StringWriter w = new StringWriter();
        mapper.writeValue(w, value);
        w.flush();
        st.setObject(index, w.toString(), Types.VARCHAR);
    } catch (final Exception ex)
    {
        throw new RuntimeException("Failed to convert Invoice to String: " + ex.getMessage(), ex);
    }

}
 
Example 6
Project: openjdk-jdk10   File: XMLStreamWriterTest.java   View Source Code Vote up 6 votes
/**
 * Test of main method, of class TestXMLStreamWriter.
 */
@Test
public void testWriteComment() {
    try {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a:html href=\"http://java.sun.com\"><!--This is comment-->java.sun.com</a:html>";
        XMLOutputFactory f = XMLOutputFactory.newInstance();
        // f.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES,
        // Boolean.TRUE);
        StringWriter sw = new StringWriter();
        XMLStreamWriter writer = f.createXMLStreamWriter(sw);
        writer.writeStartDocument("UTF-8", "1.0");
        writer.writeStartElement("a", "html", "http://www.w3.org/TR/REC-html40");
        writer.writeAttribute("href", "http://java.sun.com");
        writer.writeComment("This is comment");
        writer.writeCharacters("java.sun.com");
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        sw.flush();
        StringBuffer sb = sw.getBuffer();
        System.out.println("sb:" + sb.toString());
        Assert.assertTrue(sb.toString().equals(xml));
    } catch (Exception ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
 
Example 7
Project: incubator-netbeans   File: Utils.java   View Source Code Vote up 5 votes
/**
 * 
 */
public static String exc2String(Throwable t) {
    StringWriter writer = new StringWriter();
    t.printStackTrace(new PrintWriter(writer));
    writer.flush();
    return writer.toString();
}
 
Example 8
Project: alfresco-repository   File: BulkImportStatusImpl.java   View Source Code Vote up 5 votes
public String getLastExceptionAsString()
{
    String result = null;

	readLock.lock();
    try
    {
     if (lastException != null)
     {
         StringWriter sw = new StringWriter();
         PrintWriter  pw = new PrintWriter(sw, true);
         
         lastException.printStackTrace(pw);
         
         pw.flush();
         sw.flush();
         
         result = sw.toString();
     }
     
     return(result);
	}
	finally
	{
		readLock.unlock();
	}
}
 
Example 9
Project: uavstack   File: DataConvertHelper.java   View Source Code Vote up 5 votes
public static final String exception2String(Throwable e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
 
Example 10
Project: openjdk-jdk10   File: DocCommentTester.java   View Source Code Vote up 5 votes
void check(TreePath path, Name name) {
    StringWriter out = new StringWriter();
    DocCommentTree dc = trees.getDocCommentTree(path);
    printer.print(dc, out);
    out.flush();
    String found = out.toString().replace(NEWLINE, "\n");

    /*
     * Look for the first block comment after the first occurrence
     * of name, noting that, block comments with BI_MARKER may
     * very well be present.
     */
    int start = test.useBreakIterator
            ? source.indexOf("\n/*\n" + BI_MARKER + "\n", findName(source, name))
            : source.indexOf("\n/*\n", findName(source, name));
    int end = source.indexOf("\n*/\n", start);
    int startlen = start + (test.useBreakIterator ? BI_MARKER.length() + 1 : 0) + 4;
    String expect = source.substring(startlen, end + 1);
    if (!found.equals(expect)) {
        if (test.useBreakIterator) {
            System.err.println("Using BreakIterator");
        }
        System.err.println("Expect:\n" + expect);
        System.err.println("Found:\n" + found);
        error("AST mismatch for " + name);
    }
}
 
Example 11
Project: org.alloytools.alloy   File: SimpleCLI.java   View Source Code Vote up 5 votes
private static void validate(A4Solution sol) throws Exception {
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw);
	sol.writeXML(pw, null, null);
	pw.flush();
	sw.flush();
	String txt = sw.toString();
	A4SolutionReader.read(new ArrayList<Sig>(), new XMLNode(new StringReader(txt))).toString();
	StaticInstanceReader.parseInstance(new StringReader(txt));
}
 
Example 12
Project: org.alloytools.alloy   File: MailBug.java   View Source Code Vote up 5 votes
/** This method prepares the crash report. */
private static String prepareCrashReport(Thread thread, Throwable ex, String email, String problem) {
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw);
	pw.printf("Alloy Analyzer %s crash report (Build Date = %s) (Commit = %s)\n", Version.version(),
			Version.commit);
	pw.printf("\n========================= Email ============================\n%s\n",
			Util.convertLineBreak(email).trim());
	pw.printf("\n========================= Problem ==========================\n%s\n",
			Util.convertLineBreak(problem).trim());
	pw.printf("\n========================= Thread Name ======================\n%s\n", thread.getName().trim());
	if (ex != null)
		pw.printf("\n========================= Stack Trace ======================\n%s\n", dump(ex));
	pw.printf("\n========================= Preferences ======================\n");
	try {
		for (String key : Preferences.userNodeForPackage(Util.class).keys()) {
			String value = Preferences.userNodeForPackage(Util.class).get(key, "");
			pw.printf("%s = %s\n", key.trim(), value.trim());
		}
	} catch (BackingStoreException bse) {
		pw.printf("BackingStoreException occurred: %s\n", bse.toString().trim());
	}
	pw.printf("\n========================= System Properties ================\n");
	pw.println("Runtime.freeMemory() = " + Runtime.getRuntime().freeMemory());
	pw.println("nRuntime.totalMemory() = " + Runtime.getRuntime().totalMemory());
	for (Map.Entry<Object,Object> e : System.getProperties().entrySet()) {
		String k = String.valueOf(e.getKey()), v = String.valueOf(e.getValue());
		pw.printf("%s = %s\n", k.trim(), v.trim());
	}
	pw.printf("\n========================= The End ==========================\n\n");
	pw.close();
	sw.flush();
	return sw.toString();
}
 
Example 13
Project: lams   File: IMSJSONRequest.java   View Source Code Vote up 5 votes
@SuppressWarnings("static-access")
public static String doErrorJSON(HttpServletRequest request,HttpServletResponse response, 
		IMSJSONRequest json, String message, Exception e) 
	throws java.io.IOException 
{
	response.setContentType(APPLICATION_JSON);
	Map<String, Object> jsonResponse = new TreeMap<String, Object>();

	Map<String, String> status = null;
	if ( json == null ) {
		status = IMSJSONRequest.getStatusFailure(message);
	} else {
		status = json.getStatusFailure(message);
		if ( json.base_string != null ) {
			jsonResponse.put("base_string", json.base_string);
		}
	}
	jsonResponse.put(IMSJSONRequest.STATUS, status);
	if ( e != null ) {
		jsonResponse.put("exception", e.getLocalizedMessage());
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw, true);
			e.printStackTrace(pw);
			pw.flush();
			sw.flush();
			jsonResponse.put("traceback", sw.toString() );
		} catch ( Exception f ) {
			jsonResponse.put("traceback", f.getLocalizedMessage());
		}
	}
	Gson gson = new Gson(); 
	String jsonText = gson.toJson(jsonResponse);
	PrintWriter out = response.getWriter();
	out.println(jsonText);
	return jsonText;
}
 
Example 14
Project: openjdk-jdk10   File: BoxingAndSuper.java   View Source Code Vote up 5 votes
private void runTest(String code, String expectedDesugar) throws Exception {
    List<JavaFileObject> files = List.nil();

    for (String file : code.split("---")) {
        files = files.prepend(new ToolBox.JavaSource(file));
    }

    Path classes = Paths.get("classes");

    if (Files.exists(classes)) {
        tb.cleanDirectory(classes);
    } else {
        Files.createDirectories(classes);
    }

    JavacTool compiler = (JavacTool) ToolProvider.getSystemJavaCompiler();
    StringWriter out = new StringWriter();
    Context context = new Context();
    TestLower.preRegister(context);
    Iterable<String> options = Arrays.asList("-d", classes.toString());
    JavacTask task = (JavacTask) compiler.getTask(out, null, null, options, null, files, context);

    task.generate();

    out.flush();

    String actual = out.toString().replace(System.getProperty("line.separator"), "\n");

    if (!expectedDesugar.equals(actual)) {
        throw new IllegalStateException("Actual does not match expected: " + actual);
    }
}
 
Example 15
Project: unitimes   File: EventEmail.java   View Source Code Vote up 5 votes
private String message() throws IOException, TemplateException {
	Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
	cfg.setClassForTemplateLoading(EventEmail.class, "");
	cfg.setLocale(Localization.getJavaLocale());
	cfg.setOutputEncoding("utf-8");
	Template template = cfg.getTemplate("confirmation.ftl");
	Map<String, Object> input = new HashMap<String, Object>();
	input.put("msg", MESSAGES);
	input.put("const", CONSTANTS);
	input.put("subject", subject());
	input.put("event", event());
	input.put("operation", request().getOperation() == null ? "NONE" : request().getOperation().name());
	if (response().hasCreatedMeetings())
		input.put("created", EventInterface.getMultiMeetings(response().getCreatedMeetings(), true, false));
	if (response().hasDeletedMeetings())
		input.put("deleted", EventInterface.getMultiMeetings(response().getDeletedMeetings(), true, false));
	if (response().hasCancelledMeetings())
		input.put("cancelled", EventInterface.getMultiMeetings(response().getCancelledMeetings(), true, false));
	if (response().hasUpdatedMeetings())
		input.put("updated", EventInterface.getMultiMeetings(response().getUpdatedMeetings(), true, false));
	if (request().hasMessage())
		input.put("message", request().getMessage());
	if (request().getEvent().getId() != null) {
		if (event().hasMeetings()) {
			input.put("meetings", EventInterface.getMultiMeetings(event().getMeetings(), true, false));
		} else
			input.put("meetings", new TreeSet<MultiMeetingInterface>());
	}
	input.put("version", MESSAGES.pageVersion(Constants.getVersion(), Constants.getReleaseDate()));
	input.put("ts", new Date());
	input.put("link", ApplicationProperty.UniTimeUrl.value());
	input.put("sessionId", iRequest.getSessionId());
	
	StringWriter s = new StringWriter();
	template.process(input, new PrintWriter(s));
	s.flush(); s.close();

	return s.toString();
}
 
Example 16
Project: jaffa-framework   File: SOAEventServer.java   View Source Code Vote up 5 votes
/** Publishes a Message, based on the Event, to the appropriate Topic.
 */
private void processSOAEvent(SOAEvent event) throws FrameworkException {
    if (log.isDebugEnabled())
        log.debug("Processing " + event);
    UserContextWrapper ucw = null;
    try {
        setServerState(ServerState.PROCESSING);
        setEvent(event);
        ucw = UserContextWrapperFactory.instance(event.getCreatedBy());
        publishMessage(event);
    } catch (Exception e) {
        log.error("Failed To Process event " + event, e);
        if (log.isDebugEnabled())
            log.debug("Reporting error by sending an email to the Administrator");
        StringBuffer body = new StringBuffer("An Internal Error occured in the SOA Event Server while processing the SOAEvent\n");
        body.append(event).append('\n').append('\n');
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        sw.flush();
        body.append(sw.toString()).append('\n').append('\n');
        EmailerBean eb = new EmailerBean();
        try {
            eb.sendMail(new String[] {eb.getAdministrator()}, "ERROR - SOA Event Server", body.toString());
        } catch (Exception e2) {
            log.fatal("Cannot email error message to Administrator " + eb.getAdministrator(), e2);
        }
    } finally {
        cleanup(event);
        if (ucw != null)
            ucw.unsetContext();
    }
}
 
Example 17
Project: aliyun-maxcompute-data-collectors   File: ToolOptions.java   View Source Code Vote up 5 votes
@Override
public String toString() {
  StringWriter sw = new StringWriter();
  printHelp(new HelpFormatter(), new PrintWriter(sw));
  sw.flush();
  return sw.getBuffer().toString();
}
 
Example 18
Project: arez   File: SpyEventRecorder.java   View Source Code Vote up 5 votes
@Nonnull
String eventsAsString()
{
  final Map<String, Object> properties = new HashMap<>( 1 );
  properties.put( JsonGenerator.PRETTY_PRINTING, true );
  final StringWriter writer = new StringWriter();
  Json.createWriterFactory( properties ).createWriter( writer ).write( getEvents().build() );
  writer.flush();
  return writer.toString();
}
 
Example 19
Project: dremio-oss   File: MethodGrabbingVisitor.java   View Source Code Vote up 5 votes
@Override
    public void traverseMethodDeclarator(MethodDeclarator md) {
//      logger.debug(c.getName() + ": Found {}, include {}", md.name, captureMethods);

      if(captureMethods){
        StringWriter writer = new StringWriter();
        ModifiedUnparseVisitor v = new ModifiedUnparseVisitor(writer);
//        UnparseVisitor v = new UnparseVisitor(writer);

        md.accept(v);
        v.close();
        writer.flush();
        methods.put(md.name, writer.getBuffer().toString());
      }
    }
 
Example 20
Project: traute   File: JavacTestCompiler.java   View Source Code Vote up 4 votes
@Override
@NotNull
public CompilationResult compile(@NotNull Collection<TestSource> testSources,
                                 @NotNull TrautePluginSettings settings)
{
    StringWriter output = new StringWriter();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    SimpleFileManager fileManager = new SimpleFileManager(compiler.getStandardFileManager(
            null,
            null,
            null
    ));
    List<SimpleSourceFile> compilationUnits = testSources.stream().map(SimpleSourceFile::new).collect(toList());
    List<String> arguments = new ArrayList<>();
    arguments.addAll(asList("-classpath", System.getProperty("java.class.path")));
    arguments.addAll(getAdditionalCompilerArgs(settings));
    JavaCompiler.CompilationTask task = compiler.getTask(output,
                                                         fileManager,
                                                         null,
                                                         arguments,
                                                         null,
                                                         compilationUnits);
    Boolean successfulCompilation = task.call();
    output.flush();
    if (!successfulCompilation) {
        return new CompilationResultImpl(() -> {
            throw new IllegalStateException(String.format(
                    "Failed to compile test class sources below:%n%n%s%nCompiler output: %s",
                    TestUtil.getSources(testSources), output));
            }, output.toString(), testSources);
    }

    Supplier<Collection<ClassFile>> compiledClassesSupplier = () -> {
        List<SimpleClassFile> compiledJavacClasses = fileManager.getCompiled();
        return compiledJavacClasses.stream().map(c -> {
            String className = c.getUri()
                                .getSchemeSpecificPart()
                                .replaceAll("/", "");
            return new ClassFileImpl(className, c.getCompiledBinaries());
        }).collect(toList());
    };

    return new CompilationResultImpl(compiledClassesSupplier, output.toString(), testSources);
}