Java Code Examples for org.dom4j.io.OutputFormat.createPrettyPrint()

The following are Jave code examples for showing how to use createPrettyPrint() of the org.dom4j.io.OutputFormat class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: alfresco-repository   File: ImportFileUpdater.java   Source Code and License Vote up 6 votes
/**
 * 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);
       }
}
 
Example 2
Project: minlia-iot   File: AbstractApiComponent.java   Source Code and License Vote up 6 votes
/**
 * 打印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();
        }
    }
}
 
Example 3
Project: alfresco-repository   File: XMLTransferReportWriter.java   Source Code and License Vote up 6 votes
/**
 * 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);
}
 
Example 4
Project: joai-project   File: NCS_ITEMToNSDL_DCFormatConverter.java   Source Code and License Vote up 6 votes
/**
 *  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 "";
	}
}
 
Example 5
Project: joai-project   File: Dom4jUtils.java   Source Code and License Vote up 6 votes
/**
 *  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();
}
 
Example 6
Project: lodsve-framework   File: XmlUtils.java   Source Code and License Vote up 6 votes
/**
 * 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();
}
 
Example 7
Project: sistra   File: InstanciaTelematicaProcessorEJB.java   Source Code and License Vote up 6 votes
/**
 * 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;
}
 
Example 8
Project: codePay   File: XmlUtil.java   Source Code and License Vote up 6 votes
/**
 * 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;      
}
 
Example 9
Project: dls-repository-stack   File: Dom4jUtils.java   Source Code and License Vote up 6 votes
/**
 *  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();
}
 
Example 10
Project: dls-repository-stack   File: NCS_ITEMToNSDL_DCFormatConverter.java   Source Code and License Vote up 6 votes
/**
 *  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 "";
	}
}
 
Example 11
Project: CEC-Automatic-Annotation   File: WriteToXMLUtil.java   Source Code and License Vote up 6 votes
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;
}
 
Example 12
Project: cernunnos   File: WriteDocumentTask.java   Source Code and License Vote up 6 votes
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);
		}
				
	}
 
Example 13
Project: yalder   File: WikipediaCrawlTool.java   Source Code and License Vote up 6 votes
/**
 * 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();
}
 
Example 14
Project: olat   File: QTIExportImportTest.java   Source Code and License Vote up 6 votes
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;
}
 
Example 15
Project: olat   File: ContentPackage.java   Source Code and License Vote up 6 votes
/**
 * 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());
    }
}
 
Example 16
Project: OLE-INST   File: JAXBContextFactory_UT.java   Source Code and License Vote up 6 votes
public static String prettyPrint(final String xml) {
    if (StringUtils.isBlank(xml)) {
        throw new RuntimeException("xml was null or blank in prettyPrint()");
    }

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    } catch (Exception e) {
        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
    }
    String[] xmlArray = StringUtils.split(sw.toString(), '\n');
    Object[] xmlContent = ArrayUtils.subarray(xmlArray, 1, xmlArray.length);
    StringBuilder xmlStr = new StringBuilder();
    for (Object object : xmlContent) {
        xmlStr.append(object.toString());
        xmlStr.append('\n');
    }
    return xmlStr.toString();
}
 
Example 17
Project: community-edition-old   File: XMLTransferManifestWriter.java   Source Code and License Vote up 6 votes
/**
 * 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);
}
 
Example 18
Project: Reer   File: DOM4JSerializer.java   Source Code and License Vote up 5 votes
public static void exportToFile(ExportInteraction exportInteraction, ExtensionFileFilter fileFilter, DOM4JSettingsNode settingsNode) {
    File file = promptForFile(exportInteraction, fileFilter);
    if (file == null) {
        //the user canceled.
        return;
    }

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        LOGGER.error("Could not write to file: " + file.getAbsolutePath(), e);
        exportInteraction.reportError("Could not write to file: " + file.getAbsolutePath());
        return;
    }

    try {
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint());
        Element rootElement = settingsNode.getElement();
        rootElement.detach();

        Document document = DocumentHelper.createDocument(rootElement);

        xmlWriter.write(document);
    } catch (Throwable t) {
        LOGGER.error("Internal error. Failed to save.", t);
        exportInteraction.reportError("Internal error. Failed to save.");
    } finally {
        closeQuietly(fileOutputStream);
    }
}
 
Example 19
Project: TestDemo1-github   File: Dom4jHelper.java   Source Code and License Vote up 5 votes
/**
 * xml转换为字符串
 * @param doc
 * @param encoding
 * @return
 * @throws Exception
 */
public static String toString(Document doc,String encoding)throws Exception{
	OutputFormat format=OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    ByteArrayOutputStream byteOS=new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS,encoding),format);
	writer.write(doc);
	writer.flush();
	writer.close();		
	writer=null;
	
	return byteOS.toString(encoding);
}
 
Example 20
Project: bulbasaur   File: ValidataXMLTest.java   Source Code and License Vote up 5 votes
/**
 * 通过XSD(XML Schema)校验XML
 */
@Test
public void validateXMLByXSD() {
	String path = this.getClass().getResource("/").getPath();
	int index = path.lastIndexOf("/");
	path = path.substring(0, index);

	String xmlFileName = path + "/processCore.xml";
	// String xsdFileName =
	// "/Users/user/workspace/bulbasaur/core/src/test/resources/process_bak.xsd";
	String xsdFileName = path + "/test.xsd";
	try {
		// 创建默认的XML错误处理器
		XMLErrorHandler errorHandler = new XMLErrorHandler();
		// 获取基于 SAX 的解析器的实例
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 解析器在解析时验证 XML 内容。
		factory.setValidating(true);
		// 指定由此代码生成的解析器将提供对 XML 名称空间的支持。
		factory.setNamespaceAware(true);
		// 使用当前配置的工厂参数创建 SAXParser 的一个新实例。
		SAXParser parser = factory.newSAXParser();
		// 创建一个读取工具
		SAXReader xmlReader = new SAXReader();
		// 获取要校验xml文档实例
		Document xmlDocument = xmlReader.read(new File(xmlFileName));
		// 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在
		// [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。
		parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
		parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);
		// 创建一个SAXValidator校验工具,并设置校验工具的属性
		SAXValidator validator = new SAXValidator(parser.getXMLReader());
		// 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
		validator.setErrorHandler(errorHandler);
		// 校验
		validator.validate(xmlDocument);

		XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
		// 如果错误信息不为空,说明校验失败,打印错误信息
		if (errorHandler.getErrors().hasContent()) {
			System.out.println("XML文件通过XSD文件校验失败!");
			writer.write(errorHandler.getErrors());
		} else {
			System.out.println("Good! XML文件通过XSD文件校验成功!");
		}
	} catch (Exception ex) {
		System.out.println("XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage());
		ex.printStackTrace();
	}
}
 
