Skip to main content
Announcements
New: No-code data prep in Qlik Cloud Analytics™ TAKE A TOUR
cancel
Showing results for 
Search instead for 
Did you mean: 
Ahhouais
Contributor
Contributor

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.

Labels (2)
3 Replies
Anonymous
Not applicable

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.
Ahhouais
Contributor
Contributor
Author

Hi Christian !
Thank you for your response.
I found a nice code on your site (github.com/cschneider) 0683p000009MA9p.png
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
Ahhouais
Contributor
Contributor
Author

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 0683p000009MPcz.png
Thanks