Karaf : accessing a DataSource in pur Java code

One Star

Karaf : accessing a DataSource in pur Java code

Hi everybody,
I have declared a datasource in Karaf using a blueprint file.
The file looks like that :
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/care4drupal"/>
<property name="username" value="xxx" />
<property name="password" value="xxx" />
<property name="initialSize" value="5" />
<property name="maxIdle" value="10"/>
<property name="minIdle" value="10" />
<property name="maxActive" value="25"/>
<property name="maxWait" value="-1"/>
<property name="validationQuery" value="select 1"/>
<property name="testOnBorrow" value="false"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="120000"/>
<property name="minEvictableIdleTimeMillis" value="180000"/>
<property name="numTestsPerEvictionRun" value="2"/>
<property name="defaultAutoCommit" value="false"/>
</bean>
<service interface="javax.sql.DataSource" ref="dataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="jdbc/mysqlSimulateur"/>
</service-properties>
</service>
</blueprint>

My question is very simple : how can access this DataSource in pur java code (inside a routines or a tJava component) ?
I have tried something like that :
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("osgi:service/javax.sqlDataSource/(name=jdbc/mysqlSimulateur)");
and
Context ctx = new InitialContext();
DataSource ds2 = (DataSource) ctx.lookup("osgi:service/jdbc/mysqlSimulateur");
but it doesn't work !
Any idea ?
Best regards.

Re: Karaf : accessing a DataSource in pur Java code

For the jndi lookup to work you must have aries jndi installed (feature jndi).
If you use pure java then injecting the DataSource as an OSGi service is better than using jndi.
One Star

Re: Karaf : accessing a DataSource in pur Java code

Hi Christian !
Thank you for your response.
I found a nice code on your site (github.com/cschneider) Smiley Wink
This is exaclty what I want to use.
In your code, you use an EmbeddedDataSource, with a derby database.
Do you know if there is the same logic with MySQL ?
Regards
One Star

Re: Karaf : accessing a DataSource in pur Java code

Hi Christian,
Have you got a sample of code for "injecting the DataSource as an OSGi service" ?
I am not familiar to the injection at all Smiley Sad
Thanks