Example 21
Project: EasyML   File: WFGraph.java   Source Code and License Vote up 5 votes
public static void main(String args[]){

		Namespace rootNs = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
		QName rootQName = QName.get("workflow-app", rootNs); // your root element's name
		Element workflow = DocumentHelper.createElement(rootQName);
		Document doc = DocumentHelper.createDocument(workflow);
		
		workflow.addAttribute("name", "test");
		Element test = workflow.addElement("test");
		test.addText("hello");
				OutputFormat outputFormat = OutputFormat.createPrettyPrint();
				outputFormat.setEncoding("UTF-8");
				outputFormat.setIndent(true); 
				outputFormat.setIndent("    "); 
				outputFormat.setNewlines(true); 
		try {
			StringWriter stringWriter = new StringWriter();
			XMLWriter xmlWriter = new XMLWriter(stringWriter);
			xmlWriter.write(doc);
			xmlWriter.close();
			System.out.println( doc.asXML() );
			System.out.println( stringWriter.toString().trim());

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
 
Example 22
Project: aaden-pay   File: LianlianBranchTest.java   Source Code and License Vote up 5 votes
private void writeXml(List<JSONArray> list) throws Exception {
	File file = new File(SAVE_PATH);
	if (file.exists())
		file.delete();

	// 生成一个文档
	Document document = DocumentHelper.createDocument();
	Element root = document.addElement("root");
	for (JSONArray jsonArray : list) {
		for (Object object : jsonArray) {
			JSONObject json = (JSONObject) object;
			System.out.println(json);
			Element element = root.addElement("branch");
			// 为cdr设置属性名和属性值
			element.addAttribute("branchId", json.getString("prcptcd").trim());// 支行行号
			element.addAttribute("bankCode", json.getString("bankCode").trim());// 银行类型
			element.addAttribute("cityCode", json.getString("cityCode").trim());// 城市代码
			element.addAttribute("branchName", json.getString("brabank_name").trim());// 支行名称
		}
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(SAVE_PATH)), "UTF-8"), format);
	// 写入新文件
	writer.write(document);
	writer.flush();
	writer.close();
}
 
Example 23
Project: alfresco-repository   File: XMLWriter.java   Source Code and License Vote up 5 votes
public XMLWriter(OutputStream outputStream, boolean prettyPrint, String encoding)
        throws UnsupportedEncodingException
{
    OutputFormat format = prettyPrint ? OutputFormat.createPrettyPrint() : OutputFormat.createCompactFormat();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding(encoding);
    output = outputStream;
    this.dom4jWriter = new org.dom4j.io.XMLWriter(outputStream, format);
}
 
Example 24
Project: alfresco-repository   File: ExportSourceImporter.java   Source Code and License Vote up 5 votes
private XMLWriter createXMLExporter(Writer writer)
{
    // Define output format
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    // Construct an XML Exporter

    XMLWriter xmlWriter = new XMLWriter(writer, format);
    return xmlWriter;
}
 
Example 25
Project: joai-project   File: ADNToNSDLDCFormatConverter.java   Source Code and License Vote up 5 votes
/**
 *  Performs XML conversion from ADN to nsdl_dc format. Characters are encoded as UTF-8.
 *
 * @param  xml        XML input in the 'adn' format.
 * @param  context    The context in which this is running.
 * @param  docReader  Lucene DocReader for the item.
 * @return            XML in the converted 'nsdl_dc' format.
 */
