XML类文件和监听方法
public class XMLFileListener extends FileListener
{
private Logger logger = Logger.getLogger(FileListener.class);
private EnumerateFile enumerateFile;
XMLFileListener(String filePath)
{
if (filePath != null)
{
this.file = new File(filePath);
if (!file.isFile())
{
logger.error("The file[" + filePath
+ "] doesn't exist, please check it.");
return;
}
enumerateFile = new EnumerateFile(filePath);
}
}
public boolean isFileUpdated()
{
return enumerateFile.getEnumFile().lastModified() > enumerateFile
.getEnumLastModifieds();
}
public void loadFile()
{
loadXml();
}
public String getPropertyValue(String key)
{
return getTransferValue(key);
}
private void loadXml()
{
// 更新时间
enumerateFile.setEnumLastModifieds(enumerateFile.getEnumFile()
.lastModified());
// 解析XML
Element rootElement = XMLParserHelperDom4j.parserXML(enumerateFile
.getEnumFile().getPath());
if (rootElement == null)
{
logger.error("The file[" + enumerateFile.getEnumFile().getPath()
+ "] parser error,please check again.");
}
else
{
// 将解析的文档的根节点保存,供以后读取所用
enumerateFile.setEnumElement(rootElement);
// logger.info("The file load:" + xmlBuf.toString());
logger.info("The properties file["
+ enumerateFile.getEnumFile().getPath()
+ "] load complete.");
}
}
public String getTransferValue(String key)
{
// 由 Type + OriginallyValue + value 或 Type + TransferAttr + value组成。
String[] keys = key.split("\\|\\|");
// 没有传Value 是返回null
if (keys.length == 2)
return null;
String transferValue = keys[2];
Element transferAttrs = XMLParserHelperDom4j.getElement(
enumerateFile.getEnumElement(), null, keys[0]);
if (transferAttrs == null)
{
return null;
}
for (Iterator<?> i = transferAttrs.elementIterator(); i.hasNext();)
{
Element transfer = (Element) i.next();
if (transfer == null)
continue;
String orig_str = XMLParserHelperDom4j.getText(transfer,
XMLParserHelperDom4j.ORIGINALL_VALUE);
String tran_str = XMLParserHelperDom4j.getText(transfer,
XMLParserHelperDom4j.TRANSFER_VALUE);
if (XMLParserHelperDom4j.ORIGINALL_VALUE.equals(keys[1])
&& keys[2].equals(orig_str))
{
transferValue = tran_str;
return transferValue;
}
else if (XMLParserHelperDom4j.TRANSFER_VALUE.equals(keys[1])
&& keys[2].equals(tran_str))
{
transferValue = orig_str;
return transferValue;
}
}
logger.warn("Cannot found the value [" + keys[2] + "] by node["
+ keys[0] + " in xml file]");
return transferValue;
}
}