/** * Get the writer for the import file * * @param destination the destination XML import file * @return the XML writer */ private XMLWriter getWriter(String destination) { try { // Define output format OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(INDENT_SIZE); format.setEncoding(this.fileEncoding); return new XMLWriter(new FileOutputStream(destination), format); } catch (Exception exception) { throw new AlfrescoRuntimeException("Unable to create XML writer.", exception); } }
/** * Start the transfer report */ public void startTransferReport(String encoding, Writer writer) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(3); format.setEncoding(encoding); try { this.writer = new XMLWriter(writer, format); this.writer.startDocument(); this.writer.startPrefixMapping(PREFIX, TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI); // Start Transfer Manifest // uri, name, prefix this.writer.startElement(TransferDestinationReportModel.TRANSFER_REPORT_MODEL_1_0_URI, TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT, PREFIX + ":" + TransferDestinationReportModel.LOCALNAME_TRANSFER_DEST_REPORT, EMPTY_ATTRIBUTES); } catch (SAXException se) { se.printStackTrace(); } }
/** * Start the transfer manifest */ public void startTransferManifest(Writer writer) throws SAXException { format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(3); format.setEncoding("UTF-8"); this.writer = new XMLWriter(writer, format); this.writer.startDocument(); this.writer.startPrefixMapping(PREFIX, TransferModel.TRANSFER_MODEL_1_0_URI); this.writer.startPrefixMapping("cm", NamespaceService.CONTENT_MODEL_1_0_URI); // Start Transfer Manifest // uri, name, prefix this.writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI, ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, PREFIX + ":" + ManifestModel.LOCALNAME_TRANSFER_MAINIFEST, EMPTY_ATTRIBUTES); }
/** * Start the transfer report */ public void startTransferReport(String encoding, Writer writer) throws SAXException { OutputFormat format = OutputFormat.createPrettyPrint(); format.setNewLineAfterDeclaration(false); format.setIndentSize(3); format.setEncoding(encoding); this.writer = new XMLWriter(writer, format); this.writer.startDocument(); this.writer.startPrefixMapping(PREFIX, TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI); // Start Transfer Manifest // uri, name, prefix this.writer.startElement(TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI, TransferReportModel.LOCALNAME_TRANSFER_REPORT, PREFIX + ":" + TransferReportModel.LOCALNAME_TRANSFER_REPORT, EMPTY_ATTRIBUTES); }
/** * Performs XML conversion from ADN to oai_dc format. Characters are encoded as UTF-8. * * @param xml XML input in the 'adn' format. * @param docReader A lucene doc reader for this record. * @param context The servlet context where this is running. * @return XML in the converted 'oai_dc' format. */ public String convertXML(String xml, XMLDocReader docReader, ServletContext context) { getXFormFilesAndIndex(context); try { Transformer transformer = XSLTransformer.getTransformer(transform_file.getAbsolutePath()); String transformed_content = XSLTransformer.transformString(xml, transformer); SAXReader reader = new SAXReader(); Document document = DocumentHelper.parseText(transformed_content); // Dom4j automatically writes using UTF-8, unless otherwise specified. OutputFormat format = OutputFormat.createPrettyPrint(); StringWriter outputWriter = new StringWriter(); XMLWriter writer = new XMLWriter(outputWriter, format); writer.write(document); outputWriter.close(); writer.close(); return outputWriter.toString(); } catch (Throwable e) { System.err.println("NCS_ITEMToNSDL_DCFormatConverter was unable to produce transformed file: " + e); e.printStackTrace(); return ""; } }
/** * Formats an {@link org.dom4j.Node} as a printable string * * @param node the Node to display * @return a nicley-formatted String representation of the Node. */ public static String prettyPrint(Node node) { StringWriter sw = new StringWriter(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setXHTML(true); //Default is false, this produces XHTML HTMLWriter ppWriter = new HTMLWriter(sw, format); try { ppWriter.write(node); ppWriter.flush(); } catch (Exception e) { return ("Pretty Print Failed"); } return sw.toString(); }
public void fileSource(HttpServletRequest req, HttpServletResponse resp) throws Exception { String path=req.getParameter("path"); path=Utils.decodeURL(path); InputStream inputStream=repositoryService.readFile(path,null); String content=IOUtils.toString(inputStream,"utf-8"); inputStream.close(); String xml=null; try{ Document doc=DocumentHelper.parseText(content); OutputFormat format=OutputFormat.createPrettyPrint(); StringWriter out=new StringWriter(); XMLWriter writer=new XMLWriter(out, format); writer.write(doc); xml=out.toString(); }catch(Exception ex){ xml=content; } Map<String,Object> result=new HashMap<String,Object>(); result.put("content", xml); writeObjectToJson(resp, result); }
/** * 删除配置 * * @param name * @throws Exception */ public static void removeHttpConfig(String name) throws Exception { SAXReader reader = new SAXReader(); File xml = new File(HTTP_CONFIG_FILE); Document doc; Element root; try (FileInputStream in = new FileInputStream(xml); Reader read = new InputStreamReader(in, "UTF-8")) { doc = reader.read(read); root = doc.getRootElement(); Element cfg = (Element) root.selectSingleNode("/root/configs"); Element e = (Element) root.selectSingleNode("/root/configs/config[@name='" + name + "']"); if (e != null) { cfg.remove(e); CONFIG_MAP.remove(name); } OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(xml), format); writer.write(doc); writer.close(); } }
@Override public <R> void setResponse(R response) throws IOException { iResponse.setContentType("application/xml"); iResponse.setCharacterEncoding("UTF-8"); iResponse.setHeader("Pragma", "no-cache" ); iResponse.addHeader("Cache-Control", "must-revalidate" ); iResponse.addHeader("Cache-Control", "no-cache" ); iResponse.addHeader("Cache-Control", "no-store" ); iResponse.setDateHeader("Date", new Date().getTime()); iResponse.setDateHeader("Expires", 0); iResponse.setHeader("Content-Disposition", "attachment; filename=\"response.xml\"" ); Writer writer = iResponse.getWriter(); try { new XMLWriter(writer, OutputFormat.createPrettyPrint()).write(response); } finally { writer.flush(); writer.close(); } }
@Override public byte[] exportXml() throws IOException { Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { boolean anonymize = ApplicationProperty.SolverXMLExportNames.isFalse(); boolean idconv = ApplicationProperty.SolverXMLExportConvertIds.isTrue(); ByteArrayOutputStream ret = new ByteArrayOutputStream(); Document document = createCurrentSolutionBackup(anonymize, idconv); if (ApplicationProperty.SolverXMLExportConfiguration.isTrue()) saveProperties(document); (new XMLWriter(ret, OutputFormat.createPrettyPrint())).write(document); ret.flush(); ret.close(); return ret.toByteArray(); } finally { lock.unlock(); } }
protected void sendRequest(Document request) throws IOException { try { StringWriter writer = new StringWriter(); (new XMLWriter(writer,OutputFormat.createPrettyPrint())).write(request); writer.flush(); writer.close(); SessionImplementor session = (SessionImplementor)new _RootDAO().getSession(); Connection connection = session.getJdbcConnectionAccess().obtainConnection(); try { CallableStatement call = connection.prepareCall(iRequestSql); call.setString(1, writer.getBuffer().toString()); call.execute(); call.close(); } finally { session.getJdbcConnectionAccess().releaseConnection(connection); } } catch (Exception e) { sLog.error("Unable to send request: "+e.getMessage(),e); } finally { _RootDAO.closeCurrentThreadSessions(); } }
public String toXML(boolean pretty) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { OutputFormat format = new OutputFormat(); format.setEncoding(Charsets.UTF_8.name()); if (pretty) { format.setIndent(true); format.setNewlines(true); } else { format.setIndent(false); format.setNewlines(false); } new XMLWriter(baos, format).write(getWrapped()); return baos.toString(Charsets.UTF_8.name()); } catch (Exception e) { throw Throwables.propagate(e); } }
/** * 打印XML * * @param document */ protected void printXML(Document document) { if (log.isInfoEnabled()) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setExpandEmptyElements(true); format.setSuppressDeclaration(true); StringWriter stringWriter = new StringWriter(); XMLWriter writer = new XMLWriter(stringWriter, format); try { writer.write(document); log.info(stringWriter.toString()); } catch (IOException e) { e.printStackTrace(); } } }
/** * xml 2 string * * @param document xml document * @return */ public static String parseXMLToString(Document document) { Assert.notNull(document); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); StringWriter writer = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(writer, format); try { xmlWriter.write(document); xmlWriter.close(); } catch (IOException e) { throw new RuntimeException("XML解析发生错误"); } return writer.toString(); }
/** * Devuelve la representaci�n de un Document XML en String bien formateado * y con codificaci�n UTF-8. * @param doc Documento. * @return string representando el documento formateado y en UTF-8. */ private String documentToString(Document doc) { String result = null; StringWriter writer = new StringWriter(); OutputFormat of = OutputFormat.createPrettyPrint(); of.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(writer, of); try { xmlWriter.write(doc); xmlWriter.close(); result = writer.toString(); } catch (IOException e) { log.error("Error escribiendo xml", e); } return result; }
/** * doc2XmlFile * 将Document对象保存为一个xml文件到本地 * @return true:保存成功 flase:失败 * @param filename 保存的文件名 * @param document 需要保存的document对象 */ public static boolean doc2XmlFile(Document document,String filename) { boolean flag = true; try{ /* 将document中的内容写入文件中 */ //默认为UTF-8格式,指定为"GB2312" OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("GB2312"); XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format); writer.write(document); writer.close(); }catch(Exception ex){ flag = false; ex.printStackTrace(); } return flag; }
/** * 格式化XML * * @param inputXML * @return * @throws Exception */ public static String formatXML(String inputXML) throws Exception { Document doc = DocumentHelper.parseText(inputXML); StringWriter out = null; if (doc != null) { try { OutputFormat format = OutputFormat.createPrettyPrint(); out = new StringWriter(); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } return out.toString(); } return inputXML; }
@Test public void testExpandEmptyElements() throws IOException { Document document = DocumentHelper.createDocument(); Element root = document.addElement("root"); Element id = root.addElement("id"); id.addText("1"); root.addElement("empty"); OutputFormat xmlFormat = new OutputFormat(); // OutputFormat.createPrettyPrint(); xmlFormat.setSuppressDeclaration(true); xmlFormat.setEncoding("UTF-8"); // If this is true, elements without any child nodes // are output as <name></name> instead of <name/>. xmlFormat.setExpandEmptyElements(true); StringWriter out = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(out, xmlFormat); xmlWriter.write(document); xmlWriter.close(); assertEquals("<root><id>1</id><empty></empty></root>", out.toString()); }
public void testEscapeXML() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputFormat format = new OutputFormat(null, false, "ISO-8859-2"); format.setSuppressDeclaration(true); XMLWriter writer = new XMLWriter(os, format); Document document = DocumentFactory.getInstance().createDocument(); Element root = document.addElement("root"); root.setText("bla &#c bla"); writer.write(document); String result = os.toString(); Document doc2 = DocumentHelper.parseText(result); doc2.normalize(); }
public File write() throws Exception { Document doc = createDoc(); // 读取文件 FileOutputStream fos = new FileOutputStream(this.file); // 设置文件编码 OutputFormat format = OutputFormat.createPrettyPrint(); // 创建写文件方法 org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(fos, format); // 写入文件 xmlWriter.write(doc); // 关闭 fos.close(); xmlWriter.close(); return this.file; }
public void perform(TaskRequest req, TaskResponse res) { File f = new File((String) file.evaluate(req, res)); if (f.getParentFile() != null) { // Make sure the necessary directories are in place... f.getParentFile().mkdirs(); } try { XMLWriter writer = new XMLWriter(new FileOutputStream(f), OutputFormat.createPrettyPrint()); writer.write((Node) node.evaluate(req, res)); } catch (Throwable t) { String msg = "Unable to write the specified file: " + f.getPath(); throw new RuntimeException(msg, t); } }
/**方法(公共)<br> * 名称: save<br> * 描述: 储存文档对象为本地文件(指定文档)<br> * @param doc - 指定文档 * @param savePath - 储存路径 * @return boolean - 是否成功 */public boolean save(Document doc,String savePath) { boolean isSuccess=false; try { FileOutputStream output=new FileOutputStream(savePath); OutputFormat format=new OutputFormat("",true,"UTF-8"); XMLWriter writer=new XMLWriter(output,format); writer.write(doc); writer.close(); isSuccess=true; } catch(IOException ex) { isSuccess=false; } return isSuccess; }
public static void main(String[] args) { try { ToolBox.configureLogging(); StudentSectioningModel model = new StudentSectioningModel(new DataProperties()); Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>(); StudentSectioningXMLLoader xmlLoad = new StudentSectioningXMLLoader(model, assignment); xmlLoad.setInputFile(new File(args[0])); xmlLoad.load(); Document document = exportModel(assignment, model); FileOutputStream fos = new FileOutputStream(new File(args[1])); (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
public static boolean writeToXML(Document document, String tempPath) { try { // 使用XMLWriter写入,可以控制格式,经过调试,发现这种方式会出现乱码,主要是因为Eclipse中xml文件和JFrame中文件编码不一致造成的 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(EncodingUtil.CHARSET_UTF8); // format.setSuppressDeclaration(true);//这句话会压制xml文件的声明,如果为true,就不打印出声明语句 format.setIndent(true);// 设置缩进 format.setIndent(" ");// 空行方式缩进 format.setNewlines(true);// 设置换行 XMLWriter writer = new XMLWriter(new FileWriterWithEncoding(new File(tempPath), EncodingUtil.CHARSET_UTF8), format); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); MyLogger.logger.error("写入xml文件出错!"); return false; } return true; }
/** * Returns the given xml document as nicely formated string. * * @param node * The xml document. * @return the formated xml as string. */ private static String formatXml(Node node) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setIndentSize(4); format.setTrimText(true); format.setExpandEmptyElements(true); StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter, format); try { xmlWriter.write(node); xmlWriter.flush(); } catch (IOException e) { // this should never happen throw new RuntimeException(e); } return stringWriter.getBuffer().toString(); }
protected void write(String resource, Document document) throws IOException, DocumentException { File file = null; if (iSource == null) { file = new File(getClass().getClassLoader().getResource(resource).getFile()); } else { file = new File(iSource + File.separator + resource); } info(" -- writing " + file + " ..."); FileOutputStream fos = new FileOutputStream(file); try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setIndentSize(4); format.setPadText(false); new MyXMLWriter(fos, format).write(document); } finally { fos.flush(); fos.close(); } }
public void saveXml(String fileName, Session session, Properties parameters) throws Exception { debug("Saving "+fileName); Document doc = saveXml(session, parameters); FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); (new XMLWriter(fos,OutputFormat.createPrettyPrint())).write(doc); fos.flush();fos.close();fos=null; } finally { try { if (fos!=null) fos.close(); } catch (IOException e) { fatal("Unable to write file "+fileName+", reason:"+e.getMessage(),e); throw e; } } }
/** * Persist results for this user/aiid as an XML document. dlPointer is aiid in this case. * * @param doc * @param type * @param info */ public static void createResultsReporting(final Document doc, final Identity subj, final String type, final long aiid) { final File fUserdataRoot = new File(WebappHelper.getUserDataRoot()); final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type; final File fReportingDir = new File(fUserdataRoot, path); try { fReportingDir.mkdirs(); final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml")); final Element element = doc.getRootElement(); final XMLWriter xw = new XMLWriter(os, new OutputFormat(" ", true)); xw.write(element); // closing steams xw.close(); os.close(); } catch (final Exception e) { throw new OLATRuntimeException(FilePersister.class, "Error persisting results reporting for subject: '" + subj.getName() + "'; assessment id: '" + aiid + "'", e); } }
/** * writes the manifest.xml */ void writeToFile() { final String filename = "imsmanifest.xml"; final OutputFormat format = OutputFormat.createPrettyPrint(); try { VFSLeaf outFile; // file may exist outFile = (VFSLeaf) cpcore.getRootDir().resolve("/" + filename); if (outFile == null) { // if not, create it outFile = cpcore.getRootDir().createChildLeaf("/" + filename); } final DefaultDocument manifestDocument = cpcore.buildDocument(); final XMLWriter writer = new XMLWriter(outFile.getOutputStream(false), format); writer.write(manifestDocument); } catch (final Exception e) { log.error("imsmanifest for ores " + ores.getResourceableId() + "couldn't be written to file.", e); throw new OLATRuntimeException(CPOrganizations.class, "Error writing imsmanifest-file", new IOException()); } }
private static QTIDocument exportAndImportToQTIFormat(QTIDocument qtiDocOrig) throws IOException { Document qtiXmlDoc = qtiDocOrig.getDocument(); OutputFormat outformat = OutputFormat.createPrettyPrint(); String fileName = qtiDocOrig.getAssessment().getTitle() + "QTIFormat.xml"; OutputStreamWriter qtiXmlOutput = new OutputStreamWriter(new FileOutputStream(new File(TEMP_DIR, fileName)), Charset.forName("UTF-8")); XMLWriter writer = new XMLWriter(qtiXmlOutput, outformat); writer.write(qtiXmlDoc); writer.flush(); writer.close(); XMLParser xmlParser = new XMLParser(new IMSEntityResolver()); Document doc = xmlParser.parse(new FileInputStream(new File(TEMP_DIR, fileName)), true); ParserManager parser = new ParserManager(); QTIDocument qtiDocRestored = (QTIDocument) parser.parse(doc); return qtiDocRestored; }
/** * convert definition to hibernate xml * * @param descriptor * @return * @throws IOException */ protected String convertToXML(IStandalonePersistentBeanDescriptor descriptor) { Document doc = createDocument(descriptor); StringWriter sw = new StringWriter(); XMLWriter writer = new XMLWriter(sw, OutputFormat.createCompactFormat()); try { writer.write(doc); } catch (IOException e) { if (getLogger().isErrorEnabled()) { getLogger().error("Failed to cast xml document to string.", e); } throw new ResourceException("Failed to cast xml document to string.", e); } if (getLogger().isDebugEnabled()) { getLogger() .debug("Class [" + descriptor.getResourceClass().getName() + "] has been configured into hibernate. XML as [" + sw.toString().replace("\n", "") + "]."); } return sw.toString(); }
public static void store(OutputStream out, List snips, List users, String filter, List ignoreElements, File fileStore) { try { OutputFormat outputFormat = new OutputFormat(); outputFormat.setEncoding("UTF-8"); outputFormat.setNewlines(true); XMLWriter xmlWriter = new XMLWriter(out, outputFormat); Element root = DocumentHelper.createElement("snipspace"); xmlWriter.writeOpen(root); storeUsers(xmlWriter, users); storeSnips(xmlWriter, snips, filter, ignoreElements, fileStore); xmlWriter.writeClose(root); xmlWriter.flush(); } catch (Exception e) { e.printStackTrace(); } }