Showing posts with label DataSource. Show all posts
Showing posts with label DataSource. Show all posts

April 27, 2020
Estimated Post Reading Time ~

How to connect to oracle database using DataSource pool from OSGi

This post will explain how to connect to oracle database using datasource pool from AEM

Convert the JDBC driver to OSGI bundle: 
In eclipse - File-->New-->Plug-in Development-->Plug-in from Existing JAR Archives
Click on Add External and Select the JDBC jar file

Click Next and enter the required details

Project name - OracleDriver
Plug-in ID - com.jdbc.oracle
Plug-in vendor - Oracle
Select the Execute Environment
Select an OSGi framework and select standard
Un-Select Unzip the JAR archives into the project and select Update references to the JAR files.



Click Next and click Finish

Right click the the created project and click on Export



Select Plug-in Development --> Deploying plug-ins and fragments
Specify the destination directory and make sure the plug-in is selected(com.jdbc.oracle)



Click on Finish, this will create the OSGI bundle in the selected directory.
Install the OSGI bundle:
Login to http://localhost:4502/system/console/bundles
Click on Install/Update
Choose the OSGI bundle
Select Start Bundle and refresh Packages



Click on Install or Update

Configure the Datasource pool:Login to http://localhost:4502/system/console/configMgr

Select JDBC Connection Pool and add new Connection Pool(click on plus)

Enter the required details

JDBC driver class - oracle.jdbc.OracleDriver
JDBC connection URI - jdbc:oracle:thin:@hostname:port:SID or Service Name
Username
Password
Validation query - SELECT 1 FROM DUAL
Pool size - 10(configure based on the requirement)
Datasource name - SampleOracleDS(provide the datasource name to uniquely identify the DS)



Save the configurations

Maven dependency:

<dependency>
<groupId>com.day.commons</groupId>
<artifactId>day.commons.datasource.poolservice</artifactId>
<version>1.0.10</version>
<scope>provided</scope>
</dependency>

Service class to get the database connection and to perform the operations:

package com.tr.commerce.connector.common;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

@Component(immediate = true, metatype = true)
@Service(value = DatabaseConnectionImpl.class)
public class DatabaseConnectionImpl {

protected static final Logger log = LoggerFactory.getLogger(DatabaseConnectionImpl.class);

@Reference
private DataSourcePool dataSourceService;

public Connection getDataBaseConnection(String dataSourceName) {
Connection conn = null;
try {
DataSource dataSource = (DataSource) dataSourceService.getDataSource(dataSourceName);
conn = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}

public void executeQuery() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = getDataBaseConnection("SampleOracleDS");
stmt = con.createStatement();
rs = stmt.executeQuery("select empno,empname from Employee");
while (rs.next()) {
System.out.println("Employee ID=" + rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

}


By aem4beginner

April 26, 2020
Estimated Post Reading Time ~

How to get the currentPage URL in cq:dialog dropdown datasources?

In Touch UI dialog's, the dynamic dropdown list is loaded through data sources, sometime we may need to get the current page URL from where the dialog is opened to load the dropdown list data.

String path= request.getParameter("item");

Returns the content path with out jcr:content, e.g /content/test/en/home

String path = (String) request.getAttribute(com.adobe.granite.ui.components.Value.CONTENTPATH_ATTRIBUTE);

Returns the path with jcr:content, e.g /content/test/en/home/jcr:content

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedHashMap;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.felix.scr.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;


import org.apache.sling.api.wrappers.ValueMapDecorator;
import com.adobe.granite.ui.components.ds.DataSource;
import com.adobe.granite.ui.components.ds.SimpleDataSource;
import com.adobe.granite.ui.components.ds.ValueMapResource;


import com.adobe.granite.ui.components.Value;
import org.apache.sling.api.resource.ResourceMetadata;;

@Service(value = Servlet.class)
@Component(metatype = true)
@Properties({
@Property(name = "sling.servlet.resourceTypes", value = "/services/availableCountryDataSource1"),
@Property(name = "service.description", value = "Get country list"),
@Property(name = "label", value = "countryList") })

public class AvailableCountryDataSource extends SlingSafeMethodsServlet {

@Reference
private ResourceResolverFactory resolverFactory;

private static final long serialVersionUID = 1180258251365536303L;

private static final Logger log = LoggerFactory.getLogger(AvailableCountryDataSource.class);
protected void doGet(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException {

final Map<String, String> countriesdata = new LinkedHashMap<String, String>();
Map<String, Object> param = new HashMap<String, Object>();
param.put(ResourceResolverFactory.SUBSERVICE, "Albin");
ResourceResolver resourceResolver=null;
try{

ArrayList<Resource> countryList = new ArrayList<Resource>();

ValueMap valueMap = new ValueMapDecorator(new HashMap<String, Object>());
ValueMap properties =null;

String resourcePath =(String)request.getAttribute(Value.CONTENTPATH_ATTRIBUTE);
resourceResolver = resolverFactory.getServiceResourceResolver(param);
Resource resource = resourceResolver.getResource(resourcePath);
properties=resource.adaptTo(ValueMap.class);

String data = properties.get("countryList", (String) null);

if(data != null ){
log.error("INSIDE IF");
ValueMap vm =null;
for(String country : data.split(",")){

String[] tokens = country.split(";");
if(tokens == null || tokens.length != 2){
continue;
}
vm = new ValueMapDecorator(new HashMap<String, Object>());
vm.put("value", tokens[0] );
vm.put("text", tokens[1]);

countryList.add(new ValueMapResource(request.getResourceResolver(),new ResourceMetadata(), "nt:unstructured", vm));
}

}
DataSource dataSource = new SimpleDataSource(countryList.iterator());
log.debug("dataSource...");
request.setAttribute(DataSource.class.getName(), dataSource);

}catch(Exception e){
log.error("Error while retrieving countries.",e);
}
finally{
if(resourceResolver!=null){
resourceResolver.close();
}
}

}
}




By aem4beginner

April 13, 2020
Estimated Post Reading Time ~

Using Granite DataSource objects to populate AEM Touch UI objects

You can create an Adobe Experience Manager (AEM) 6 Touch UI component that contains drop-down controls that can be used within the AEM Touch UI view. A drop-down control can be populated by using a com.adobe.granite.ui.components.ds.DataSourceobject. For information, see DataSource.
Once you create a DataSource object, its data can be used to dynamically populate a drop-down control, as shown in this illustration.



This article modifies the Hero Touch UI component that was created by following this AEM community article:
Creating your first Adobe Experience Manager Touch UI component
Before you read this article, its is strongly recommended that you create the Hero Touch UI component by following the article listed here.


By aem4beginner

Create Mobile Applications for Data Services 4.6

Now you can view and interact with your mission critical enterprise data in any location at any time! That is right, you can create mobile applications for Data Services 4.6. For example, you can create a mobile application for a tablet that lets you view and interact with your enterprise data. The following illustration shows the supported clients for Data Services 4.6.
You use the AIR client-side API to create the mobile application as well as Flash Builder 4.6. You use the Java API to create server-side classes that retrieve financial data from a content provider and sends messages to a server destination. When the mobile application detects new messages, the application is updated in real time with financial data.

For example, assume that the mobile application tracks multiple stocks. When the server retrieves updated data from the financial content provider, it creates an updated message and pushes the message to the destination. The mobile application detects the new message and displays changes to the stock price.
The following illustration shows the mobile application that is created. Notice that this application is able to track multiple stock prices. When the user clicks on a row in the grid control, more detailed information is displayed in the mobile application. For example, you can view the stock price during the past five years in an Area control.

To create this mobile application by using Data Services 4.6, then click on the following link to read the full article: Creating Mobile Applications using Data Services 4.6 Message service.


By aem4beginner

Using Granite DataSource objects to populate Experience Manager 6.2 Touch UI Select objects

You can create an Adobe Experience Manager (AEM) 6.2 Touch UI component that contains a drop-down control that can be used within the AEM Touch UI view. An AEM author selects drop-down values during design time. For example, an author can select a USA state value from an AEM component that displays address information. A drop-down control is populated by using a com.adobe.granite.ui.components.ds.DataSource object. For information, see DataSource.

Once you create a DataSource object, its data can be used to dynamically populate a drop-down control, as shown in this illustration.


This development article steps you through how to build an AEM 6.2 HTL component by using an AEM Maven Archetype 10 project. Then it discusses how to populate a drop-down field in the component's dialog using a DataSource object.

To read this development article- click https://helpx.adobe.com/experience-manager/using/aem62_datasource.html.


By aem4beginner

Datastore garbage collection

My instance had 12GB datastore

$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda5 169G 73G 88G 46% /
none 5.9G 672K 5.9G 1% /dev
none 5.9G 196K 5.9G 1% /dev/shm
none 5.9G 104K 5.9G 1% /var/run
none 5.9G 0 5.9G 0% /var/lock
/dev/sda2 98G 12G 81G 13% /mnt/datastore


I ran datastore garbage collection, which ran for 5 hours. and it's now 2GB:
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda5 169G 73G 88G 46% /
none 5.9G 672K 5.9G 1% /dev
none 5.9G 296K 5.9G 1% /dev/shm
none 5.9G 108K 5.9G 1% /var/run
none 5.9G 0 5.9G 0% /var/lock
/dev/sda2 98G 2.0G 91G 3% /mnt/datastore


I have datastore out of crx-quickstart on a different drive for easy back up.. etc.
<DataStore class="com.day.crx.core.data.ClusterDataStore">
<param name="path" value="/mnt/datastore"/>
</DataStore>

The script for running datastore garbage collection is here:

#!/bin/bash

if (( $# < 1))
then
echo "Usage: $0 host:port"
echo "example"
echo " $0 localhost:4502 < admin-password.txt"
exit 1
fi

h="$1"
user="admin"
workspace="crx.default"
read -s -p "password for admin> " password
cookie=$(tempfile --suffix=".cookie")

echo "logging in to $workspace as $user"
curl -f -s -c "$cookie" \
-F"_charset_=UTF-8" \
-F"UserId=$user" \
-F"Password=$password" \
-F"Workspace=$workspace" "http://$h/crx/login.jsp" &&
echo "got cookie: $cookie" &&
curl -f -s -b "$cookie" \
-F"memGc=checked" \
-F"delete=checked" \
-F"pmScan=checked" \
-F"sleep=10" \
-F"action=run" "http://$h/crx/config/datastore_gc.jsp"


By aem4beginner

April 7, 2020
Estimated Post Reading Time ~

Implement DataSource for drop down using Sightly AEM 6.1



In the Touch UI component, DataSource is very useful when it comes to populating dropdown dynamically. This article will help you to understand how datasource can be used with Sightly and leaving JSP behind.

Let’s get started with authoring…


The component contains a simple drop-down, values for this will be populated dynamically using DataSource.

Here is the code used…

1. DataSource is present at /apps/sightlydatasource/components/content/sample-ds

<sly data-sly-use.data="com.sightlydatasource.core.sightly.SightlyDataSourceExample"> </sly>
It simply calls the Java class which act as DataSource

2. com.sightlydatasource.core.sightly.SightlyDataSourceExample

package com.sightlydatasource.core.sightly;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.ValueMapDecorator;

import com.adobe.cq.sightly.WCMUse;
import com.adobe.granite.ui.components.ds.DataSource;
import com.adobe.granite.ui.components.ds.SimpleDataSource;
import com.adobe.granite.ui.components.ds.ValueMapResource;

/**
* Sightly class act as a data source returning dynamic data.
*
* @author Praveen
*/
public class SightlyDataSourceExample extends WCMUse {
@Override
public void activate() throws Exception {
ResourceResolver resolver = getResource().getResourceResolver();

// Create an ArrayList to hold data
List < Resource > resourceList = new ArrayList < Resource > ();

ValueMap vm = null;

for (int i = 1; i <= 5; i++) {
vm = new ValueMapDecorator(new HashMap < String, Object > ());
String Value = "samplevalue" + i;
String Text = "Sample Text " + i;
vm.put("value", Value);
vm.put("text", Text);

resourceList.add(new ValueMapResource(resolver,
new ResourceMetadata(), "nt:unstructured", vm));
}

// Create a DataSource that is used to populate the drop-down control
DataSource ds = new SimpleDataSource(resourceList.iterator());
this.getRequest().setAttribute(DataSource.class.getName(), ds);
}

Line 45: Create a new SimpleDataDource object and pass the iterator of our list which contains data.

Here is the AEM Helpx article which shows the same in JSP


By aem4beginner