Saturday, May 23, 2015

How to get all the configurations from a configurationFactory - Adobe CQ5/Adobe AEM

How to get all the configurations from a configurationFactory - Adobe CQ5/Adobe AEM

@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.STATIC)
private ConfigurationAdmin configAdmin;


try {
Configuration[] confArray = configAdmin.listConfigurations("(service.factoryPid= com.service.config.impl.ConfigFactoryServiceImpl)");

//Retrieve the configurations - Iterate through confArray
final Configuration conf = confArray[0];
final String property1 = (String) conf.getProperties().get("property1");

} catch (Exception e) {

}

service.factoryPid:



Adobe CQ/Adobe AEM: Configuration Services for Multiple Sites through configurationFactory

Adobe CQ/Adobe AEM: Configuration Services for Multiple Sites through configurationFactory

Sometimes, we have to define configuration services that will differ only with configuration values. For e.g we will have different sites that will use the same configuration service but with different configuration values specific to sites.

In this scenario, we have to create a site specific configuration service for all the sites (multiple services) but OSGI provides the concept of ServiceFactories, the service factory can be used to create configuration services with same set of properties and different values.

As an example let’s assume, we have two different sites that will use the same configuration service but require site specific configuration values. The configurationFactory can be used to create configuration service for different sites.

configurationFactory to create site specific cconfigurations and to retrieve the site specific configuration properties.


import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(configurationFactory = true, policy = ConfigurationPolicy.REQUIRE, immediate = true, label = "Config Factory Service", description = "Global configuration Factory Service", metatype = true)
@Properties({ @Property(name = Constants.SERVICE_DESCRIPTION, value = "Common Configuration Factory Service") })
@Service(value = ConfigFactoryServiceImpl.class)
public class ConfigFactoryServiceImpl{

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

private static ResourceResolverFactory resourceResolverFactory;
private static BundleContext bundleContext;

@Reference
private ResourceResolverFactory resourceResolverFactoryInit;

private static final String SERVICE_PID = "service.pid";

private static final String DEFAULT_CONFIG = "DEFAULT";

private static Map<String, String> svcPIDMap = new HashMap<String, String>();

@Property(label = "Site Root Path", value = "DEFAULT", description = "Root path for site (e.g. - /content/sample).")
public static final String SITE_ROOT_PATH = "siteRootPath";

@Property(label = "Property1", value = "Property1: ", description = "Property1.")
public static final String PROPERTY1 = "PROPERTY1";

@Property(label = "Property2", value = "Property2: ", description = "Property2.")
public static final String PROPERTY2 = "PROPERTY2";

@Property(label = "Property3", value = "Property3: ", description = "Property3.")
public static final String PROPERTY3 = "PROPERTY3";

protected String getSiteRootPath() {
return SITE_ROOT_PATH;
}

protected void activate(ComponentContext context) {
try {
bundleContext = context.getBundleContext();
resourceResolverFactory = resourceResolverFactoryInit;
// Get the current config
Dictionary<?, ?> props = context.getProperties();
// Save the service.pid to static map
String servicePID = (String) props.get(SERVICE_PID);
setServicePID(props, servicePID);
} catch (Exception e) {

}
}

private void setServicePID(Dictionary<?, ?> props, String servicePID) {
String siteRootPath = (String) props.get(getSiteRootPath());
if(!siteRootPath.equals("DEFAULT") && !siteRootPath.startsWith("/"))
{
siteRootPath="/"+siteRootPath;
}
if (!StringUtils.isEmpty(siteRootPath)) {
svcPIDMap.put(siteRootPath, servicePID);
}
}

public static String getConfig(HttpServletRequest request, String key) {
return getConfig(request, null, key);
}

public static String getConfig(HttpServletRequest request, String uri,String key) {
String property = null;
Object configObj = null;
try {
configObj = getConfigObj(request, uri, key);
} catch (Exception e) {

}
if (null != configObj) {
property = configObj.toString();
}
return property;
}

public static Object getConfigObj(HttpServletRequest request,String pagePath, String key) {
Configuration conf;
String resourcePath = null;
try {
if (!("DEFAULT").equals(pagePath)) {
resourcePath = getResourcePath(request, pagePath);
conf = locateConfiguration(resourcePath);
} else {
conf = locateConfiguration(DEFAULT_CONFIG);
}

if (null != conf && null != conf.getProperties()) {
Object obj = conf.getProperties().get(key);
return obj;
} else {
throw new Exception("Could not find matching configuration");
}
} catch (Exception e) {

}
return null;
}

private static Configuration locateConfiguration(String resourcePath) {
Configuration locatedConfig = null;
try {
String siteRootPath = getSiteRootPath(resourcePath);
String svcPID = svcPIDMap.get(siteRootPath);
ConfigurationAdmin bundleConfigAdmin = (ConfigurationAdmin) bundleContext.
getService(bundleContext.getServiceReference(ConfigurationAdmin.class.getName()));
locatedConfig = bundleConfigAdmin.getConfiguration(svcPID);
} catch (Exception e) {

}
return locatedConfig;
}

protected static String getResourcePath(HttpServletRequest request,String pagePath) {
String resourcePath = null;
String uri = request.getRequestURI();
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory.getResourceResolver(null);
Resource resolvedResource;
if (null == pagePath) {
resolvedResource = resourceResolver.resolve(request, uri);
} else {
resolvedResource = resourceResolver.resolve(request, pagePath);
}
resourcePath = resolvedResource.getPath();
} catch (Exception e) {

} finally {
if (null != resourceResolver) {
resourceResolver.close();
}
}

return resourcePath;
}

