Logging and Using JNDI Resources from a Plugin
Modified on: Mon, 10 Oct, 2022 at 4:51 PM
In this article you will find out more about importing a SL4J logger and using the JNDI resources from a plugin.
When writing either an enricher or validation plugin in Java, you will almost certainly require logging and you may require database connections. Rather than trying to re-invent the wheel, it is simple and straightforward to piggy back on the JNDI resources stored in the semarchy.xml and also leverage the PDE log from within the code.
Firstly, to use the JNDI resources you use the fact that Tomcat has loaded these as resources during start-up. From this, you can get a connection with 3 lines of code (see full code attached for imports):
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/SEMARCHY_CUSTOMER_B2C_MDM");
Connection con = ds.getConnection();
This connection should be managed like any other connection through try-catch blocks and closed once it is finished. The one gotcha is that in some examples the Context object is closed. This will remove the resources from Tomcat, and so the enricher may work the first time, but then once the context is closed it will no longer surface the JNDI data sources. Just don't close the Context object, but definitely still close the any connection, statements or result sets you get from it.
To use the logging is slightly trickier, only because it requires an additional set of libraries that aren't standard Java. You need to add an "Imported Packages" to import org.slf4j (1.7.0) (note that it must be this version - the most recent version does not work of Semarchy xDM). See the screenshot below for how to do this.
After adding the dependency, you will now be able to use the slf4j logger. First you should import the Logger and LoggerFactory: