Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

AEM 6.3 DataSourcePool reference annotation is null

Avatar

Level 6

Hi All,

I am using mysql database, used datasourcepool to connect, but @Reference is not working. DataSourcePool is null always.

I have added dependency in pom file and did proper JDBC configuration in felix console.

Please advise to fix this null pointer exception. Below is my code.

@Component

@Service

public class InsertRowService implements InsertRow {

    private static Logger LOG = LoggerFactory.getLogger(InsertRowService.class);

   

@Reference

    private DataSourcePool dataSourceService;

@Override

public void insertRow() {

    LOG.info("Inside insertRow of InsertRowService");

Statement statement = null;

Connection con = null;

        try {

        if(dataSourceService == null) {

        LOG.info("dataSourceService is null");

        }

DataSource ds = (DataSource) dataSourceService.getDataSource("Customer");

if(ds != null)

con = ds.getConnection();

if(con != null)

statement = con.createStatement();

Thanks,

Pradeep

1 Accepted Solution

Avatar

Correct answer by
Level 10

I works nicely with HTL - you can use Sling Models. Here is the Service Interface for MySQL operation:

CustDataService

package com.aem.community.core;

public interface CustDataService {

public String getTotalCustomers() ;

}

CustDataServiceImp (contains app logic)

package com.aem.community.core;

import org.osgi.service.component.annotations.Component;

import org.osgi.service.component.annotations.Reference;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

//Add the DataSourcePool package

import com.day.commons.datasource.poolservice.DataSourcePool;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.SQLException;

import javax.sql.DataSource;

@Component(service = CustDataService.class,

        immediate = true

        )

public class CustDataServiceImp implements CustDataService{

  private final Logger logger = LoggerFactory.getLogger(getClass());

@Reference

    private DataSourcePool source;

//Returns the number of customs in the Customer table

public String getTotalCustomers()

{

Connection c = null;

int rowcount = 0;

String strCount ="";

try

{

logger.info("**** ABOUT TO CREATE CONNECTION"); 

// Create a Connection object

            c =  getConnection();

         

             ResultSet rs = null;

             Statement s = c.createStatement();

             Statement stmt = c.createStatement();

               

             //Query all

             String query = "select * from customer" ;

             rs = stmt.executeQuery(query) ;

             while (rs.next())

             {

                

            rowcount++;

             }

            

             logger.info("**** CUST REC IS "+rowcount) ;

            

             strCount = java.lang.Integer.toString(rowcount);

                         

             return strCount;

}

catch(Exception e)

{

e.printStackTrace() ;

}

return ""  ;

}

//Returns a connection using the configured DataSourcePool

public Connection getConnection()

  {

           DataSource dataSource = null;

           Connection con = null;

           try

           {

               //Inject the DataSourcePool right here!

               dataSource = (DataSource) source.getDataSource("Customer");

               con = dataSource.getConnection();

               return con;

               

             }

           catch (Exception e)

           {

               e.printStackTrace();

           }

               return null;

  }

}

THis is the great part - we can call into the Service from the Sling Model class like this:

/*

*  Copyright 2015 Adobe Systems Incorporated

*

*  Licensed under the Apache License, Version 2.0 (the "License");

*  you may not use this file except in compliance with the License.

*  You may obtain a copy of the License at

*

*      http://www.apache.org/licenses/LICENSE-2.0

*

*  Unless required by applicable law or agreed to in writing, software

*  distributed under the License is distributed on an "AS IS" BASIS,

*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

*  See the License for the specific language governing permissions and

*  limitations under the License.

*/

package com.aem.community.core.models;

import javax.annotation.PostConstruct;

import javax.inject.Inject;

import javax.inject.Named;

import org.apache.sling.api.resource.Resource;

import org.apache.sling.models.annotations.Default;

import org.apache.sling.models.annotations.Model;

import org.apache.sling.settings.SlingSettingsService;

import com.aem.community.core.CustDataService;

@Model(adaptables=Resource.class)

public class HelloWorldModel {

    @Inject

    private SlingSettingsService settings;

   

    @Inject

    private CustDataService custSer;

    @Inject @Named("sling:resourceType") @Default(values="No resourceType")

    protected String resourceType;

    private String message;

    @PostConstruct

    protected void init() {

        message = "\tHello World!\n";

        message += "\tThis is instance: " + settings.getSlingId() + "\n";

       message += "\tNumber of Customer Records: " + custSer.getTotalCustomers() + "\n";

    }

    public String getMessage() {

        return message;

    }

}

We will get all of this into a HELPX  artilce that we will release early next week.

View solution in original post

11 Replies

Avatar

Level 10

Have you added the Database Driver file into an OSGi bundle?

Avatar

Level 10

See the Video here and make sure that you do everything.

Scott's Digital Community: Injecting a DataSourcePool Service into an Adobe Experience Manager OSGi ...

In meantime - i will also test on AEM 6.3 and post back results.

Avatar

Level 10

I am going to update the DataSourePool article for AEM 6.3 and post back here.

Avatar

Level 10

I just tested on AEM 6.3 and it worked. I will write a walkthrough. Here is an HTL component returning the number of records in a table:

COunt.png

When configuring AEM to use a DataSourcePool - make sure that you are filling in the configuration view properly. See:

DataSource.png

Avatar

Level 6

Hi smacdonald,

First of all sorry i am not using 6.3 , i am using AEM 6.2. Wrongly mentioned 6.3.

I didn't add any database driver in OSGi console. Let me know what driver i have to add to connect MySQL. Please share driver if you have.

Thanks,

Pradeep

Avatar

Level 10

If needed, we can have a connect session!

Avatar

Level 6

Hi Smacdonald,

Finally it worked if follow all steps mentioned in video. But that is in JSP. When i tried in WCMUsePojo class same error is coming(DataSourcePool reference is null). Will this support only in JSP? Or sightly code is also available for same?

Code works only if i call like below

com.test.core.InsertRow custService = sling.getService(com.sling.tv.core.InsertRow.class);

Will not work if call  like below

com.test.core.InsertRowService custService = new InsertRowService();

Why it is working in 1st case but not in 2nd?

Thanks,

Pradeep

Avatar

Correct answer by
Level 10

I works nicely with HTL - you can use Sling Models. Here is the Service Interface for MySQL operation:

CustDataService

package com.aem.community.core;

public interface CustDataService {

public String getTotalCustomers() ;

}

CustDataServiceImp (contains app logic)

package com.aem.community.core;

import org.osgi.service.component.annotations.Component;

import org.osgi.service.component.annotations.Reference;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

//Add the DataSourcePool package

import com.day.commons.datasource.poolservice.DataSourcePool;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.SQLException;

import javax.sql.DataSource;

@Component(service = CustDataService.class,

        immediate = true

        )

public class CustDataServiceImp implements CustDataService{

  private final Logger logger = LoggerFactory.getLogger(getClass());

@Reference

    private DataSourcePool source;

//Returns the number of customs in the Customer table

public String getTotalCustomers()

{

Connection c = null;

int rowcount = 0;

String strCount ="";

try

{

logger.info("**** ABOUT TO CREATE CONNECTION"); 

// Create a Connection object

            c =  getConnection();

         

             ResultSet rs = null;

             Statement s = c.createStatement();

             Statement stmt = c.createStatement();

               

             //Query all

             String query = "select * from customer" ;

             rs = stmt.executeQuery(query) ;

             while (rs.next())

             {

                

            rowcount++;

             }

            

             logger.info("**** CUST REC IS "+rowcount) ;

            

             strCount = java.lang.Integer.toString(rowcount);

                         

             return strCount;

}

catch(Exception e)

{

e.printStackTrace() ;

}

return ""  ;

}

//Returns a connection using the configured DataSourcePool

public Connection getConnection()

  {

           DataSource dataSource = null;

           Connection con = null;

           try

           {

               //Inject the DataSourcePool right here!

               dataSource = (DataSource) source.getDataSource("Customer");

               con = dataSource.getConnection();

               return con;

               

             }

           catch (Exception e)

           {

               e.printStackTrace();

           }

               return null;

  }

}

THis is the great part - we can call into the Service from the Sling Model class like this:

/*

*  Copyright 2015 Adobe Systems Incorporated

*

*  Licensed under the Apache License, Version 2.0 (the "License");

*  you may not use this file except in compliance with the License.

*  You may obtain a copy of the License at

*

*      http://www.apache.org/licenses/LICENSE-2.0

*

*  Unless required by applicable law or agreed to in writing, software

*  distributed under the License is distributed on an "AS IS" BASIS,

*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

*  See the License for the specific language governing permissions and

*  limitations under the License.

*/

package com.aem.community.core.models;

import javax.annotation.PostConstruct;

import javax.inject.Inject;

import javax.inject.Named;

import org.apache.sling.api.resource.Resource;

import org.apache.sling.models.annotations.Default;

import org.apache.sling.models.annotations.Model;

import org.apache.sling.settings.SlingSettingsService;

import com.aem.community.core.CustDataService;

@Model(adaptables=Resource.class)

public class HelloWorldModel {

    @Inject

    private SlingSettingsService settings;

   

    @Inject

    private CustDataService custSer;

    @Inject @Named("sling:resourceType") @Default(values="No resourceType")

    protected String resourceType;

    private String message;

    @PostConstruct

    protected void init() {

        message = "\tHello World!\n";

        message += "\tThis is instance: " + settings.getSlingId() + "\n";

       message += "\tNumber of Customer Records: " + custSer.getTotalCustomers() + "\n";

    }

    public String getMessage() {

        return message;

    }

}

We will get all of this into a HELPX  artilce that we will release early next week.

Avatar

Level 1

Hi Smacdonald,

I have the same issue. Getting datasource object as null.

Getting the below exception message :

Unknown system variable 'language'

Followed all the steps as shown in the video. Still no luck !

Thanks,
Sanketh