public String convertXML(String xml, XMLDocReader docReader, ServletContext context) {
	getXFormFilesAndIndex(context);
	try {
		Transformer adn_to_nsdl_transformer = XSLTransformer.getTransformer(adn_to_nsdl_file.getAbsolutePath());
		Transformer namespace_out_transformer = XSLTransformer.getTransformer(namespace_out_file.getAbsolutePath());

		String transformed_content = XSLTransformer.transformString(xml, adn_to_nsdl_transformer);
		transformed_content = XSLTransformer.transformString(transformed_content, namespace_out_transformer);

		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Replace IDs with URL in each field as appropriate
		for (int i = 0; i < fieldsToReplace.length; i++)
			handleRelationField("//nsdl_dc:nsdl_dc/" + fieldsToReplace[i], document);

		// 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("ADNToNSDLDCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 26
Project: parabuild-ci   File: ProjectStats.java   Source Code and License Vote up 5 votes
/**
 * Report statistics as an XML document to given output stream.
 */
public void reportSummary(OutputStream out) {
	Document document = DocumentHelper.createDocument();

	toElement(document);

	try {
		XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
		writer.write(document);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 27
Project: joai-project   File: SchemaViewerForm.java   Source Code and License Vote up 5 votes
/**
 *  Description of the Method
 *
 *@param  node           Description of the Parameter
 *@return                Description of the Return Value
 *@exception  Exception  Description of the Exception
 */
private String prettyPrint(Node node)
	throws Exception {
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();
	//These are the default formats from createPrettyPrint, so you needn't set them:
	//  format.setNewlines(true);
	//  format.setTrimText(true);
	format.setXHTML(true);
	//Default is false, this produces XHTML
	HTMLWriter ppWriter = new HTMLWriter(sw, format);
	ppWriter.write(node);
	ppWriter.flush();
	return sw.toString();
}
 
Example 28
Project: joai-project   File: ADNToOAIDCFormatConverter.java   Source Code and License Vote up 5 votes
/**
 *  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 adn_to_oai_transformer = XSLTransformer.getTransformer(adn_to_oai_file.getAbsolutePath());
		Transformer namespace_out_transformer = XSLTransformer.getTransformer(namespace_out_file.getAbsolutePath());

		String transformed_content = XSLTransformer.transformString(xml, adn_to_oai_transformer);
		transformed_content = XSLTransformer.transformString(transformed_content, namespace_out_transformer);
					
		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Replace IDs in the relation field only
		handleRelationField("//oai_dc:dc/dc:relation",document);
	
		// 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("ADNToOAIDCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 29
Project: pndaox   File: DaoGenHelper.java   Source Code and License Vote up 5 votes
public String mixMethodToData(DaoGen daoGen, String namespace, Map<String, MapperMethod> methodMap, String data) {
    if (data.isEmpty())
        data = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
                "\n" +
                "<!DOCTYPE mapper\n" +
                "PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "\n" +
                "<mapper namespace=\"" + namespace + "\">\n" +
                "</mapper>\n";
    try {
        Document document = parseText(data);
        Element element = document.getRootElement();
        element.elements().forEach(sqlEle -> {
            String id = sqlEle.attribute("id").getText();
            methodMap.remove(id);
        });
        methodMap.forEach(getGenFunc(daoGen, element));

        OutputFormat format = OutputFormat.createPrettyPrint();
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            XMLWriter writer = new XMLWriter(outputStream, format);
            writer.write(document);
            writer.flush();

            return outputStream.toString("UTF-8");
        }
    } catch (DocumentException | IOException | SAXException e) {
        throw new Error(e);
    }
}
 
Example 30
Project: appium-java-repl   File: Utils.java   Source Code and License Vote up 5 votes
/**
 * Pretty-Print XML.
 * 
 * @param xml The XML
 * @return A beautiful XML
 * @throws IOException
 * @throws DocumentException
 */
public static String prettyXML(final String xml) throws IOException, DocumentException {
  Document doc = DocumentHelper.parseText(xml);
  StringWriter sw = new StringWriter();
  OutputFormat format = OutputFormat.createPrettyPrint();
  format.setIndent(true);
  format.setIndentSize(3);
  XMLWriter xw = new XMLWriter(sw, format);
  xw.write(doc);
  return sw.toString();
}
 
Example 31
Project: dls-repository-stack   File: SchemaViewerForm.java   Source Code and License Vote up 5 votes
/**
 *  Description of the Method
 *
 *@param  node           Description of the Parameter
 *@return                Description of the Return Value
 *@exception  Exception  Description of the Exception
 */
private String prettyPrint(Node node)
	throws Exception {
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();
	//These are the default formats from createPrettyPrint, so you needn't set them:
	//  format.setNewlines(true);
	//  format.setTrimText(true);
	format.setXHTML(true);
	//Default is false, this produces XHTML
	HTMLWriter ppWriter = new HTMLWriter(sw, format);
	ppWriter.write(node);
	ppWriter.flush();
	return sw.toString();
}
 
Example 32
Project: dls-repository-stack   File: ADNToOAIDCFormatConverter.java   Source Code and License Vote up 5 votes
/**
 *  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 adn_to_oai_transformer = XSLTransformer.getTransformer(adn_to_oai_file.getAbsolutePath());
		Transformer namespace_out_transformer = XSLTransformer.getTransformer(namespace_out_file.getAbsolutePath());

		String transformed_content = XSLTransformer.transformString(xml, adn_to_oai_transformer);
		transformed_content = XSLTransformer.transformString(transformed_content, namespace_out_transformer);
					
		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Replace IDs in the relation field only
		handleRelationField("//oai_dc:dc/dc:relation",document);
	
		// 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("ADNToOAIDCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 33
Project: cuba   File: XMLConverter2.java   Source Code and License Vote up 5 votes
protected String documentToString(Document document) {
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        StringWriter sw = new StringWriter();
        XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 34
Project: dls-repository-stack   File: AdvancedQueryForm.java   Source Code and License Vote up 5 votes
/**
 *  Description of the Method
 *
 *@param  node           Description of the Parameter
 *@return                Description of the Return Value
 *@exception  Exception  Description of the Exception
 */
private String prettyPrint(Node node)
	throws Exception {
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();
	//These are the default formats from createPrettyPrint, so you needn't set them:
	//  format.setNewlines(true);
	//  format.setTrimText(true);
	format.setXHTML(true);
	//Default is false, this produces XHTML
	HTMLWriter ppWriter = new HTMLWriter(sw, format);
	ppWriter.write(node);
	ppWriter.flush();
	return sw.toString();
}
 
Example 35
Project: SpringBootUnity   File: XmlUtil.java   Source Code and License Vote up 5 votes
/**
 * 保存文档
 *
 * @throws Exception
 */
public static void save(Document doc, String xmlPath, String encoding) throws Exception {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath), encoding), format);
    writer.write(doc);
    writer.flush();
    writer.close();
}
 
Example 36
Project: SpringBootUnity   File: XmlUtil.java   Source Code and License Vote up 5 votes
/**
 * xml转换为字符串
 *
 * @param doc
 * @param encoding
 * @return
 * @throws Exception
 */
public static String toString(Document doc, String encoding) throws Exception {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS, encoding), format);
    writer.write(doc);
    writer.flush();
    writer.close();
    return byteOS.toString(encoding);
}
 
Example 37
Project: dls-repository-stack   File: OAISetsXMLConfigManager.java   Source Code and License Vote up 5 votes
/**
 *  Removes the given OAI set definition from the ListSets config XML file and writes it to disc.
 *
 * @param  setsConfigFile  The ListSets config file
 * @param  setSpec         The set to remove
 * @return                 True if the set existed and was removed
 * @exception  Exception   If error
 */
public static boolean removeOAISetSpecDefinition(File setsConfigFile, String setSpec) throws Exception {
	Document document = null;
	if (setsConfigFile == null || !setsConfigFile.exists())
		return false;

	// Create the XML DOM
	if (setsConfigFile.exists()) {
		document = Dom4jUtils.getXmlDocument(setsConfigFile, "UTF-8");
	}

	Element root = document.getRootElement();
	if (!root.getName().equals("ListSets"))
		throw new Exception("OAI Sets XML is incorrect. Root node is not 'ListSets'");

	// Remove the previous set definition, if present
	String xPath = "set[setSpec=\"" + setSpec + "\"]";
	Element prevSet = (Element) root.selectSingleNode(xPath);
	if (prevSet == null)
		return false;
	root.remove(prevSet);

	// Write the XML to disc
	OutputFormat format = OutputFormat.createPrettyPrint();
	XMLWriter writer = new XMLWriter(new FileWriter(setsConfigFile), format);
	writer.write(document);
	writer.close();

	return true;
}
 
Example 38
Project: dls-repository-stack   File: ADNToNSDLDCFormatConverter.java   Source Code and License Vote up 5 votes
/**
 *  Performs XML conversion from ADN to nsdl_dc format. Characters are encoded as UTF-8.
 *
 * @param  xml        XML input in the 'adn' format.
 * @param  context    The context in which this is running.
 * @param  docReader  Lucene DocReader for the item.
 * @return            XML in the converted 'nsdl_dc' format.
 */
