XmlUtils.java 2.34 KB
package com.topdraw.sohu.utils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class XmlUtils {
	private static final Logger logger = LoggerFactory.getLogger(XmlUtils.class);
	public static final String FTP_PATH = "/app/proftpd/smp/";
	public static final String XML_RELATIVE_PATH = "notify/xml/";
	
	public String generateNotifyXml(int iResult, String strErrorDescripiton) {
		String strRet = "";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String strDate = sdf.format(date) + "/";
		String strRelativePath = XML_RELATIVE_PATH + strDate + UUID.randomUUID() + ".xml";
		String strPath = FTP_PATH + strRelativePath;

		File file = new File(strPath);
		if (!file.isDirectory()) { // 目录不存在
			String[] aPathSegments = strPath.split("/");
			String strWalkThroughPath = "/";
			for (int i = 0; i < aPathSegments.length - 1; i++) {
				strWalkThroughPath = strWalkThroughPath + "/" + aPathSegments[i];
				file = new File(strWalkThroughPath);
				if (!file.isDirectory()) {
					file.mkdir();
				}
			}
		}

		Document document = DocumentHelper.createDocument();
		Element el = document.addElement("xsi:ADI");
		el.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
		Element elReply = el.addElement("Reply");
		Element elPropertyResult = elReply.addElement("Property");
		Element elPropertyDescription = elReply.addElement("Property");
		elPropertyResult.addAttribute("Name", "Result");
		elPropertyDescription.addAttribute("Name", "Description");
		elPropertyResult.setText(iResult + "");
		elPropertyDescription.setText(strErrorDescripiton);

		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		format.setNewLineAfterDeclaration(false);
		try {
			XMLWriter writer = new XMLWriter(new FileOutputStream(strPath), format);
			writer.setEscapeText(false);
			writer.write(document);
			writer.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return PropertiesUtil.get("project.ftp_base_url") + strRelativePath;

	}
	
	public static void main(String[] args) {

	}
}