Java Code Examples for org.dom4j.io.XMLWriter

The following examples show how to use org.dom4j.io.XMLWriter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: das   Source File: ResourceUtil.java    License: Apache License 2.0 6 votes vote down vote up
public boolean initializeDasSetXml() throws Exception {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement(DATA_SET_ROOT).addAttribute("name", DAS_SET_APPID);
    root.addElement("databaseSets").addElement("databaseSet")
            .addAttribute("name", DATA_SET_BASE).addAttribute("provider", "mysqlProvider")
            .addElement("add")
            .addAttribute("name", DATA_BASE)
            .addAttribute("connectionString", DATA_BASE)
            .addAttribute("databaseType", "Master")
            .addAttribute("sharding", "1");
    Element connectionLocator =  root.addElement("ConnectionLocator");
    connectionLocator.addElement("locator").addText("com.ppdai.das.core.DefaultConnectionLocator");
    connectionLocator.addElement("settings").addElement("dataSourceConfigureProvider").addText("com.ppdai.das.console.config.init.ConsoleDataSourceConfigureProvider");
    try (FileWriter fileWriter = new FileWriter(getDasXmlPath())) {
        XMLWriter writer = new XMLWriter(fileWriter);
        writer.write(document);
        writer.close();
    }
    return true;
}
 
Example 2
Source Project: ofdrw   Source File: TestTool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 生成XML 并打印打控制台
 *
 * @param name 文件名称
 * @param call 元素添加方法
 */
