org.dom4j.io.XMLWriter Java Examples

The following examples show how to use org.dom4j.io.XMLWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractSolver.java    From unitime with 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 #2
Source File: QTIExportImportTest.java    From olat with 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 #3
Source File: EnhanceBaseBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #4
Source File: TestTool.java    From ofdrw with 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 #5
Source File: XmlHelper.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
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
Source File: ImportFileUpdater.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 File: XmppStreamOpen.java    From onos with 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 File: WriteToXMLUtil.java    From CEC-Automatic-Annotation with 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
Source File: XMLTransferReportWriter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 File: XSLConfiguration.java    From CogniCrypt with 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 File: Command.java    From ApkCustomizationTool with 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 #12
Source File: ContentPackage.java    From olat with 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 #13
Source File: PropFindMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #14
Source File: PropPatchMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #15
Source File: DefaultXmlWriter.java    From yarg with 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 #16
Source File: ContentPackage.java    From olat with 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 #17
Source File: FrameServletHandler.java    From urule with 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 #18
Source File: OSMMapExtractor.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 File: StudentSolver.java    From unitime with 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 File: ResourceUtil.java    From das with 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 #21
Source File: WFGraph.java    From EasyML with Apache License 2.0 5 votes vote down vote up
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
Source File: PropFindMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates the required response XML for the current node
 * 
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param path String
 */
protected void generateResponseForNode(XMLWriter xml, FileInfo nodeInfo, String path) throws Exception
{
    boolean isFolder = nodeInfo.isFolder();
    
    // Output the response block for the current node
    xml.startElement(
            WebDAV.DAV_NS,
            WebDAV.XML_RESPONSE,
            WebDAV.XML_NS_RESPONSE,
            getDAVHelper().getNullAttributes());

    // Build the href string for the current node
    String strHRef = getURLForPath(m_request, path, isFolder);

    xml.startElement(WebDAV.DAV_NS, WebDAV.XML_HREF, WebDAV.XML_NS_HREF, getDAVHelper().getNullAttributes());
    xml.write(strHRef);
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_HREF, WebDAV.XML_NS_HREF);

    switch (m_mode)
    {
    case GET_NAMED_PROPS:
        generateNamedPropertiesResponse(xml, nodeInfo, isFolder);
        break;
    case GET_ALL_PROPS:
        generateAllPropertiesResponse(xml, nodeInfo, isFolder);
        break;
    case FIND_PROPS:
        generateFindPropertiesResponse(xml, nodeInfo, isFolder);
        break;
    }

    // Close off the response element
    xml.endElement(WebDAV.DAV_NS, WebDAV.XML_RESPONSE, WebDAV.XML_NS_RESPONSE);
}
 
Example #23
Source File: IoUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭XMLWriter输出流
 * @param out
 */
public static void close(XMLWriter out){
    if(out != null){
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #24
Source File: Test.java    From cpsolver with 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 #25
Source File: PropFindMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates the XML response snippet showing the lock information for the
 * given path
 * 
 * @param xml XMLWriter
 * @param nodeInfo FileInfo
 * @param isDir boolean
 */
protected void generateLockDiscoveryResponse(XMLWriter xml, FileInfo nodeInfo, boolean isDir) throws Exception
{
    // Output the lock status response
    LockInfo lockInfo = getNodeLockInfo(nodeInfo);
    if (lockInfo.isLocked() && !lockInfo.isExpired())
    {
        generateLockDiscoveryXML(xml, nodeInfo, lockInfo);
    }
}
 
Example #26
Source File: CurriculumClassification.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void setStudentsDocument(Document document) {
	try {
		if (document == null) {
			setStudents(null);
		} else {
			StringWriter string = new StringWriter();
			XMLWriter writer = new XMLWriter(string, OutputFormat.createCompactFormat());
			writer.write(document);
			writer.flush(); writer.close();
			setStudents(string.toString());
		}
	} catch (Exception e) {
		sLog.warn("Failed to store cached students for " + getCurriculum().getAbbv() + " " + getName() + ": " + e.getMessage(), e);
	}
}
 
Example #27
Source File: SolverInfo.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void setValue(Document document) {
	try {
		if (document == null) {
			setData(null);
		} else {
			 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
             XMLWriter writer = new XMLWriter(new GZIPOutputStream(bytes),OutputFormat.createCompactFormat());
             writer.write(document);
             writer.flush(); writer.close();
             setData(bytes.toByteArray());
		}
	} catch (IOException e) {
		throw new HibernateException(e.getMessage(),e);
	}
}
 
Example #28
Source File: WebDAVMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Flushes all XML written so far to the response
 * 
 * @param writer XMLWriter that should be flushed
 */
protected final void flushXML(XMLWriter writer) throws IOException
{
    if (shouldFlushXMLWriter())
    {
        writer.flush();
    }
    
    m_response.getWriter().write(m_xmlWriter.toCharArray());
    
    m_xmlWriter.reset();
}
 
Example #29
Source File: VersionUpdater.java    From birt with 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 #30
Source File: PropPatchMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates the XML response for a PROPFIND request that asks for a list of
 * all known properties
 * 
 * @param xml XMLWriter
 * @param property WebDAVProperty
 * @param status int
 * @param description String
 */
protected void generatePropertyResponse(XMLWriter xml, WebDAVProperty property, int status, String description)
{
    try
    {
        // Output the start of the properties element
        Attributes nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);

        // Output property name
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);
        if (property.hasNamespaceName())
        {
            xml.write(DocumentHelper.createElement(property.getNamespaceName() + WebDAV.NAMESPACE_SEPARATOR + property.getName()));
        }
        else
        {
            xml.write(DocumentHelper.createElement(property.getName()));
        }
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);

        // Output action result status
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
        xml.write(WebDAV.HTTP1_1 + " " + status + " " + description);
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);
    }
    catch (Exception ex)
    {
        // Convert to a runtime exception
        throw new AlfrescoRuntimeException("XML processing error", ex);
    }
}