public String convertXML(String xml, XMLDocReader docReader, ServletContext context) {
	getXFormFilesAndIndex(context);
	try {
		Transformer adn_to_nsdl_transformer = XSLTransformer.getTransformer(adn_to_nsdl_file.getAbsolutePath());
		Transformer namespace_out_transformer = XSLTransformer.getTransformer(namespace_out_file.getAbsolutePath());

		String transformed_content = XSLTransformer.transformString(xml, adn_to_nsdl_transformer);
		transformed_content = XSLTransformer.transformString(transformed_content, namespace_out_transformer);

		SAXReader reader = new SAXReader();
		Document document = DocumentHelper.parseText(transformed_content);

		// Replace IDs with URL in each field as appropriate
		for (int i = 0; i < fieldsToReplace.length; i++)
			handleRelationField("//nsdl_dc:nsdl_dc/" + fieldsToReplace[i], document);

		// 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("ADNToNSDLDCFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 39
Project: validatar   File: JUnitFormatter.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 * Writes out the report for the given testSuites in the JUnit XML format.
 */
@Override
public void writeReport(List<TestSuite> testSuites) throws IOException {
    Document document = DocumentHelper.createDocument();

    Element testSuitesRoot = document.addElement(TESTSUITES_TAG);

    // Output for each test suite
    for (TestSuite testSuite : testSuites) {
        Element testSuiteRoot = testSuitesRoot.addElement(TESTSUITE_TAG);
        testSuiteRoot.addAttribute(TESTS_ATTRIBUTE, Integer.toString(testSuite.queries.size() + testSuite.tests.size()));
        testSuiteRoot.addAttribute(NAME_ATTRIBUTE, testSuite.name);

        for (Query query : testSuite.queries) {
            Element queryNode = testSuiteRoot.addElement(TESTCASE_TAG).addAttribute(NAME_ATTRIBUTE, query.name);
            if (query.failed()) {
                String failureMessage = StringUtils.join(query.getMessages(), NEWLINE);
                queryNode.addElement(FAILED_TAG).addCDATA(failureMessage);
            }
        }
        for (Test test : testSuite.tests) {
            Element testNode = testSuiteRoot.addElement(TESTCASE_TAG).addAttribute(NAME_ATTRIBUTE, test.name);
            if (test.failed()) {
                Element target = testNode;
                if (test.isWarnOnly()) {
                    testNode.addElement(SKIPPED_TAG);
                } else {
                    target = testNode.addElement(FAILED_TAG);
                }
                target.addCDATA(NEWLINE + test.description + NEWLINE + StringUtils.join(test.getMessages(), NEWLINE));
            }
        }
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(outputFile), format);
    writer.write(document);
    writer.close();
}
 
Example 40
Project: Intercloud   File: PacketError.java   Source Code and License Vote up 5 votes
public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {
        writer.write(element);
    }
    catch (Exception e) {
        // Ignore.
    }
    return out.toString();
}
 
Example 41
Project: Intercloud   File: StreamError.java   Source Code and License Vote up 5 votes
public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {
        writer.write(element);
    }
    catch (Exception e) { e.printStackTrace(); }
    return out.toString();
}
 
Example 42
Project: Intercloud   File: Packet.java   Source Code and License Vote up 5 votes
public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {
        writer.write(element);
    }
    catch (Exception e) {
        // Ignore.
    }
    return out.toString();
}
 
Example 43
Project: uimaster   File: StringUtil.java   Source Code and License Vote up 5 votes
public static String formatXml(Document document) throws DocumentException, IOException  {  
    OutputFormat format = OutputFormat.createPrettyPrint();  
    StringWriter writer = new StringWriter();  
    XMLWriter xmlWriter = new XMLWriter(writer, format);  
    xmlWriter.write(document);  
    xmlWriter.close();  
    return writer.toString();  
}
 
Example 44
Project: cacheonix-core   File: Dom4jManyToOneTest.java   Source Code and License Vote up 5 votes
public static void print(Element elt) throws Exception {
	OutputFormat outformat = OutputFormat.createPrettyPrint();
	// outformat.setEncoding(aEncodingScheme);
	XMLWriter writer = new XMLWriter( System.out, outformat );
	writer.write( elt );
	writer.flush();
	// System.out.println( elt.asXML() );
}
 
Example 45
Project: cacheonix-core   File: MultiRepresentationTest.java   Source Code and License Vote up 5 votes
private void prettyPrint(Element element) {
	//System.out.println( element.asXML() );
	try {
		OutputFormat format = OutputFormat.createPrettyPrint();
		new XMLWriter( System.out, format ).write( element );
		System.out.println();
	}
	catch ( Throwable t ) {
		System.err.println( "Unable to pretty print element : " + t );
	}
}
 
Example 46
Project: jeveassets   File: Update.java   Source Code and License Vote up 5 votes
void setVersion(final File xml, final int newVersion) throws DocumentException {
	SAXReader xmlReader = new SAXReader();
	Document doc = xmlReader.read(xml);

	XPath xpathSelector = DocumentHelper.createXPath("/settings");
	List<?> results = xpathSelector.selectNodes(doc);
	for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
		Element element = (Element) iter.next();
		Attribute attr = element.attribute("version");
		if (attr == null) {
			element.add(new DefaultAttribute("version", String.valueOf(newVersion)));
		} else {
			attr.setText(String.valueOf(newVersion));
		}
	}

	try {
		FileOutputStream fos = new FileOutputStream(xml);
		OutputFormat outformat = OutputFormat.createPrettyPrint();
		outformat.setEncoding("UTF-16");
		XMLWriter writer = new XMLWriter(fos, outformat);
		writer.write(doc);
		writer.flush();
	} catch (IOException ioe) {
		LOG.error("Failed to update the serttings.xml version number", ioe);
		throw new RuntimeException(ioe);
	}
}
 
Example 47
Project: tempss   File: SchemaProcessorUtils.java   Source Code and License Vote up 5 votes
/**
 * Utility method to format XML string.
 *
 * @param xml String containing XML to format.
 * @return String containing formatted XML
 * @throws DocumentException
 * @throws IOException
 */
public static String prettyPrintXml(String xml) throws DocumentException, IOException {
    Document doc = DocumentHelper.parseText(xml);
    StringWriter sw = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter xw = new XMLWriter(sw, format);
    xw.write(doc);
    String result = sw.toString();
    return result;
}
 
Example 48
Project: spring-test-dbunit-template   File: GivenWhenThenFlatXmlDataSetLoader.java   Source Code and License Vote up 5 votes
private void writeXml(String path, org.dom4j.Document newDoc) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(
            new FileWriter(path), format
    );
    writer.write(newDoc);
    writer.close();
}
 
