AEM 6.3 DataSourcePool reference annotation is null | Community
Skip to main content
Level 5
Jan 17, 2018 4:05 PM UTC
Solved

AEM 6.3 DataSourcePool reference annotation is null

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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
smacdonald2008
smacdonald2008Accepted solution
Level 10
Jan 18, 2018 5:34 PM UTC

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.

11 replies

New Participant
Feb 2, 2018 4:16 AM UTC

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

Translate
Level 5
Jan 19, 2018 9:08 AM UTC

It worked. Thanks Smacdonald.

Translate
smacdonald2008
smacdonald2008Accepted solution
Level 10
Jan 18, 2018 5:34 PM UTC

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.

Translate
Level 5
Jan 18, 2018 5:25 PM UTC

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

Translate
smacdonald2008
Level 10
Jan 18, 2018 3:53 AM UTC

If needed, we can have a connect session!

Translate
smacdonald2008
Level 10
Jan 18, 2018 2:40 AM UTC

Follow the article here - including placing driver file into OSGi - Scott's Digital Community: Injecting a DataSourcePool Service into an Adobe Experience Manager OSGi bundle

Translate
Level 5
Jan 18, 2018 2:08 AM UTC

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

Translate
smacdonald2008
Level 10
Jan 17, 2018 7:37 PM UTC

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:

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

Translate
smacdonald2008
Level 10
Jan 17, 2018 5:15 PM UTC

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

Translate
smacdonald2008
Level 10
Jan 17, 2018 5:05 PM UTC

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 bundle

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

Translate