Sunday, May 31, 2015

org.springframework.a op.framework.AopConfigException: Could not generate CGLIB subclass of class [class net.sf.ehcache.CacheManager]

org.springframework.a op.framework.AopConfigException: Could not generate CGLIB subclass of class [class net.sf.ehcache.CacheManager]

While using Ehcache with spring, spring context initialization fails with the below exception

Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
ng bean with name 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceI
mpl#0': Cannot resolve reference to bean 'ehcacheManager' while setting bean pro
perty 'cacheManager'; nested exception is org.springframework.beans.factory.Bean
CreationException: Error creating bean with name 'ehcacheManager': Post-processi
ng of the FactoryBean's object failed; nested exception is org.springframework.a
op.framework.AopConfigException: Could not generate CGLIB subclass of class [cla
ss net.sf.ehcache.CacheManager]: Common causes of this problem include using a f
inal class or a non-visible class; nested exception is org.springframework.cglib
.core.CodeGenerationException: net.sf.ehcache.CacheException-->Another unnamed C
acheManager already exists in the same VM. Please provide unique names for each
CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same Cac
heManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: InputStreamConfigurationSource [stre
am=java.io.BufferedInputStream@128647a]

Configuration Details:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
     xsi:schemaLocation="
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<ehcache:annotation-driven cache-manager="cacheManager"/>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  <property name="configLocation" value="classpath:config/ehcache/ehcache.xml" />
  <property name="shared" value="true" />
</bean>
</beans>

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

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

Friday, May 8, 2015

Removing the Cookie is not working in IE10 and IE11

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:


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

Thursday, May 7, 2015

Enabling Multi Site supports in Adobe Experience Manager(AEM) through Dispatcher and publisher configurations

Enabling Multi Site supports in Adobe Experience Manager(AEM) through Dispatcher and publisher configurations

Invalidate dispatcher cache after successfull jenkins build - AEM/Adobe CQ5

Invalidate dispatcher cache after successful Jenkins build - AEM/Adobe CQ5

This post will explain how to invalidate the cache in Adobe Experience Manager after successful Jenkins build.

Login to Jenkins console
Open the job and click on configuration
Add post-build step of type  “Execute Shell” and select “Run only if build succeeds”


Enter the below script and click on  - Change the dispatcher host name accordingly.

/usr/bin/curl -H "CQ-Action: DELETE" -H "CQ-Handle:/" -H "Content-Length: 0" -H "Content-Type: application/octet-stream" --noproxy .com http://<<dispatcher host name>>/dispatcher/invalidate.cache


If multiple dispatcher are configured then configure the dispatchers as shown below in the script.

/usr/bin/curl -H "CQ-Action: DELETE" -H "CQ-Handle:/" -H "Content-Length: 0" -H "Content-Type: application/octet-stream" --noproxy .com http://{dispatcher1, dispatcher2, dispatcher3, dispatcher4}.com/dispatcher/invalidate.cache