Example 49
Project: openmeetings   File: XmlExport.java   Source Code and License Vote up 5 votes
public static void toXml(Writer out, Document doc) throws Exception {
	OutputFormat outformat = OutputFormat.createPrettyPrint();
	outformat.setIndentSize(1);
	outformat.setIndent("\t");
	outformat.setEncoding(UTF_8.name());
	XMLWriter writer = new XMLWriter(out, outformat);
	writer.write(doc);
	writer.flush();
	out.flush();
	out.close();
}
 
Example 50
Project: jmsRestful   File: StringUtil.java   Source Code and License Vote up 5 votes
/**
 * html 必须是格式良好的
 * @param str
 * @return
 * @throws Exception
 */
public static String formatHtml(String str) throws Exception {
	Document document = null;
	document = DocumentHelper.parseText(str);

	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("utf-8");
	StringWriter writer = new StringWriter();

	HTMLWriter htmlWriter = new HTMLWriter(writer, format);

	htmlWriter.write(document);
	htmlWriter.close();
	return writer.toString();
}
 
Example 51
Project: ServletStudyDemo   File: XmlUtils.java   Source Code and License Vote up 5 votes
public static void writeToXml(Document document) throws IOException{
	 // Pretty print the document to System.out
       OutputFormat format = OutputFormat.createPrettyPrint();
       format.setEncoding("UTF-8");
       XMLWriter writer = new XMLWriter( new FileOutputStream(filepath), format );
       writer.write( document );
       writer.close();
}
 
Example 52
Project: cleverbus   File: MessageController.java   Source Code and License Vote up 5 votes
/**
 * Converts input XML to "nice" XML.
 *
 * @param original the original XML
 * @return pretty XML
 */
static String prettyPrintXML(String original) {
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        Document document = DocumentHelper.parseText(original);
        StringWriter sw = new StringWriter();
        XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
        return sw.toString();
    } catch (Exception exc) {
        Log.debug("Error pretty-printing XML: ", exc);
        return original;
    }
}
 
Example 53
Project: g3server   File: ImportExportPlugin.java   Source Code and License Vote up 5 votes
/**
 * Converts the user data that is to be exported to a byte[]. If a read-only
 * user store is being used a user's password will be the same as their username.
 *
 * @return a byte[] of the user data.
 * @throws IOException if there's a problem writing to the XMLWriter.
 */
public byte[] exportUsersToByteArray() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    writer.write(exportUsers());
    
    return out.toByteArray();
}
 
Example 54
Project: FoxBPM   File: TestCase.java   Source Code and License Vote up 5 votes
public void testB() {
	BpmnXMLConverter converter = new BpmnXMLConverter();
	Document doc = converter.convertToXML(null);
	try {
		// 定义输出流的目的地
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		// 定义用于输出xml文件的XMLWriter对象
		XMLWriter xmlWriter = new XMLWriter(System.out, format);
		xmlWriter.write(doc);
		xmlWriter.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 55
Project: findbugs-all-the-bugs   File: AddMessages.java   Source Code and License Vote up 5 votes
@SuppressWarnings("DM_EXIT")
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("Usage: " + AddMessages.class.getName() + " <input collection> <output collection>");
        System.exit(1);
    }

    // Load plugins, in order to get message files
    DetectorFactoryCollection.instance();

    String inputFile = args[0];
    String outputFile = args[1];
    Project project = new Project();

    SortedBugCollection inputCollection = new SortedBugCollection(project);
    inputCollection.readXML(inputFile);

    Document document = inputCollection.toDocument();

    AddMessages addMessages = new AddMessages(inputCollection, document);
    addMessages.execute();

    XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(outputFile)),
            OutputFormat.createPrettyPrint());
    writer.write(document);
    writer.close();
}
 
Example 56
Project: community-edition-old   File: XMLTransferRequsiteWriter.java   Source Code and License Vote up 5 votes
public XMLTransferRequsiteWriter(Writer out)
{
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    this.writer = new XMLWriter(out, format);
}
 
Example 57
Project: FindBug-for-Domino-Designer   File: AddMessages.java   Source Code and License Vote up 5 votes
@SuppressFBWarnings("DM_EXIT")
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("Usage: " + AddMessages.class.getName() + " <input collection> <output collection>");
        System.exit(1);
    }

    // Load plugins, in order to get message files
    DetectorFactoryCollection.instance();

    String inputFile = args[0];
    String outputFile = args[1];
    Project project = new Project();

    SortedBugCollection inputCollection = new SortedBugCollection(project);
    inputCollection.readXML(inputFile);

    Document document = inputCollection.toDocument();

    AddMessages addMessages = new AddMessages(inputCollection, document);
    addMessages.execute();

    XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(outputFile)),
            OutputFormat.createPrettyPrint());
    writer.write(document);
    writer.close();
}
 
Example 58
Project: tinder   File: Packet.java   Source Code and License Vote up 5 votes
public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {
        writer.write(element);
    }
    catch (Exception e) {
        // Ignore.
    }
    return out.toString();
}
 
Example 59
Project: xresloader   File: DataDstXml.java   Source Code and License Vote up 5 votes
/**
 * 转储常量数据
 * @return 常量数据,不支持的时候返回空
 */
public final byte[] dumpConst(HashMap<String, Object> data) {
    // pretty print
    OutputFormat of = null;
    if (ProgramOptions.getInstance().prettyIndent <= 0) {
        of= OutputFormat.createCompactFormat();
    } else {
        of = OutputFormat.createPrettyPrint();
        of.setIndentSize(ProgramOptions.getInstance().prettyIndent);
    }

    // build xml tree
    Document doc = DocumentHelper.createDocument();
    String encoding = SchemeConf.getInstance().getKey().getEncoding();
    if (null != encoding && false == encoding.isEmpty()) {
        doc.setXMLEncoding(encoding);
        of.setEncoding(encoding);
    }

    doc.setRootElement(DocumentHelper.createElement(ProgramOptions.getInstance().xmlRootName));
    doc.getRootElement().addComment("this file is generated by xresloader, please don't edit it.");

    writeData(doc.getRootElement(), data, "");

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(bos, of);
        writer.write(doc);

        return bos.toByteArray();
    } catch(Exception e) {
        ProgramOptions.getLoger().error("write xml failed, %s", e.getMessage());
        return null;
    }
}
 
Example 60
Project: Openfire   File: Xep227ExporterTest.java   Source Code and License Vote up 5 votes
/**
 * Test method for {@link org.jivesoftware.openfire.plugin.OpenfireExporter#exportUsers(org.jivesoftware.openfire.user.UserManager)}.
 * @throws UserAlreadyExistsException 
 * @throws IOException 
 */