public static void genXml(String name, Consumer<Document> call) {
    Document doc = DocumentHelper.createDocument();
    String filePath = TEST_DEST + File.separator + name + ".xml";
    try (FileOutputStream out = new FileOutputStream(filePath)) {
        call.accept(doc);

        // 格式化打印到控制台
        XMLWriter writerToSout = new XMLWriter(System.out, FORMAT);
        writerToSout.write(doc);

        // 打印打到文件
        XMLWriter writeToFile = new XMLWriter(out, FORMAT);
        writeToFile.write(doc);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source Project: olat   Source File: QTIExportImportTest.java    License: Apache License 2.0 6 votes vote down vote up
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 4
private static File createPernsistenceXml(List<Class<?>> classes, File directory) throws Exception {
	Document document = DocumentHelper.createDocument();
	Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
	persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
			"http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
	persistence.addAttribute("version", "2.0");
	Element unit = persistence.addElement("persistence-unit");
	unit.addAttribute("name", "enhance");
	for (Class<?> o : classes) {
		Element element = unit.addElement("class");
		element.addText(o.getCanonicalName());
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	File file = new File(directory, "persistence.xml");
	XMLWriter writer = new XMLWriter(new FileWriter(file), format);
	writer.write(document);
	writer.close();
	return file;
}
 
Example 5
public static String toString(final Element el, final boolean prettyFormat)
{
  if (el == null) {
    return "";
  }
  final StringWriter out = new StringWriter();
  final OutputFormat format = new OutputFormat();
  if (prettyFormat == true) {
    format.setNewlines(true);
    format.setIndentSize(2);
  }
  final XMLWriter writer = new XMLWriter(out, format);
  String result = null;
  try {
    writer.write(el);
    result = out.toString();
    writer.close();
  } catch (final IOException ex) {
    log.error(ex.getMessage(), ex);
  }
  return result;
}
 
Example 6
public void doWork(XmlPullParser reader, XMLWriter writer)
	throws Exception
{
	// Deal with the contents of the tag
	int eventType = reader.getEventType();
	while (eventType != XmlPullParser.END_TAG) 
       {
		eventType = reader.next();
		if (eventType == XmlPullParser.START_TAG) 
		{
			ImportFileUpdater.this.outputCurrentElement(reader, writer, new OutputChildren());
		}
		else if (eventType == XmlPullParser.TEXT)
		{
			// Write the text to the output file
			writer.write(reader.getText());
		}
       }			
}
 
Example 7
Source Project: onos   Source File: XmppStreamOpen.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toXml() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createCompactFormat());
    try {
        out.write("<");
        writer.write(element.getQualifiedName());
        for (Attribute attr : (List<Attribute>) element.attributes()) {
            writer.write(attr);
        }
        writer.write(Namespace.get(this.element.getNamespacePrefix(), this.element.getNamespaceURI()));
        writer.write(Namespace.get("jabber:client"));
        out.write(">");
    } catch (IOException ex) {
        log.info("Error writing XML", ex);
    }
    return out.toString();
}
 
Example 8
Source Project: CEC-Automatic-Annotation   Source File: WriteToXMLUtil.java    License: Apache License 2.0 6 votes vote down vote up
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 9
/**
 * 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 10
Source Project: CogniCrypt   Source File: XSLConfiguration.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public File persistConf() throws IOException {
	final XMLClaferParser parser = new XMLClaferParser();
	Document configInXMLFormat = parser.displayInstanceValues(instance, this.options);
	if (configInXMLFormat != null) {
		final OutputFormat format = OutputFormat.createPrettyPrint();
		final XMLWriter writer = new XMLWriter(new FileWriter(pathOnDisk), format);
		writer.write(configInXMLFormat);
		writer.close();
		configInXMLFormat = null;

		return new File(pathOnDisk);
	} else {
		Activator.getDefault().logError(Constants.NO_XML_INSTANCE_FILE_TO_WRITE);
	}
	return null;

}
 
Example 11
Source Project: urule   Source File: FrameServletHandler.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 12
Source Project: ApkCustomizationTool   Source File: Command.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 修改bools.xml文件内容
 *
 * @param file  bools文件
 * @param bools 修改的值列表
 */
private void updateBools(File file, List<Bools> bools) {
    try {
        if (bools == null || bools.isEmpty()) {
            return;
        }
        Document document = new SAXReader().read(file);
        List<Element> elements = document.getRootElement().elements();
        elements.forEach(element -> {
            final String name = element.attribute("name").getValue();
            bools.forEach(s -> {
                if (s.getName().equals(name)) {
                    element.setText(s.getValue());
                    callback("修改 bools.xml name='" + name + "' value='" + s.getValue() + "'");
                }
            });
        });
        XMLWriter writer = new XMLWriter(new FileOutputStream(file));
        writer.write(document);
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 13
Source Project: olat   Source File: ContentPackage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 14
/**
 * Output the supported lock types XML element
 * 
 * @param xml XMLWriter
 */
protected void writeLockTypes(XMLWriter xml)
{
    try
    {
        AttributesImpl nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_SUPPORTED_LOCK, WebDAV.XML_NS_SUPPORTED_LOCK, nullAttr);

        // Output exclusive lock
        // Shared locks are not supported, as they cannot be supported by the LockService (relevant to ALF-16449).
        writeLock(xml, WebDAV.XML_NS_EXCLUSIVE);

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_SUPPORTED_LOCK, WebDAV.XML_NS_SUPPORTED_LOCK);
    }
    catch (Exception ex)
    {
        throw new AlfrescoRuntimeException("XML write error", ex);
    }
}
 
Example 15
/**
 * Generates the error tag
 * 
 * @param xml XMLWriter
 */
protected void generateError(XMLWriter xml)
{
    try
    {
        // Output the start of the error element
        Attributes nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR, nullAttr);
        // Output error
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_CANNOT_MODIFY_PROTECTED_PROPERTY));

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR);
    }
    catch (Exception ex)
    {
        // Convert to a runtime exception
        throw new AlfrescoRuntimeException("XML processing error", ex);
    }
}
 
Example 16
Source Project: yarg   Source File: DefaultXmlWriter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String buildXml(Report report) {
    try {
        Document document = DocumentFactory.getInstance().createDocument();
        Element root = document.addElement("report");

        root.addAttribute("name", report.getName());
        writeTemplates(report, root);
        writeInputParameters(report, root);
        writeValueFormats(report, root);
        writeRootBand(report, root);

        StringWriter stringWriter = new StringWriter();
        new XMLWriter(stringWriter, OutputFormat.createPrettyPrint()).write(document);
        return stringWriter.toString();
    } catch (IOException e) {
        throw new ReportingException(e);
    }
}
 
