Saturday, May 23, 2015

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;
}
}



Friday, May 22, 2015

how to Delete/Disable the users through Java API in Adobe Experience Manager(AEM)

how to Delete/Disable the users through Java API in Adobe Experience Manager(AEM)

This post will explain how to Delete/Disable the users through Java API in Adobe Experience Manager(AEM).

 @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

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>



Don't support MessageVariable in fromPart - Oracle SOA Suite

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

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

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/>