@Test
public void testExportUsers() throws UserAlreadyExistsException, IOException {
  
  InExporter testobject = new Xep227Exporter("serverName", offlineMessagesStore, vCardManager, privateStorage, userManager, null);
  
  for (int i = 0; i < 10; i++) {
    userManager.createUser("username" + i,"pw" , "name" + i, "email" + i);
  }
  
  Document result = testobject.exportUsers();
  
  assertNotNull(result);
  
  assertEquals(1, result.nodeCount());
  assertNotNull(result.node(0));
  Element elem = ((Element)result.node(0));
  assertEquals(1, elem.nodeCount());
  assertNotNull(elem.node(0));
  elem = ((Element)elem.node(0));
  assertEquals(10, elem.nodeCount());
  assertNotNull(elem.node(0));
  elem = ((Element)elem.node(0));
  assertEquals(3, elem.nodeCount());
  assertEquals(2, elem.attributeCount());
  
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  
  XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
  writer.write(result);
  
  logger.fine(out.toString() );
  
  assertTrue("Invalid input", testobject.validate(new ByteArrayInputStream(out.toByteArray())));

}
 
Example 61
Project: Openfire-connectionmanager   File: StreamError.java   Source Code and License Vote up 5 votes
@Override
public String toString() {
       StringWriter out = new StringWriter();
       XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
       try {
           writer.write(element);
       }
       catch (Exception e) { }
       return out.toString();
   }
 
Example 62
Project: PackagePlugin   File: FileUtil.java   Source Code and License Vote up 4 votes
/**
 * 保存http请求信息到xml
 *
 * @param hc
 * @return
 * @throws Exception
 */
public static boolean saveHttpConfig(HttpConfig hc) throws Exception {
    SAXReader reader = new SAXReader();
    File xml = new File(HTTP_CONFIG_FILE);
    Document doc = null;
    Element root = null;
    boolean isNew = true;
    if (!xml.exists()) {
        doc = DocumentHelper.createDocument();
        root = DocumentHelper.createElement("root");
        root.addElement("configs");
        doc.add(root);
    }
    if (doc == null) {
        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='" + hc.getName() + "']");
    if (e != null) {
        isNew = false;
        cfg.remove(e);
    }
    CONFIG_MAP.put(hc.getName(), hc);

    Element cfg1 = cfg.addElement("config");
    cfg1.addAttribute("name", hc.getName());
    cfg1.addAttribute("encodeType", hc.getEncodeType());
    cfg1.addAttribute("charset", hc.getCharset());
    cfg1.addAttribute("requestType", hc.getRequestType());
    cfg1.addAttribute("sendXML", hc.getSendXML().toString());
    cfg1.addAttribute("packHead", hc.getPackHead().toString());
    cfg1.addAttribute("lowercaseEncode", hc.getLowercaseEncode().toString());

    cfg1.addElement("url").setText(hc.getUrl());
    cfg1.addElement("header").setText(hc.getHeaderStr());
    cfg1.addElement("parameter").setText(hc.getParameterStr());
    cfg1.addElement("encodeField").setText(hc.getEncodeFieldName());
    cfg1.addElement("encodeKey").setText(hc.getEncodeKey());

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    XMLWriter writer = new XMLWriter(new FileOutputStream(xml), format);
    writer.write(doc);
    writer.close();
    return isNew;
}
 
Example 63
Project: parabuild-ci   File: XDocsBugReporter.java   Source Code and License Vote up 4 votes
private void writeXML(OutputStream out, Project project) throws IOException {
	Document document = endDocument(project);

	XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
	writer.write(document);
}
 
Example 64
Project: joai-project   File: NSDL_DCToNCS_ITEMFormatConverter.java   Source Code and License Vote up 4 votes
/**
 *  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);

	System.out.println("xml: " + xml);

	String xsl2Transformer = "net.sf.saxon.TransformerFactoryImpl";

	try {
		Transformer version_transformer = XSLTransformer.getTransformer(version_transform_file.getAbsolutePath());
		Transformer format_transformer =
			XSLTransformer.getTransformer(format_transform_file.getAbsolutePath(), xsl2Transformer);

		/* 
			when working with nsdl-dc-v1.03 source we had to first transform to nsdl-dc-v1.02 before
			applying format transform to ncs-item.
		*/
		// String transformed_content = XSLTransformer.transformString(xml, version_transformer);
		// transformed_content = XSLTransformer.transformString(transformed_content, format_transformer);

		/*
			when working with nsdl-dc-v1.02-020 source - no nsdl-dc version transform is required
		*/
		String transformed_content = XSLTransformer.transformString(xml, format_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("NSDL_DCToNCS_ITEMFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 65
Project: libraries   File: DocumentUtilities.java   Source Code and License Vote up 4 votes
private static OutputFormat createOutputFormat(final String encoding) {
  final OutputFormat format = OutputFormat.createPrettyPrint();
  format.setEncoding(encoding);
  return format;
}
 
Example 66
Project: dls-repository-stack   File: NSDL_DCToNCS_ITEMFormatConverter.java   Source Code and License Vote up 4 votes
/**
 *  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);

	System.out.println("xml: " + xml);

	String xsl2Transformer = "net.sf.saxon.TransformerFactoryImpl";

	try {
		Transformer version_transformer = XSLTransformer.getTransformer(version_transform_file.getAbsolutePath());
		Transformer format_transformer =
			XSLTransformer.getTransformer(format_transform_file.getAbsolutePath(), xsl2Transformer);

		/* 
			when working with nsdl-dc-v1.03 source we had to first transform to nsdl-dc-v1.02 before
			applying format transform to ncs-item.
		*/
		// String transformed_content = XSLTransformer.transformString(xml, version_transformer);
		// transformed_content = XSLTransformer.transformString(transformed_content, format_transformer);

		/*
			when working with nsdl-dc-v1.02-020 source - no nsdl-dc version transform is required
		*/
		String transformed_content = XSLTransformer.transformString(xml, format_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("NSDL_DCToNCS_ITEMFormatConverter was unable to produce transformed file: " + e);
		e.printStackTrace();
		return "";
	}
}
 
Example 67
Project: eurocarbdb   File: HibernateXmlEntityManagerTest.java   Source Code and License Vote up 4 votes
public void test1() throws Exception
    {
        //EntityManager em = new HibernateXMLEntityManager();
        
        // Taxonomy t        = em.lookup( Taxonomy.class, 100 );
        // TissueTaxonomy tt = em.lookup( TissueTaxonomy.class, 100 );
        // Disease d         = em.lookup( Disease.class, 100 );
       
        HibernateXMLEntityManager em = new HibernateXMLEntityManager();
        Session xml_session = em.getHibernateSession();
        Transaction tx = null;
        
        try 
        {
            tx = xml_session.beginTransaction();
            xml_session = em.getXmlSession();
            
            //Element tax1 = (Element) xml_session.get( Taxonomy.class, 304356 );
/*
            List results = xml_session
                           .createQuery("from Disease d where d.diseaseId = :id")
                           .setParameter("id", 8413 )
                           .list();
            Element tax1 = (Element) results.get(0);
                           
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter out = new XMLWriter( System.out, format );
            
            out.write( tax1 );                               
*/            
/*
            List<Element> dlist = (List<Element>) xml_session
                                   .createQuery( "from Disease d join fetch d.relations r "
                                               + "where r.rightIndex - r.leftIndex = 1 " )
                                   .list();
                           
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter out = new XMLWriter( System.out, format );
            
            out.write( dlist );                              
*/            
            
            List<Element> gslist = (List<Element>) xml_session
                                   .createQuery( "from GlycanSequence gs "
                                               + "join fetch gs.glycanContexts gc "
                                               + "join fetch gc.biologicalContext bc "
                                               //+ "join fetch gs.glycanEvidence ge "
                                               //+ "join fetch ge.evidence ev "
                                               )
                                   .list();
                           
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter out = new XMLWriter( System.out, format );
            
            out.write( gslist );                              

            
            tx.commit();
        }
        catch ( Exception e ) 
        {
            if ( tx != null ) 
                tx.rollback();
                
            e.printStackTrace();
            throw e;
        }
        finally 
        {
            if ( xml_session != null && xml_session.isOpen() )
                xml_session.close();
        }    
    }
 
Example 68
Project: AXmlSwing   File: Dom4jUtil.java   Source Code and License Vote up 4 votes
public static void writeDOM2XML(File file, Document doc) throws Exception{
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), format);
    writer.write(doc);
    writer.close();
}
 
