使用 groovy,我正在尝试读取 tomcat server.xml 并在<Resource name="jdbc/testDS" auth="Container" ..... >
缺少节点时插入新的节点资源标记。
Server.xml 的层次结构为 Server -> GlobalNamingResources -> Resource
尝试了 2 种方式:- 1) 读取 server.xml
groovy.util.XmlParser parser = new groovy.util.XmlParser();
println "tomcat.directory.path for server.xml >> " + "C:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/server.xml"
def root = parser.parse( "C:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/server.xml" )
datasourceToAdd = parser.parseText("<Resource name=\"jdbc/testDS\" auth=\"Container\" type=\"javax.sql.DataSource\" driverClassName=\"oracle.jdbc.OracleDriver\" url=\"jdbc:oracle:thin:@localhost:1521:ORA\" username=\"ORA_TEST\" password=\"*****\" factory=\"org.apache.commons.dbcp.BasicDataSourceFactory\" defaultAutoCommit=\"false\" maxActive=\"10\" maxIdle=\"5\" maxWait=\"30000\" whenExhaustedAction=\"1\" driver=\"oracle.jdbc.OracleDriver\"/>");
def nodeName = root.'**'.findAll { it.name()== 'jdbc/testDS' };
println "nodeName >>>>>>> " + nodeName;
if(!root.'**'.findAll { it.name()== 'jdbc/testDS' })
{
root.find { it.name() == 'GlobalNamingResources' }.children().add( 0, fragmentToAdd )
String outxml = groovy.xml.XmlUtil.serialize( root )
println outxml
}
这里的问题是无法将数据写回 server.xml 并且条件也不正确。如果条件正确,则需要将 xml 写回文件,但没有找到如何执行此操作。
2) 逐行读取 server.xml 并开始写入文件,如果找不到条目,则插入标签。这里也放置条件似乎有问题。
String cr = System.getProperty( "line.separator" );
File webXML = new File( "C:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/server2.xml" )
try
{
FileInputStream fstream = new FileInputStream( "C:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/server.xml" );
DataInputStream dataInputStream = new DataInputStream( fstream );
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( dataInputStream ) );
String strLine;
//Read File Line By Line
while ( ( strLine = bufferedReader.readLine() ) != null )
{
println ">>>>>" + strLine;
if(!strLine.contains("jdbc/testDS"))
{
webXML.append( strLine + cr );
}
}
dataInputStream.close();
AntBuilder ant = new AntBuilder()
ant.move(file: "C:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/server2.xml" , tofile: "C:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/server.xml" );
}
catch ( Exception e )
{//Catch exception if any
println( "Error: " + e.getMessage() );
}
我尝试的两种方法都不会给出预期的结果。知道如何实现这一目标吗?