protected static String getSiteRootPath(String resourcePath) {
if (StringUtils.isEmpty(resourcePath)) {
return null;
}

if (resourcePath.equalsIgnoreCase(DEFAULT_CONFIG)) {
return resourcePath;
}

String siteRootPath = null;
String[] path = resourcePath.split("/");
if (path.length > 2) {
siteRootPath = "/" + path[1] + "/" + path[2];
LOG.error("siteRootPath= "+siteRootPath);
}

return siteRootPath;
}
}

After deploying the factory service, create the configuration for different sites e.g. /content/Sample1 and /content/Sample2) and also one for DEFAULT configuration by specifying the value for siteRootPath





Retrieving the properties:

String property1 = ConfigFactoryServiceImpl.getConfig(request, ConfigFactoryServiceImpl.PROPERTY1);

If we are using this in Sample1 site, the property1 specific to Sample1 site will be return.


If we are using this in Sample2 site, the property1 specific to the Sample2 site will be return.


Retrieving the properties by specifying the path:

For e.g to retrieve the properties from DEFAULT configuration

String property1 = ConfigFactoryServiceImpl.getConfig(request,”DEFAULT”, ConfigFactoryServiceImpl.PROPERTY1);



Retrieve site specific properties.

String property1 = ConfigFactoryServiceImpl.getConfig(request,”/content/Sample1”, ConfigFactoryServiceImpl.PROPERTY1);

Friday, May 22, 2015

how to Delete/Disable the users through Java API in Adobe CQ5

This post will explain how to Delete/Disable the users through Java API in Adobe CQ5.

 @Reference
 ResourceResolverFactory resolverFactory;

 ResourceResolver adminResolver = null;
 Session adminSession=null;

 try {  
adminResolver = resolverFactory.getAdministrativeResourceResolver(null);
        adminSession = adminResolver.adaptTo(Session.class);
        final UserManager userManager= adminResolver.adaptTo(UserManager.class);
             
      Authorizable authorizable = userManager.getAuthorizable("userName");
      if (authorizable instanceof User) {
         User user = (User)authorizable;
         user.remove(); //Remove the user

        user.disable() // Disable the user.
    }
                       
 } catch (Exception e) {
e.printStackTrace();
 } finally {
        if (adminResolver != null) adminResolver.close();              
 }

Saturday, May 16, 2015

Suppressing the Selection Failure exception in Assign activity – Oracle SOA Suite

This post will explain how to suppress the Selection Failure exception BPEL Assign activity – Oracle SOA Suite
In BPEL Assign activity if the xpath returns empty result then SelectionFailure RuntimeFault will be thrown by the engine.

But some cases we may need to suppress the selectionFailure error while assigning the optional elements.

In my case I have a assign activity that will mapthe elements  input and input1 from inputVariable to result and result1 of outputVariable.