Example 69
Project: AndroidSDKLiteServer   File: RepoSitesEditorV2.java   Source Code and License Vote up 4 votes
@Override
public void write(OutputStream out) throws IOException {
	XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
	writer.write(mDocument);
}
 
Example 70
Project: xresloader   File: DataDstXml.java   Source Code and License Vote up 4 votes
@Override
public final byte[] build(DataDstImpl compiler) throws ConvException {
    // pretty print
    OutputFormat of = null;
    if (ProgramOptions.getInstance().prettyIndent <= 0) {
        of = OutputFormat.createCompactFormat();
    } else {
        of = OutputFormat.createPrettyPrint();
        of.setIndentSize(ProgramOptions.getInstance().prettyIndent);
    }

    // build data
    DataDstObject data_obj = build_data(compiler);

    // build xml tree
    Document doc = DocumentHelper.createDocument();
    String encoding = SchemeConf.getInstance().getKey().getEncoding();
    if (null != encoding && false == encoding.isEmpty()) {
        doc.setXMLEncoding(encoding);
        of.setEncoding(encoding);
    }

    doc.setRootElement(DocumentHelper.createElement(ProgramOptions.getInstance().xmlRootName));
    doc.getRootElement().addComment("this file is generated by xresloader, please don't edit it.");

    Element header = DocumentHelper.createElement("header");
    Element body = DocumentHelper.createElement("body");

    writeData(header, data_obj.header, header.getName());

    // body
    for(Map.Entry<String, List<Object> > item: data_obj.body.entrySet()) {
        for(Object obj: item.getValue()) {
            Element xml_item = DocumentHelper.createElement(item.getKey());

            writeData(xml_item, obj, item.getKey());

            body.add(xml_item);
        }
    }

    writeData(body, data_obj.body, body.getName());

    doc.getRootElement().add(header);
    doc.getRootElement().add(body);

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(bos, of);
        writer.write(doc);

        return bos.toByteArray();
    } catch(Exception e) {
        ProgramOptions.getLoger().error("write xml failed, %s", e.getMessage());
        return null;
    }
}
 
Example 71
Project: community-edition-old   File: WebDAVMethod.java   Source Code and License Vote up 4 votes
/**
 * Returns the format required for an XML response. This may vary per method.
 */
protected OutputFormat getXMLOutputFormat()
{
    // Check if debug output or XML pretty printing is enabled
    return (XMLPrettyPrint || logger.isDebugEnabled()) ? OutputFormat.createPrettyPrint() : OutputFormat.createCompactFormat();
}
 
Example 72
Project: openfire   File: UpdateManager.java   Source Code and License Vote up 4 votes
/**
 * Saves to conf/server-update.xml information about the latest Openfire release that is
 * available for download.
 */
private void saveLatestServerInfo() {
    Element xmlResponse = docFactory.createDocument().addElement("version");
    if (serverUpdate != null) {
        Element component = xmlResponse.addElement("openfire");
        component.addAttribute("latest", serverUpdate.getLatestVersion());
        component.addAttribute("changelog", serverUpdate.getChangelog());
        component.addAttribute("url", serverUpdate.getURL());
    }
    // Write data out to conf/server-update.xml file.
    Writer writer = null;
    try {
        // Create the conf folder if required
        File file = new File(JiveGlobals.getHomeDirectory(), "conf");
        if (!file.exists()) {
            file.mkdir();
        }
        file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf",
                "server-update.xml");
        // Delete the old server-update.xml file if it exists
        if (file.exists()) {
            file.delete();
        }
        // Create new version.xml with returned data
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
        xmlWriter.write(xmlResponse);
    }
    catch (Exception e) {
        Log.error(e.getMessage(), e);
    }
    finally {
        if (writer != null) {
            try {
                writer.close();
            }
            catch (IOException e1) {
                Log.error(e1.getMessage(), e1);
            }
        }
    }
}
 
Example 73
Project: g3server   File: UpdateManager.java   Source Code and License Vote up 4 votes
/**
 * Saves to conf/available-plugins.xml the list of plugins that are available
 * at igniterealtime.org.
 */
