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

The following examples show how to use java.io.StringWriter#flush() . 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: IMSJSONRequest.java    From lams with GNU General Public License v2.0 7 votes vote down vote up
@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 2
Source File: XMLStreamWriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 3
Source File: ZipEntryDecompiler.java    From custom-bytecode-analyzer with GNU General Public License v3.0 6 votes vote down vote up
@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 4
Source File: DocCommentTester.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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
    int start = source.indexOf("\n/*\n", findName(source, name));
    int end = source.indexOf("\n*/\n", start);
    String expect = source.substring(start + 4, end + 1);
    if (!found.equals(expect)) {
        System.err.println("Expect:\n" + expect);
        System.err.println("Found:\n" + found);
        error("AST mismatch for " + name);
    }
}
 
Example 5
Source File: XhtmlGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public String generateInsert(Document doc, String name, String desc) throws Exception {
  StringWriter out = new StringWriter();
  
  out.write("<div class=\"example\">\r\n");
  out.write("<p>Example Instance \""+name+"\""+(desc == null ? "" : ": "+Utilities.escapeXml(desc))+"</p>\r\n"); 
  out.write("<pre class=\"xml\">\r\n");

  XhtmlGeneratorAdornerState state = null; // adorner == null ? new XhtmlGeneratorAdornerState("", "") : adorner.getState(this, null, null);
  for (int i = 0; i < doc.getChildNodes().getLength(); i++)
    writeNode(out, doc.getChildNodes().item(i), state, 0);
  
  out.write("</pre>\r\n");
  out.write("</div>\r\n");
  out.flush();
  return out.toString();
}
 
Example 6
Source File: DocCommentTester.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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
    int start = source.indexOf("\n/*\n", findName(source, name));
    int end = source.indexOf("\n*/\n", start);
    String expect = source.substring(start + 4, end + 1);
    if (!found.equals(expect)) {
        System.err.println("Expect:\n" + expect);
        System.err.println("Found:\n" + found);
        error("AST mismatch for " + name);
    }
}
 
Example 7
Source File: DbLogInterceptor.java    From Aooms with Apache License 2.0 6 votes vote down vote up
@Override
public void finalHandle(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    Record record = (Record) request.getAttribute(DB_LOGGER);
    if(record != null){
        DbLogService dbLogService = (DbLogService)SpringUtils.getApplicationContext().getBean("dbLogService");
        if(ex != null){
            StringWriter stackTrace = new StringWriter();
            ex.printStackTrace(new PrintWriter(stackTrace));
            stackTrace.flush();
            record.set("status", "1");
            record.set("trace", stackTrace.toString());
        }

        long start = record.getLong("cost");
        record.set("cost", (System.currentTimeMillis() - start) / 1000); // 单位:s
        dbLogService.saveLog(record);
    }
}
 
Example 8
Source File: DocCommentTester.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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
    int start = source.indexOf("\n/*\n", findName(source, name));
    int end = source.indexOf("\n*/\n", start);
    String expect = source.substring(start + 4, end + 1);
    if (!found.equals(expect)) {
        System.err.println("Expect:\n" + expect);
        System.err.println("Found:\n" + found);
        error("AST mismatch for " + name);
    }
}
 
Example 9
Source File: TemplateUtil.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static String loadTemplate(String templateName) {
    try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(templateName)) {
        if (is == null) {
            throw new IllegalStateException("unable to find " + templateName);
        }
        try (InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
             BufferedReader bufferedReader = new BufferedReader(reader)) {
            StringWriter writer = new StringWriter();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                writer.append(line).append(System.lineSeparator());
            }
            writer.flush();
            return writer.toString();
        }
    } catch (Exception e) {
        throw new IllegalStateException("unable to load template " + templateName, e);
    }
}
 
Example 10
Source File: AvroCompatibilityHelperTest.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void assertCompiles(Collection<AvroGeneratedSourceCode> generatedCode) throws Exception {

    //write out generated code into a source tree
    Path tempRootFolder = Files.createTempDirectory(null);
    File[] fileArray = new File[generatedCode.size()];
    int i=0;
    for (AvroGeneratedSourceCode avroGeneratedSourceCode : generatedCode) {
      fileArray[i++] = avroGeneratedSourceCode.writeToDestination(tempRootFolder.toFile());
    }

    //spin up a java compiler task, use current runtime classpath, point at source tree created above
    List<String> optionList = new ArrayList<>();
    optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(fileArray);
    StringWriter compilerOutput = new StringWriter();
    JavaCompiler.CompilationTask task = compiler.getTask(compilerOutput, fileManager, null, optionList, null, javaFileObjects);
    compilerOutput.flush();

    //compile, assert no errors
    Assert.assertTrue(task.call(), "compilation failed with " + compilerOutput.toString());
  }
 