Example 17
Source Project: olat   Source File: ContentPackage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 18
private void write() {
    double pressLat = viewer.getLatitude(press.y);
    double pressLon = viewer.getLongitude(press.x);
    double releaseLat = viewer.getLatitude(release.y);
    double releaseLon = viewer.getLongitude(release.x);
    try {
        OSMMap newMap = new OSMMap(map,
                                   Math.min(pressLat, releaseLat),
                                   Math.min(pressLon, releaseLon),
                                   Math.max(pressLat, releaseLat),
                                   Math.max(pressLon, releaseLon));
        Document d = newMap.toXML();
        XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
        writer.write(d);
        writer.flush();
        writer.close();
        System.out.println("Wrote map");
    }
    // CHECKSTYLE:OFF:IllegalCatch
    catch (Exception ex) {
        ex.printStackTrace();
    }
    // CHECKSTYLE:ON:IllegalCatch
}
 
Example 19
Source Project: unitime   Source File: StudentSolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] backupXml() {
	java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock();
       lock.lock();
       try {
           ByteArrayOutputStream ret = new ByteArrayOutputStream();
           GZIPOutputStream gz = new GZIPOutputStream(ret);
           
           Document document = createCurrentSolutionBackup(false, false);
           saveProperties(document);
           
           new XMLWriter(gz, OutputFormat.createCompactFormat()).write(document);
           
           gz.flush(); gz.close();

           return ret.toByteArray();
       } catch (Exception e) {
           sLog.error(e.getMessage(),e);
           return null;
       } finally {
       	lock.unlock();
       }
}
 
Example 20
Source Project: unitime   Source File: AbstractSolver.java    License: Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 21
Source Project: unitime   Source File: SolverImport.java    License: Apache License 2.0 5 votes vote down vote up
protected byte[] toData(Element root) throws UnsupportedEncodingException, IOException {
	Element configEl = root.element("configuration");
	if (configEl != null) root.remove(configEl);
	
	ByteArrayOutputStream ret = new ByteArrayOutputStream();
	(new XMLWriter(ret, OutputFormat.createCompactFormat())).write(root.getDocument());
       ret.flush(); ret.close();
       return ret.toByteArray();
}
 
Example 22
Source Project: ofdrw   Source File: ElemCup.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 序列化文档对象
 *
 * @param e  文档对象
 * @param to 目标目录
 * @throws IOException IO异常
 */
public static void dump(Element e, Path to) throws IOException {
    if (e == null) {
        return;
    }
    if (to == null) {
        throw new IllegalArgumentException("文档元素序列化目标目录(to)为空");
    }
    if (Files.notExists(to)) {
        if (Files.notExists(to.getParent())) {
            Files.createDirectories(to.getParent());
        }
        Files.createFile(to);
    }

    Document doc = DocumentHelper.createDocument();
    if (e.getDocument() != null) {
        // 如果元素所属文档不为空,说明是从文件中加载得到,此时需要Clone这个对象以放入新的Document中
        e = (Element) e.clone();
    }
    doc.add(e);
    try (OutputStream out = Files.newOutputStream(to)) {
        XMLWriter writeToFile = new XMLWriter(out);
        writeToFile.write(doc);
        writeToFile.close();
    }
}
 
Example 23
Source Project: ofdrw   Source File: TestTool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取对应元素的XML文本文件的字节内容
 *
 * @param element 元素
 * @return 字节内容
 */
public static byte[] xmlByte(Element element) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        XMLWriter writerToSout = new XMLWriter(out, FORMAT);
        writerToSout.write(element);
        writerToSout.flush();
        return out.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 24
Source Project: birt   Source File: VersionUpdater.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @author 
 * @param folderPath
 * @param plug_id
 * @param lastDate
 * @param dayInpast
 */
private void genVersionLog(	File folderPath , 
							String plug_id , 
							String lastDate , 
							int dayInpast ){
	// gen the dest file path
	String parentPath = folderPath.getAbsolutePath();
	String fileName = plug_id + "_DayInPast" + ".xml";
	String fullName = parentPath + "/" + fileName;
	File dest = new File(fullName);
	System.out.println("dest file full path:\t"+fullName);
	try{
		//genarate document factory
		DocumentFactory factory = new DocumentFactory();
		//create root element
		DOMElement rootElement = new DOMElement("plugin");
		rootElement.setAttribute("id",plug_id);
		//add child:lastdate
		DOMElement dateElement = new DOMElement("LastDate");
		dateElement.setText(lastDate);
		rootElement.add(dateElement);
		//add child:dayinpast
		DOMElement dayElement = new DOMElement("DayInPast");
		dayElement.setText( Integer.toString(dayInpast));
		rootElement.add(dayElement);
		//gen the doc
		Document doc = factory.createDocument(rootElement);
	
		//PrettyFormat
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter( new FileWriter(dest) , format );
		writer.write( doc );
		writer.close();

	}catch(Exception ex){
		ex.printStackTrace();
	}

}
 