private void saveAvailablePluginsInfo() {
    //  XML to store in the file
    Element xml = docFactory.createDocument().addElement("available");
    for (AvailablePlugin plugin : availablePlugins.values()) {
        Element component = xml.addElement("plugin");
        component.addAttribute("name", plugin.getName());
        component.addAttribute("latest", plugin.getLatestVersion());
        component.addAttribute("changelog", plugin.getChangelog());
        component.addAttribute("url", plugin.getURL());
        component.addAttribute("author", plugin.getAuthor());
        component.addAttribute("description", plugin.getDescription());
        component.addAttribute("icon", plugin.getIcon());
        component.addAttribute("minServerVersion", plugin.getMinServerVersion());
        component.addAttribute("readme", plugin.getReadme());
        component.addAttribute("licenseType", plugin.getLicenseType());
        component.addAttribute("fileSize", Long.toString(plugin.getFileSize()));
    }
    // Write data out to conf/available-plugins.xml file.
    Writer writer = null;
    try {
        // Create the conf folder if required
        File file = new File(JiveGlobals.getHomeDirectory(), "conf");
        if (!file.exists()) {
            file.mkdir();
        }
        file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf",
                "available-plugins.xml");
        // Delete the old version.xml file if it exists
        if (file.exists()) {
            file.delete();
        }
        // Create new version.xml with returned data
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
        xmlWriter.write(xml);
    }
    catch (Exception e) {
        Log.error(e.getMessage(), e);
    }
    finally {
        if (writer != null) {
            try {
                writer.close();
            }
            catch (IOException e1) {
                Log.error(e1.getMessage(), e1);
            }
        }
    }
}
 
Example 74
Project: g3server   File: UpdateManager.java   Source Code and License Vote up 4 votes
/**
 * Saves to conf/server-update.xml information about the latest Openfire release that is
 * available for download.
 */
private void saveLatestServerInfo() {
    Element xmlResponse = docFactory.createDocument().addElement("version");
    if (serverUpdate != null) {
        Element component = xmlResponse.addElement("openfire");
        component.addAttribute("latest", serverUpdate.getLatestVersion());
        component.addAttribute("changelog", serverUpdate.getChangelog());
        component.addAttribute("url", serverUpdate.getURL());
    }
    // Write data out to conf/server-update.xml file.
    Writer writer = null;
    try {
        // Create the conf folder if required
        File file = new File(JiveGlobals.getHomeDirectory(), "conf");
        if (!file.exists()) {
            file.mkdir();
        }
        file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf",
                "server-update.xml");
        // Delete the old server-update.xml file if it exists
        if (file.exists()) {
            file.delete();
        }
        // Create new version.xml with returned data
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
        xmlWriter.write(xmlResponse);
    }
    catch (Exception e) {
        Log.error(e.getMessage(), e);
    }
    finally {
        if (writer != null) {
            try {
                writer.close();
            }
            catch (IOException e1) {
                Log.error(e1.getMessage(), e1);
            }
        }
    }
}
 
Example 75
Project: Openfire   File: UpdateManager.java   Source Code and License Vote up 4 votes
/**
 * Saves to conf/available-plugins.xml the list of plugins that are available
 * at igniterealtime.org.
 */
private void saveAvailablePluginsInfo() {
    //  XML to store in the file
    Element xml = docFactory.createDocument().addElement("available");
    for (AvailablePlugin plugin : availablePlugins.values()) {
        Element component = xml.addElement("plugin");
        component.addAttribute("name", plugin.getName());
        component.addAttribute("latest", plugin.getVersion() != null ? plugin.getVersion().getVersionString() : null);
        component.addAttribute("changelog", plugin.getChangelog() != null ? plugin.getChangelog().toExternalForm() : null );
        component.addAttribute("url", plugin.getDownloadURL() != null ? plugin.getDownloadURL().toExternalForm() : null );
        component.addAttribute("author", plugin.getAuthor());
        component.addAttribute("description", plugin.getDescription());
        component.addAttribute("icon", plugin.getIcon() != null ? plugin.getIcon().toExternalForm() : null );
        component.addAttribute("minServerVersion", plugin.getMinServerVersion() != null ? plugin.getMinServerVersion().getVersionString() : null);
        component.addAttribute("priorToServerVersion", plugin.getPriorToServerVersion() != null ? plugin.getPriorToServerVersion().getVersionString() : null);
        component.addAttribute("readme", plugin.getReadme() != null ? plugin.getReadme().toExternalForm() : null );
        component.addAttribute( "licenseType", plugin.getLicense() );
        component.addAttribute("fileSize", Long.toString(plugin.getFileSize()));
    }
    // Write data out to conf/available-plugins.xml file.
    Writer writer = null;
    try {
        // Create the conf folder if required
        File file = new File(JiveGlobals.getHomeDirectory(), "conf");
        if (!file.exists()) {
            file.mkdir();
        }
        file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf",
                "available-plugins.xml");
        // Delete the old version.xml file if it exists
        if (file.exists()) {
            file.delete();
        }
        // Create new version.xml with returned data
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
        xmlWriter.write(xml);
    }
    catch (Exception e) {
        Log.error(e.getMessage(), e);
    }
    finally {
        if (writer != null) {
            try {
                writer.close();
            }
            catch (IOException e1) {
                Log.error(e1.getMessage(), e1);
            }
        }
    }
}
 
Example 76
Project: atlas   File: XmlHelper.java   Source Code and License Vote up 3 votes
public static void saveDocument(Document document, File file) throws IOException {

        file.getParentFile().mkdirs();

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");

        saveFile(document, format, file);
    }
 
Example 77
Project: hermes   File: PropertyTree.java   Source Code and License Vote up 3 votes
/**
 * Stores the properties to the specified url location.
 * 
 * @param url the url of the properties source.
 * @throws Exception if the operation is unsuccessful. 
 * @see hk.hku.cecid.piazza.commons.module.PersistentComponent#storing(java.net.URL)
 */
protected void storing(URL url) throws Exception {
    XMLWriter writer = new XMLWriter(new FileOutputStream(Convertor.toFile(url)),
            OutputFormat.createPrettyPrint());
    writer.write(dom);
    writer.close();
}
 
Example 78
Project: dls-repository-stack   File: Dom4jUtils.java   Source Code and License Vote up 2 votes
/**
 *  Write formated xml to file to faciliate human-readibility, using UTF-8 encoding.
 *
 * @param  doc            Documument to write
 * @param  out            File to write to
 * @exception  Exception  If error
 */
public static void writePrettyDocToFile(Document doc, File out)
	 throws Exception {
	OutputFormat format = OutputFormat.createPrettyPrint();
	writeDocToFile(doc, out, format);
}
 
Example 79
Project: APICloud-Studio   File: XMLUtil.java   Source Code and License Vote up 2 votes
/**
 * 写XML文件
 * @param file 文件
 * @param document XML对象
 * @return
 * @throws IOException
 */
public static boolean saveXml(File file, Document document) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint(); // 紧缩
    format.setEncoding("UTF-8"); // 设置UTF-8编码
    return saveXml(file, document, format);
}