List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:org.apache.struts2.interceptor.debugging.DebuggingInterceptor.java
public String intercept(ActionInvocation inv) throws Exception { boolean cont = true; if (devMode) { final ActionContext ctx = ActionContext.getContext(); String type = getParameter(DEBUG_PARAM); ctx.getParameters().remove(DEBUG_PARAM); if (XML_MODE.equals(type)) { inv.addPreResultListener(new PreResultListener() { public void beforeResult(ActionInvocation inv, String result) { printContext();// w w w. j a va2s . c om } }); } else if (CONSOLE_MODE.equals(type)) { consoleEnabled = true; inv.addPreResultListener(new PreResultListener() { public void beforeResult(ActionInvocation inv, String actionResult) { String xml = ""; if (enableXmlWithConsole) { StringWriter writer = new StringWriter(); printContext(new PrettyPrintWriter(writer)); xml = writer.toString(); xml = xml.replaceAll("&", "&"); xml = xml.replaceAll(">", ">"); xml = xml.replaceAll("<", "<"); } ActionContext.getContext().put("debugXML", xml); FreemarkerResult result = new FreemarkerResult(); result.setFreemarkerManager(freemarkerManager); result.setContentType("text/html"); result.setLocation("/org/apache/struts2/interceptor/debugging/console.ftl"); result.setParse(false); try { result.execute(inv); } catch (Exception ex) { log.error("Unable to create debugging console", ex); } } }); } else if (COMMAND_MODE.equals(type)) { ValueStack stack = (ValueStack) ctx.getSession().get(SESSION_KEY); String cmd = getParameter(EXPRESSION_PARAM); ServletActionContext.getRequest().setAttribute("decorator", "none"); HttpServletResponse res = ServletActionContext.getResponse(); res.setContentType("text/plain"); try { PrintWriter writer = ServletActionContext.getResponse().getWriter(); writer.print(stack.findValue(cmd)); writer.close(); } catch (IOException ex) { ex.printStackTrace(); } cont = false; } } if (cont) { try { return inv.invoke(); } finally { if (devMode && consoleEnabled) { final ActionContext ctx = ActionContext.getContext(); ctx.getSession().put(SESSION_KEY, ctx.get(ActionContext.VALUE_STACK)); } } } else { return null; } }
From source file:uk.ac.ebi.embl.api.validation.EnaValidator.java
/** * Validate entries in reader.//from ww w .j a v a 2 s. c o m * * @param writer * the writer * @param targetFile * the target file * @return the list of ValidationPlanResult */ protected List<ValidationPlanResult> validateEntriesInReader(Writer writer, File targetFile, ArrayList<Object> entryList) { List<ValidationPlanResult> validationResults = new ArrayList<ValidationPlanResult>(); try { int currentEntryCount = 0; Object entry = getNextEntryFromReader(writer); if (entryList != null) entryList.add(entry); FileWriter origFileWriter = null; FileWriter fixedFileWriter = null; /** * we write fixed files (if we are fixing) to a temp file, then * replace the original file once we have finished reading the * original file */ File fixedTempFile = new File("./fixedFile_temp.del"); String diagnosisDir = "diagnosis"; /** * for files with errors, we split the original file rather than * write it using the writer, this ensures we have an exact copy of * the original. */ String[] splitEntries = null; String fileString = null; if (filterMode && filterPrefix != null && !FileType.GFF3.equals(fileType)) { File originalFile = new File(targetFile.getPath()); fileString = FileUtils.readFile(new FileInputStream(originalFile)); fileString = fileString.trim(); splitEntries = fileString.split("//"); } if (fixDiagnoseMode) { File diagnoseDir = new File("./" + diagnosisDir); if (!diagnoseDir.exists()) { diagnoseDir.mkdirs(); } origFileWriter = new FileWriter( new File(diagnosisDir + File.separator + targetFile.getName() + "_orig.txt")); fixedFileWriter = new FileWriter( new File(diagnosisDir + File.separator + targetFile.getName() + "_fixed.txt")); } else if (fixMode) { fixedFileWriter = new FileWriter(fixedTempFile); String originalDirString = prefix == null ? "./original_files" : prefix + "_" + "original_files"; File originalsDir = new File(originalDirString); System.out.println(originalsDir.getAbsolutePath()); /** * make the original file dir if does not exist */ if (!originalsDir.exists()) { originalsDir.mkdirs(); } /** * make copies of the original files only if copies have not * been made already */ File copyOfOriginal = new File(originalDirString + File.separator + targetFile.getName()); if (!copyOfOriginal.exists()) { FileUtils.copyFile(targetFile, copyOfOriginal); } } /** * total number of validation messages created */ int totalCount = 0; while (entry != null) { String originalFileString = null; /** * if in diagnosis mode - need to make a copy of the entry * before it gets fixed. Write the entry out to a string and * keep it for writing if any fixes take place. We use the file * writer rather than make a copy of the original file because * we want the file writer to sort the feature table - making * diffs easier to see when comparing with the fixed files. */ if (fixDiagnoseMode) { StringWriter stringWriter = new StringWriter(); if (FileType.GENOMEASSEMBLY.equals(fileType)) { GenomeAssemblyFileWriter.getWriter((GenomeAssemblyRecord) entry).write(stringWriter); } else if (FileType.EMBL.equals(fileType) || FileType.GENBANK.equals(fileType)) { Entry originalEntry = (Entry) reader.getEntry(); EntryWriter entryWriter; if (FileType.EMBL.equals(fileType) || FileType.FASTA.equals(fileType)) { entryWriter = new EmblEntryWriter(originalEntry); } else { entryWriter = new GenbankEntryWriter(originalEntry); } entryWriter.setWrapType(wrapType); entryWriter.write(stringWriter); } stringWriter.close(); originalFileString = stringWriter.toString(); } /** * then validate and fix the entry */ ValidationPlanResult planResult = validateEntry(entry); if (targetFile != null) { planResult.setTargetOrigin(targetFile.getName());// set the validation target to be the file name } if (!suppressedErrorCodes.isEmpty()) { for (String warningCode : suppressedErrorCodes) { planResult.removeMessages(warningCode); } } /** * if we are rewriting de lines - do so here */ if (writeDeMode && entry instanceof Entry) { ValidationResult deValidationResult = DEGenerator.writeDE((Entry) entry); planResult.append(deValidationResult); } /** * if we are sorting the files into good and bad - do so here */ if (filterMode && filterPrefix != null && !(FileType.GFF3.equals(fileType)) && !(FileType.GENOMEASSEMBLY.equals(fileType))) { if (!planResult.getMessages(Severity.ERROR).isEmpty()) { if (splitEntries.length == 1) { badFilesWriter.write(fileString); badFilesWriter.flush(); } else { String entryString = splitEntries[currentEntryCount]; entryString = entryString.concat("\n//\n");// as we will have lost the original when splitting badFilesWriter.write(entryString.trim()); badFilesWriter.flush(); } } else { EntryWriter entryWriter = null; switch (fileType) { case EMBL: case FASTA: case AGP: entryWriter = new EmblEntryWriter((Entry) entry); break; case GENBANK: entryWriter = new GenbankEntryWriter((Entry) entry); break; default: break; } if (entryWriter != null) entryWriter.write(goodFilesWriter); } } /** * if we are fixing in diagnosis mode, see if there were fixes. * if so, write the original and fixed files into the diagnosis * directory. */ if (fixDiagnoseMode) { if (!planResult.getMessages(Severity.FIX).isEmpty()) { File diagnoseDir = new File("./" + diagnosisDir); if (!diagnoseDir.exists()) { diagnoseDir.mkdirs(); } if (originalFileString != null) { origFileWriter.write(originalFileString); } if (FileType.GENOMEASSEMBLY.equals(fileType)) { GenomeAssemblyFileWriter.getWriter((GenomeAssemblyRecord) entry).write(fixedFileWriter); } else { EntryWriter entryWriter; if (FileType.EMBL.equals(fileType) || FileType.FASTA.equals(fileType)) { entryWriter = new EmblEntryWriter((Entry) entry); } else { entryWriter = new GenbankEntryWriter((Entry) entry); } entryWriter.setWrapType(wrapType); Entry Egentry = (Entry) entry; if (!Egentry.isDelete()) { entryWriter.write(fixedFileWriter); } } } } else if (fixMode) { EntryWriter entryWriter = null; Entry Egentry = (Entry) entry; switch (fileType) { case GENOMEASSEMBLY: GenomeAssemblyFileWriter.getWriter((GenomeAssemblyRecord) entry).write(fixedFileWriter); break; case EMBL: case FASTA: case AGP: if (!Egentry.isDelete()) entryWriter = new EmblEntryWriter((Entry) entry); break; case GENBANK: entryWriter = new GenbankEntryWriter((Entry) entry); break; default: break; } if (entryWriter != null) { entryWriter.setWrapType(wrapType); entryWriter.write(fixedFileWriter); } } if (planResult.getMessages(Severity.FIX).size() > 0) { fixCount++; } if (planResult.getMessages(Severity.ERROR).size() > 0) { failCount++; } if (planResult.getMessages(Severity.FIX).size() == 0) { unchangedCount++; } /** * writes to the report files */ writeResultsToFile(planResult); if (!lowMemoryMode) { validationResults.add(planResult); totalCount += planResult.count(); } /** * we go into low memory mode automatically past a certain * threshold */ if (totalCount > LOW_MEMORY_THRESHOLD && !lowMemoryMode) { System.out.println("\n\nEntering low memory mode\n\n"); lowMemoryMode = true; validationResults.clear(); System.gc(); } entry = getNextEntryFromReader(writer); if (entryList != null && entry != null) entryList.add((Entry) entry); totalEntryCount++; currentEntryCount++; } if (origFileWriter != null) { origFileWriter.close(); } if (fixedFileWriter != null) { fixedFileWriter.close(); if (fixMode) { FileUtils.copyFile(fixedTempFile, targetFile); fixedTempFile.delete(); } } } catch (Throwable e) { e.printStackTrace(); printMessageLine("VALIDATOR FAILING", LOG_LEVEL_QUIET); System.exit(1); } return validationResults; }
From source file:org.energy_home.jemma.ah.internal.configurator.Configuratore.java
public String doc2xmlString(Document doc) { final String XML_VERSION = "1.0"; final String XML_ENCODING = "UTF-8"; StringWriter strWriter = null; XMLSerializer probeMsgSerializer = null; OutputFormat outFormat = null;//from w w w . j av a2s . c o m String xmlStr = null; try { probeMsgSerializer = new XMLSerializer(); strWriter = new StringWriter(); outFormat = new OutputFormat(); // Setup format settings outFormat.setEncoding(XML_ENCODING); outFormat.setVersion(XML_VERSION); outFormat.setIndenting(true); outFormat.setIndent(4); // Define a Writer probeMsgSerializer.setOutputCharStream(strWriter); // Apply the format settings probeMsgSerializer.setOutputFormat(outFormat); // Serialize XML Document probeMsgSerializer.serialize(doc); xmlStr = strWriter.toString(); strWriter.close(); } catch (IOException ioEx) { log.error("exception: " + ioEx); return null; } return xmlStr; }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);//from ww w. j ava 2 s . co m } CommandLine cmdLine; if (execPath != null) { // Run the configured calibre ebook-convert executable logger.info("Calibre ebook-convert will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Calibre ebook-convert will be run within the PATH variable."); cmdLine = new CommandLine(command); } // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString()); cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString()); // Output will be in format "KF8" only, old format does not allow external CSS files cmdLine.addArgument("--mobi-file-type=new"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(calibreStreamHandler); logger.debug("Launching calibres ebook-convert:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("calibres ebook-convert failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("calibre ebook-converts execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) { logger.error("calibres ebook-convert could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("calibre ebook-converts execution got interrupted: "); logger.error(e.getMessage(), e); } String output = ""; try { output += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading calibre ebook-converts output from buffer:"); logger.error(e.getMessage(), e); } logger.debug("Calibre ebook-convert output: \n" + output); return tempMobiFilepath.toFile(); }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);//from www .jav a2 s . com } CommandLine cmdLine; if (execPath != null) { // Run the configured kindlegen executable logger.info("Kindlegen will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Kindlegen will be run within the PATH variable."); cmdLine = new CommandLine(command); } // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); cmdLine.addArgument("-c0"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter stdoutWriter = new StringWriter(); StringWriter stderrWriter = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8")); WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8")); ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream); executor.setStreamHandler(kindlegenStreamHandler); logger.debug("Launching kindlegen:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Kindlegen failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Kindlegen execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"kindlegen\"")) { logger.error("Kindlegen could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("Kindlegen's execution got interrupted: "); logger.error(e.getMessage(), e); } try { String stderrOutput = stderrWriter.getBuffer().toString(); stderrWriter.close(); if (stderrOutput.isEmpty() == false) { logger.error("Kindlegen logged some errors:"); logger.error(stderrOutput); } } catch (IOException e) { logger.error("Error closing kindlegen's stderr buffer"); logger.error(e.getMessage(), e); } String output = ""; try { output += stdoutWriter.getBuffer().toString(); stdoutWriter.close(); } catch (IOException e) { logger.error("Error closing kindlegen's stdout buffer:"); logger.error(e.getMessage(), e); } logger.debug("Kindlegen output: \n" + output); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); logger.debug("Moving Kindlegen output file: " + mobiFilename); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); return tempMobiFilepath.toFile(); }
From source file:org.eclipse.winery.repository.resources.servicetemplates.plans.PlansResourceData.java
/** * Data object for the JSP//from w w w . j a v a2 s . co m * * @param plans the plans this resource manages */ public PlansResourceData(List<TPlan> plans) { if (plans.isEmpty()) { this.embeddedPlansTableData = "[]"; this.linkedPlansTableData = "[]"; return; } JsonFactory jsonFactory = new JsonFactory(); StringWriter embeddedPlansTableDataSW = new StringWriter(); StringWriter linkedPlansTableDataSW = new StringWriter(); try { JsonGenerator jGeneratorEmbedded = jsonFactory.createGenerator(embeddedPlansTableDataSW); JsonGenerator jGeneratorLinked = jsonFactory.createGenerator(linkedPlansTableDataSW); jGeneratorEmbedded.writeStartArray(); jGeneratorLinked.writeStartArray(); for (TPlan plan : plans) { String name = plan.getName(); if (name == null) { // name defaults to id name = plan.getId(); } String type = PlanTypesManager.INSTANCE.getShortName(plan.getPlanType()); String language = PlanLanguagesManager.INSTANCE.getShortName(plan.getPlanLanguage()); PlanModelReference planModelReference = plan.getPlanModelReference(); String reference = planModelReference != null ? planModelReference.getReference() : null; JsonGenerator gen; boolean writeReference; if (reference == null) { gen = jGeneratorEmbedded; writeReference = false; } else if (reference.startsWith("../")) { gen = jGeneratorEmbedded; writeReference = false; } else { gen = jGeneratorLinked; writeReference = true; } gen.writeStartArray(); gen.writeString(plan.getId()); gen.writeString(""); // precondition gen.writeString(name); gen.writeString(type); gen.writeString(language); if (writeReference) { gen.writeString(reference); } gen.writeEndArray(); } jGeneratorEmbedded.writeEndArray(); jGeneratorLinked.writeEndArray(); jGeneratorEmbedded.close(); embeddedPlansTableDataSW.close(); jGeneratorLinked.close(); linkedPlansTableDataSW.close(); } catch (JsonGenerationException e) { PlansResourceData.LOGGER.error(e.getMessage(), e); this.embeddedPlansTableData = "[]"; this.linkedPlansTableData = "[]"; return; } catch (IOException e) { PlansResourceData.LOGGER.error("", e); this.embeddedPlansTableData = "[]"; this.linkedPlansTableData = "[]"; return; } this.embeddedPlansTableData = embeddedPlansTableDataSW.toString(); this.linkedPlansTableData = linkedPlansTableDataSW.toString(); }
From source file:org.pentaho.di.core.Const.java
public static final String getClassicStackTrace(Throwable e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter);/*from w w w. j a va 2 s . c o m*/ String string = stringWriter.toString(); try { stringWriter.close(); } catch (IOException ioe) { // is this really required? } return string; }
From source file:org.opcfoundation.ua.stacktest.io.BetwixtTestLog.java
private void write() { try {/*from w w w .ja v a2 s . co m*/ // Start by preparing the writer // We'll write to a string StringWriter outputWriter = new StringWriter(); // Betwixt just writes out the bean as a fragment // So if we want well-formed xml, we need to add the prolog outputWriter.write("<?xml version='1.0' ?>\n"); // create write and set basic properties BeanWriter beanWriter = new BeanWriter(outputWriter); //writer.getXMLIntrospector().setAttributesForPrimitives(true); beanWriter.enablePrettyPrint(); beanWriter.setInitialIndentLevel(0); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.getBindingConfiguration().setObjectStringConverter(new DateConverter()); /* new ObjectStringConverter() { public String objectToString(Object object, Class type, Context context) { if (object == null) return ""; else if (GregorianCalendar.class.equals(context.getBean().getClass())) return ((GregorianCalendar) context.getBean()).getTime().toString(); else if (GregorianCalendar.class.equals(type)) return ((GregorianCalendar) object).getTime().toString(); else return object.toString(); } } ); */ // set a custom name mapper for attributes beanWriter.getXMLIntrospector().getConfiguration().setAttributeNameMapper(new CapitalizeNameMapper()); // set a custom name mapper for elements beanWriter.getXMLIntrospector().getConfiguration().setElementNameMapper(new CapitalizeNameMapper()); /* beanWriter.getXMLIntrospector().getConfiguration().setPropertySuppressionStrategy( new PropertySuppressionStrategy() { public boolean suppressProperty(Class clazz, Class type, String name) { return "class".equals(name) || GregorianCalendar.class.equals(type); } }); */ // write out the bean beanWriter.write(testLog); System.out.println(outputWriter.toString()); outputWriter.close(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.netbeans.nbbuild.MakeJnlp2.java
private void generateVersionXMLFiles() throws IOException { FileSet fs = new FileSet(); fs.setIncludes("**/*.jar"); for (File directory : jarDirectories) { fs.setDir(directory);//w w w .j a v a2 s.c o m DirectoryScanner scan = fs.getDirectoryScanner(getProject()); StringWriter writeVersionXML = new StringWriter(); writeVersionXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writeVersionXML.append("<jnlp-versions>\n"); for (String jarName : scan.getIncludedFiles()) { File jar = new File(scan.getBasedir(), jarName); JarFile jarFile = new JarFile(jar); String version = getJarVersion(jarFile); if (version != null) { writeVersionXML.append(" <resource>\n <pattern>\n <name>"); writeVersionXML.append(jar.getName()); writeVersionXML.append("</name>\n <version-id>"); writeVersionXML.append(version); writeVersionXML.append("</version-id>\n </pattern>\n <file>"); writeVersionXML.append(jar.getName()); writeVersionXML.append("</file>\n </resource>\n"); } else { writeVersionXML.append(" <!-- No version found for "); writeVersionXML.append(jar.getName()); writeVersionXML.append(" -->\n"); } } writeVersionXML.append("</jnlp-versions>\n"); writeVersionXML.close(); File versionXML = new File(directory, "version.xml"); FileWriter w = new FileWriter(versionXML); w.write(writeVersionXML.toString()); w.close(); } }