How do I get the list of Datasources available ?

A DataSource is the preferred means of getting a connection from a Database. Let’s learn how to fetch the list of Datasources which are configured in the application server using the CLI and programmatically.

WildFly / JBoss EAP 6/7

The simplest way to retrieve the list of Datasources at runtime is using the CLI:

./jboss-cli.sh --connect --command="/subsystem=datasources:read-resource" | grep "data-source"

On the other hand, if you are running in Domain mode, include the profile name in the CLI command. For example:

./jboss-cli.sh --connect --command=" /profile=full-ha/subsystem=datasources:read-resource" | grep "data-source"

To fetch the list of Datasources programmatically, you can also use the JMX API. Example:

import javax.management.*;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HelloWorld {
	public static void main(String[] args) throws Exception {
		status();
	}

	public static void status() throws Exception{
		String host = "localhost";
		int port = 9990;  // management-http port
		String urlString = "service:jmx:remote+http://" + host + ":" + port;
		System.out.println("\n\n\t****  urlString: "+urlString);;
		JMXServiceURL serviceURL = new JMXServiceURL(urlString);

		Map map = new HashMap();
		String[] credentials = new String[] { "admin", "admin" };
		map.put("jmx.remote.credentials", credentials);
		JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, map);

		MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();

                Set instances = connection.queryMBeans(null, null);
                Iterator iterator = instances.iterator();

                while (iterator.hasNext()) {
                  ObjectInstance instance = iterator.next();
                  if (instance.getObjectName().toString().startsWith("jboss.as:subsystem=datasources,data-source=") &&
                    (!instance.getObjectName().toString().contains(",statistics")))
                  System.out.println("Object Name:" + instance.getObjectName());

                }
	        jmxConnector.close();

	}

}

Please note that you need to include in your application’s classpath the jboss-client JAR files in order to be able to use the remote+http protocol:

<dependency>
  <groupId>org.wildfly</groupId>
  <artifactId>wildfly-client-all</artifactId>
  <version>20.0.0.Final</version>
</dependency>

JBOSS AS 4/5 Users

You can use the twiddle command line for this purpose:

$ twiddle.sh query "jboss.jca:service=DataSourceBinding,*"
Found the article helpful? if so please follow us on Socials