Example 25
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 26
Source Project: cpsolver   Source File: Test.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Save the problem and the resulting assignment
 * @param outputDir output directory
 * @param assignment final assignment
 */
protected void save(File outputDir, Assignment<TeachingRequest.Variable, TeachingAssignment> assignment) {
    try {
        File outFile = new File(outputDir, "solution.xml");
        FileOutputStream fos = new FileOutputStream(outFile);
        try {
            (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(save(assignment));
            fos.flush();
        } finally {
            fos.close();
        }
    } catch (Exception e) {
        sLog.error("Failed to save solution: " + e.getMessage(), e);
    }
}
 
Example 27
Source Project: iaf   Source File: XmlUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String canonicalize(String input) throws DocumentException, IOException {
	if (StringUtils.isEmpty(input)) {
		return null;
	}
	org.dom4j.Document doc = DocumentHelper.parseText(input);
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setExpandEmptyElements(true);
	XMLWriter xw = new XMLWriter(sw, format);
	xw.write(doc);
	return sw.toString();
}
 
Example 28
Source Project: eclipse-cs   Source File: XMLUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a pretty printed representation of the document as a byte array.
 * 
 * @param document
 *          the document
 * @return the document as a byte array (UTF-8)
 * @throws IOException
 *           Exception while serializing the document
 */
public static byte[] toByteArray(Document document) throws IOException {

  ByteArrayOutputStream byteOut = new ByteArrayOutputStream(512);

  // Pretty print the document to System.out
  OutputFormat format = OutputFormat.createPrettyPrint();
  XMLWriter writer = new XMLWriter(byteOut, format);
  writer.write(document);

  return byteOut.toByteArray();
}
 
Example 29
private static void write(Argument arg) throws Exception {
	try {
		Document document = DocumentHelper.createDocument();
		Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
		persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
				"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
		persistence.addAttribute("version", "2.0");
		for (Class<?> cls : scanContainerEntity(arg.getProject())) {
			Element unit = persistence.addElement("persistence-unit");
			unit.addAttribute("name", cls.getCanonicalName());
			unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
			Element provider = unit.addElement("provider");
			provider.addText(PersistenceProviderImpl.class.getCanonicalName());
			for (Class<?> o : scanMappedSuperclass(cls)) {
				Element mapped_element = unit.addElement("class");
				mapped_element.addText(o.getCanonicalName());
			}
			Element slice_unit_properties = unit.addElement("properties");
			Map<String, String> properties = new LinkedHashMap<String, String>();
			for (Entry<String, String> entry : properties.entrySet()) {
				Element property = slice_unit_properties.addElement("property");
				property.addAttribute("name", entry.getKey());
				property.addAttribute("value", entry.getValue());
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File(arg.getPath());
		XMLWriter writer = new XMLWriter(new FileWriter(file), format);
		writer.write(document);
		writer.close();
		System.out.println("create persistence.xml at path:" + arg.getPath());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 30
public static List<String> directWrite(String path, List<String> classNames) throws Exception {
	try {
		Document document = DocumentHelper.createDocument();
		Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
		persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
				"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
		persistence.addAttribute("version", "2.0");
		for (String className : classNames) {
			Element unit = persistence.addElement("persistence-unit");
			unit.addAttribute("name", className);
			unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
			Element provider = unit.addElement("provider");
			provider.addText(PersistenceProviderImpl.class.getName());
			Element mapped_element = unit.addElement("class");
			mapped_element.addText(className);
			Element sliceJpaObject_element = unit.addElement("class");
			sliceJpaObject_element.addText("com.x.base.core.entity.SliceJpaObject");
			Element jpaObject_element = unit.addElement("class");
			jpaObject_element.addText("com.x.base.core.entity.JpaObject");
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File(path);
		FileUtils.touch(file);
		XMLWriter writer = new XMLWriter(new FileWriter(file), format);
		writer.write(document);
		writer.close();
		return classNames;
	} catch (Exception e) {
		throw new Exception("registContainerEntity error.className:" + ListTools.toStringJoin(classNames), e);
	}
}