The input2 is optional and somecases input2 element  will not be available in the request payload.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sup="http://xmlns.oracle.com/Application1/SuppressSelectionFailure/SuppressSelectionFailure">
   <soapenv:Header/>
   <soapenv:Body>
      <sup:process>
         <sup:input>?</sup:input>
      </sup:process>
   </soapenv:Body>
</soapenv:Envelope>


While invoking the service I am getting the selectionFailure exception as shown below.

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <env:Fault>
         <faultcode>env:Server</faultcode>
         <faultstring>faultName: {{http://schemas.xmlsoap.org/ws/2003/03/business-process/}selectionFailure}
messageType: {{http://schemas.oracle.com/bpel/extension}RuntimeFaultMessage}</faultstring>
         <faultactor/>
         <detail>
            <exception/>
         </detail>
      </env:Fault>
   </env:Body>
</env:Envelope>

I want to suppress the selectionFailure exception because input2 is a optional element .

The ignoreMissingFromData attribute will help us to suppress the selectionFailure if the target is missing in the copy operation.

<copy bpelx:ignoreMissingFromData="yes|no"/>



Now even though the input1 element is missing in the request the assign activity will not throw the selectionFailure exception instead the empty tag will get assigned to the outputVariable.


The bpelx:insertMissingToData attribute will help us to suppress the selectionFailure if the target is missing in the copy operation.

<copy bpelx:insertMissingToData="yes|no"/>

If the xpath in the copy operations returns empty node for the target then we will be getting exception "The assign activity of the to node query is returning zero node"



Configure the attribute bpelx:insertMissingToData will help us to suppress this error.

 <copy bpelx:insertMissingToData="yes">
        <from variable="inputVariable" part="payload"
              query="/client:process/client:input1"/>
        <to variable="outputVariable" part="payload"
            query="/client:processResponse/client:result1"/>
      </copy>

The runtime will crate the to-spec element if it is missing and assign the source value(used Remove operation to remove the result1 element from outputVariable for testing).



The attributes insertMissingToData and ignoreMissingFromData can be added by righ clicking the copy rules.

Don't support MessageVariable in fromPart - Oracle SOA Suite 11g

Don't support MessageVariable in fromPart -  Oracle SOA Suite 11g:

This error will be thrown while invoking the service with Multipart Message type and the receive activity uses the fromPart to retrieve the parts data and assign to a variables created based on message type or invoke activity uses toPart to assign the data to parts based message type variable.




To resolve this whenever retrieving or assigning values to parts in receive/invoke activity through fromPart or toPart use the element based variables instead using the message type based variable.



Friday, May 15, 2015

window.location.href is not working while clicking on hyper link in IE

I was trying to redirect to a page while clicking on a hyper link with JQuery Ajax and java script windows.location.href

<a id="signout" href="">signOut<a/>

<script>
    $("#signout").click(function(){

                       $.ajax({
                        type : "POST",
                        async: false,
                        url : "/services/logout",                    
                        success : function() {
                                       window.location="/content/test/test.html";
 },
error : function() {
                                       window.location="/content/test/test.html";
}
});
    } );
</script>

This is working perfectly in both Firefox and Chrome but it is not working in IE.

In IE while redirecting the URL is stripped off to /content/test/(test.html got removed while performing the redirect)

The issue can be fixed as below by adding # in href attribute.

<a id="signout" href="#">signOut<a/>

Saturday, May 9, 2015

Removing the Cookie is not working in IE10 and IE11

While trying to remove the cookies in IE10 and IE11 through Java, the cookies are not getting removed in the browser.

The code snippet used to remove the cookie is

Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String cookieName = "SampleCookieName";
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
cookie.setPath("/");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}

The root cause of  the issue is IE10 and IE11 expecting the value for the attribute Expires as 0 not for Max-Age.

Fix for the issue - Use the below code to remove the cookies

Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String cookieName = "SampleCookie";
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
StringBuilder cookieString = new StringBuilder(cookieHeaderName + "=" + "" + "; ");

cookieString.append("Expires=0" + "; ");
cookieString.append("Version=0; ");
cookieString.append("Path=/; ");
cookieString.append("Max-Age=0" + "; ");
//cookieString.append("HttpOnly");

response.addHeader("Set-Cookie", cookieString.toString());
}
}
}

Refer the following blog to set cookies in IE10 and IE11 - cookie-values-are-not-setting-in-ie10-and-ie11

Contact Form

Name

Email *

Message *