Say you have a tomcat / conf / context.xml file that looks something like this:
<?xml version="1.0" encoding="utf-8"?> <Context> <WatchedResource>WEB-INF/web.xml</WatchedResource> <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource" removeAbandoned="true" removeAbandonedTimeout="15" maxActive="5" maxIdle="5" maxWait="7000" username="${db.mydb.uid}" password="${db.mydb.pwd}" driverClassName="${db.mydb.driver}" url="${db.mydb.url}${db.mydb.dbName}?autoReconnectForPools=true&characterEncoding=UTF-8" factory="com.mycompany.util.configuration.CustomDataSourceFactory" validationQuery="SELECT '1';" testOnBorrow="true"/> </Context>
What we want to replace in this case is something in the $ {file. *} in this resource definition. However, with a slight change to the code below, you can perform these substitutions by almost any criteria you would like.
Notice the line factory="com.mycompany.util.configuration.CustomDataSourceFactory"
This means that Tomcat will try to use this factory to process this resource. It should be noted that this means that this factory should be in the Tomcat classpath at startup (Personally, I put mine in the JAR in the Tomcat lib directory).
This is what my factory looks like:
package com.mycompany.util.configuration; import java.util.Hashtable; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.Context; import javax.naming.Name; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.StringRefAddr; import javax.naming.spi.ObjectFactory; import org.apache.commons.dbcp.BasicDataSourceFactory; public class CustomDataSourceFactory extends BasicDataSourceFactory implements ObjectFactory { private static final Pattern _propRefPattern = Pattern.compile("\\$\\{.*?\\}");
Then, as soon as this code is in the classpath, restart Tomcat and view the catalina.out file for log messages. NOTE. System.out.println operators are more likely to print sensitive information in your logs, so you can delete them after debugging is complete.
In the isolation, I wrote this because I found that many examples are too specific for one particular topic (for example, the use of cryptography), and I wanted to show how this can be done in general. In addition, some other answers to this question do not explain themselves very well, and I had to do something to figure out what needs to be done to complete this work. I wanted to share my findings with you guys. Please feel free to comment on this by asking any questions or making corrections if you find problems, and I will definitely get corrections in my answer.
source share