Example 11
Source File: BoxingAndSuper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 12
Source File: MailBug.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/** 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
Source File: SimpleCLI.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
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 14
Source File: BulkImportStatusImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 15
Source File: ToolOptions.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  StringWriter sw = new StringWriter();
  printHelp(new HelpFormatter(), new PrintWriter(sw));
  sw.flush();
  return sw.getBuffer().toString();
}
 
Example 16
Source File: VelocityUtil.java    From sc-generator with Apache License 2.0 5 votes vote down vote up
public static String writerGeneratorConfig(String url, String username, String password, String driverClass,
		String packagePath, String targetPath, List<String> tables) throws IOException, SQLException {
	VelocityContext ctx = new VelocityContext();
	Template template = getTempate("templates/generatorConfig.vm");
	ctx.put("url", url);
	ctx.put("username", username);
	ctx.put("password", password);
	ctx.put("driverClass", driverClass);
	ctx.put("tables", tables);

	Map<String, String> primaryKeys = new HashMap<>();

	Connection connection = DriverManager.getConnection(url, username, password);
	for (String tableName : tables) {
		String primaryKey = TblUtil.getPrimaryKey(connection, tableName);
		String key = toHump(primaryKey);
		primaryKeys.put(tableName, key);
	}
	ctx.put("primaryKeys", primaryKeys);
	List<String> models = new ArrayList<String>();
	for (String table : tables) {
		String modelName = tableNameConvertModelName(table);
		models.add(modelName);
	}
	ctx.put("models", models);
	ctx.put("packagePath", packagePath);
	ctx.put("targetPath", targetPath);
	StringWriter writer = new StringWriter();
	template.merge(ctx, writer);
	writer.flush();
	writer.close();
	return writer.toString();
}
 
Example 17
Source File: DataConvertHelper.java    From uavstack with Apache License 2.0 5 votes vote down vote up
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 18
Source File: SmartOperateLogAspect.java    From smart-admin with MIT License 4 votes vote down vote up
protected void handleLog(final JoinPoint joinPoint, final Exception e) {
    try {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        OperateLog operateLog = this.getAnnotationLog(joinPoint);
        if (operateLog == null) {
            return;
        }
        RequestTokenBO requestToken = SmartRequestTokenUtil.getRequestUser();
        if (requestToken == null) {
            return;
        }
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String operateMethod = className + "." + methodName;
        Object[] args = joinPoint.getArgs();
        StringBuilder sb = new StringBuilder();
        for (Object obj : args) {
            sb.append(obj.getClass().getSimpleName());
            sb.append("[");
            sb.append(JSON.toJSONString(obj));
            sb.append("]");
        }
        String params = sb.toString();
        String failReason = null;
        Integer result = JudgeEnum.YES.getValue();
        if (e != null) {
            result = JudgeEnum.NO.getValue();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            failReason = sw.toString();
            pw.flush();
            pw.close();
            sw.flush();
            sw.close();
        }
        UserOperateLogEntity operateLogEntity =
            UserOperateLogEntity.builder().userId(requestToken.getRequestUserId()).userName(requestToken.getEmployeeBO().getActualName()).url(request.getRequestURI()).method(operateMethod).param(params).failReason(failReason).result(result).build();
        ApiOperation apiOperation = this.getApiOperation(joinPoint);
        if (apiOperation != null) {
            operateLogEntity.setContent(apiOperation.value());
        }
        Api api = this.getApi(joinPoint);
        if (api != null) {
            String[] tags = api.tags();
            operateLogEntity.setModule(SmartStringUtil.join(tags, ","));
        }
        logService.addLog(operateLogEntity);
    } catch (Exception exp) {
        log.error("保存操作日志异常:{}", exp.getMessage());
        exp.printStackTrace();
    }
}
 
Example 19
Source File: QuartzTask.java    From smart-admin with MIT License 4 votes vote down vote up
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    JobDetail jobDetail = context.getJobDetail();
    Object params = jobDetail.getJobDataMap().get(QuartzConst.QUARTZ_PARAMS_KEY);
    JobKey jobKey = jobDetail.getKey();

    Long taskId = SmartQuartzUtil.getTaskIdByJobKey(jobKey);
    QuartzTaskService quartzTaskService = (QuartzTaskService) SmartApplicationContext.getBean("quartzTaskService");
    QuartzTaskEntity quartzTaskEntity = quartzTaskService.getByTaskId(taskId);

    QuartzTaskLogService quartzTaskLogService = (QuartzTaskLogService) SmartApplicationContext.getBean("quartzTaskLogService");

    QuartzTaskLogEntity taskLogEntity = new QuartzTaskLogEntity();
    taskLogEntity.setTaskId(taskId);
    taskLogEntity.setIpAddress(SmartIPUtil.getLocalHostIP());
    taskLogEntity.setTaskName(quartzTaskEntity.getTaskName());
    String paramsStr = null;
    if (params != null) {
        paramsStr = params.toString();
        taskLogEntity.setTaskParams(paramsStr);
    }
    taskLogEntity.setUpdateTime(new Date());
    taskLogEntity.setCreateTime(new Date());
    //任务开始时间
    long startTime = System.currentTimeMillis();
    try {
        ITask taskClass = (ITask) SmartApplicationContext.getBean(quartzTaskEntity.getTaskBean());
        taskClass.execute(paramsStr);
        taskLogEntity.setProcessStatus(TaskResultEnum.SUCCESS.getStatus());
    } catch (Exception e) {
        log.error("", e);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        taskLogEntity.setProcessStatus(TaskResultEnum.FAIL.getStatus());
        taskLogEntity.setProcessLog(sw.toString());
    } finally {
        long times = System.currentTimeMillis() - startTime;
        taskLogEntity.setProcessDuration(times);
        quartzTaskLogService.save(taskLogEntity);
    }

}
 
Example 20
Source File: MethodGrabbingVisitor.java    From Bats with Apache License 2.0 4 votes vote down vote up
@Override
public void traverseMethodDeclarator(MethodDeclarator methodDeclarator) {
  if (captureMethods) {
    // Generates a "labeled statement".
    // This code takes code from the method body, wraps it into the labeled statement
    // and replaces all the return statements by break command with label.
    //
    // For example, the following method
    //    public void foo(int a) {
    //      if (a < 0) {
    //        return;
    //      } else {
    //        do something;
    //      }
    //    }
    //
    // will be converted to
    //    MethodClassName_foo: {
    //      if (a < 0) {
    //        break MethodClassName_foo;
    //      } else {
    //        do something;
    //      }
    //    }

    // Constructs a name of the resulting label
    // using methods class name and method name itself.
    String[] fQCN = methodDeclarator.getDeclaringType().getClassName().split("\\.");
    String returnLabel = fQCN[fQCN.length - 1] + "_" + methodDeclarator.name;
    Java.Block methodBodyBlock = new Java.Block(methodDeclarator.getLocation());

    // DeepCopier implementation which returns break statement with label
    // instead if return statement.
    DeepCopier returnStatementReplacer = new DeepCopier() {
      @Override
      public Java.BlockStatement copyReturnStatement(Java.ReturnStatement subject) {
        return new Java.BreakStatement(subject.getLocation(), returnLabel);
      }
    };
    try {
      // replaces return statements and stores the result into methodBodyBlock
      methodBodyBlock.addStatements(
          returnStatementReplacer.copyBlockStatements(methodDeclarator.optionalStatements));
    } catch (CompileException e) {
      throw new RuntimeException(e);
    }

    // wraps method code with replaced return statements into label statement.
    Java.LabeledStatement labeledStatement =
        new Java.LabeledStatement(methodDeclarator.getLocation(), returnLabel, methodBodyBlock);

    // Unparse the labeled statement.
    StringWriter writer = new StringWriter();
    Unparser unparser = new Unparser(writer);
    // unparses labeledStatement and stores unparsed code into writer
    unparser.unparseBlockStatement(labeledStatement);
    unparser.close();
    writer.flush();
    methods.put(methodDeclarator.name, writer.getBuffer().toString());
  }
}