Saturday, May 16, 2015

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

Thursday, April 30, 2015

Dispatcher caching issue while displaying the image renditions in Adobe Experience Manager(AEM)

We are using the image renditions to display the images for different devices in Adobe Experience Manager(AEM).

The HTML5 Adaptive image is used as shown below to display the images for different devices.

<img src="/content/dam/Albin/Untitled.jpg" srcset="/content/dam/Albin/Untitled.jpg/jcr:content/renditions/cq5dam.thumbnail.319.319.png 1x,/content/dam/Albin/Untitled.jpg" alt="Sample Image">

/content/dam/Albin/Untitled.jpg - Original image
/content/dam/Albin/Untitled.jpg/jcr:content/renditions/cq5dam.thumbnail.319.319.png - Rendition for 1x devices.

If the image is first accessed from the mobile devices then Untitled.jpg folder is created to cache the renditions image(rendition images will be matched for mobile devices) - /content/dam/Albin/Untitled.jpg/jcr:content/renditions/cq5dam.thumbnail.319.319.png

While the image is getting accessed from desktop browsers then dispatcher will try to return the folder Untitled.jpg as image(/content/dam/Albin/Untitled.jpg - original image will be matched for desktop browsers) so the image link will be broken in browser.

In other hand, if the image is first accessed from desktop browser then dispatcher caches Untitled.jpg as image. The subsequent request to the renditions image will not find the images in dispatcher cache so the image will be retrieved from publisher for rendering(rendition images will not be cached in this scenario as untitled.jpg is created as a image).

 Refer the following post To resolve the issue

https://www.albinsblog.com/2015/04/how-to-use-html5-adaptive-image-in-AdobeCQ5.html

Wednesday, April 29, 2015

How to get the audit level settings of a Composite through Java - Oracle SOA Suite

How to get the audit level settings of a Composite through Java - Oracle SOA Suite

This blog will explain how to get the audit level settings of a Composite through Java in Oracle SOA Suite

import java.util.Hashtable;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import javax.naming.Context;

import oracle.fabric.composite.model.CompositeNameModel;

public class GetCompositeAuditLevel {
    static MBeanServerConnection m_connection = null;

    public static String getCompositeAuditLevel(String compositeName,String version) throws Exception {
        String auditLevel = "";
        String mBeanName = "*:j2eeType=SCAComposite,revision=" + version + ",*,name=\"" + compositeName + "\"";
        Set<ObjectName> mbeans = m_connection.queryNames(new ObjectName(mBeanName), null);
        System.out.println(mbeans);
        ObjectName mbean = (ObjectName)mbeans.iterator().next();
        javax.management.openmbean.CompositeData[] properties =(javax.management.openmbean.CompositeData[])m_connection.getAttribute(mbean,"Properties");
        if (properties.length > 0) {
            for (int i = 0; i < properties.length; i++) {
                CompositeDataSupport cds = (CompositeDataSupport)properties[i];
                if (cds.get("name").equals("auditLevel")) {
                    auditLevel = (String)cds.get("value");
                    break;
                }
                auditLevel = "Inherit";
            }
        }
        if (auditLevel.equals("Inherit")) {
            auditLevel = getSOAINFRAAuditLevel();
        }
        return auditLevel;
    }

    public static String getSOAINFRAAuditLevel() throws Exception {
        String auditLevel = "";
        String mBeanName ="*:*,name=soa-infra,type=SoaInfraConfig,Application=soa-infra";
        Set<ObjectName> mbeans = m_connection.queryNames(new ObjectName(mBeanName), null);
        ObjectName mbean = (ObjectName)mbeans.iterator().next();
        auditLevel = (String)m_connection.getAttribute(mbean, "AuditLevel");
        return auditLevel;
    }


    public static String getDefaultCompositeRevision(String partiitionName,
                                                     String compositeName) throws Exception {
        ObjectName compositeLifeCycleMBean = null;
        Set queryResult = m_connection.queryNames(new ObjectName("*:j2eeType=CompositeLifecycleConfig,*"), null);
        if (!queryResult.isEmpty()) {
            compositeLifeCycleMBean =(ObjectName)queryResult.iterator().next();
        }
        //CompositeDN - DomainName/CompositeName
        String compositeDN = partiitionName + '/' + compositeName;
        String revision = null;
        CompositeData deployedComposite =(CompositeData)m_connection.invoke(compositeLifeCycleMBean, "getDefaultComposite",
                                               new Object[] { compositeDN },
                                               new String[] { String.class.getName() });
        if (deployedComposite != null) {
            CompositeNameModel cm = CompositeNameModel.parseDN((String)deployedComposite.get("DN"));
            revision = cm.getRevision();
        }
        return revision;
    }

    public static MBeanServerConnection getMbeanServerConnection(String host,int port,String userName,
                                                                 String password) throws Exception {
        String jndiroot = "/jndi/";
        MBeanServerConnection m_connection = null;
        try {
            Hashtable jndiProps = new Hashtable();
            jndiProps.put(Context.SECURITY_PRINCIPAL, userName);
            jndiProps.put(Context.SECURITY_CREDENTIALS, password);
            jndiProps.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");

            JMXServiceURL serviceURL =new JMXServiceURL("t3", host, port, jndiroot +"weblogic.management.mbeanservers.runtime");
            JMXConnector m_connector =JMXConnectorFactory.newJMXConnector(serviceURL, jndiProps);
            m_connector.connect();
            m_connection = m_connector.getMBeanServerConnection();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return m_connection;
    }


    public static void main(String[] args) {
        try {
            m_connection =getMbeanServerConnection("localhost", 7001,"weblogic", "welcome1");
            String defaultVersion =getDefaultCompositeRevision("default", "TestComposite");
            String auditLevel=getCompositeAuditLevel("TestComposite", defaultVersion);
             System.out.println("auditLevel:"+auditLevel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Jar files required in the class path:

  • SOA Runtime jars 
  • weblogic.jar

Tuesday, April 28, 2015

Sunday, April 19, 2015

How to send the HTML email using Velocity template in AEM/Adobe CQ5

How to send the HTML email using Velocity template in Adobe CQ5

This post will explain the steps required to send HTML email in Adobe CQ5 using Velocity template.

Configure mail service:

Go to the Felix Console - http://localhost:4502/system/console/configMgr
Search for Day CQ Mail Service
Enter the email server details as shown below and Save the data (Here I am using Gmail server details).


Email Template:

Create the email template as html file and store it in repository - /etc/email/template/emailTemplate.html (change the path accordingly)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <body>
       Hi ${firstName} ${lastName}</br>
       This is the sample mail.
       <ul>
  #foreach( $data in $dataList )
    <li>$data</li>
  #end
       </ul>
    </body>
</html>

Maven dependencies to the POM.xml:

<dependency>
  <groupId>com.day.cq</groupId>
  <artifactId>cq-mailer</artifactId>
  <version>5.4.0</version>
  <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6.2</version>
</dependency>

Import-Package configuration in POM.xml bundle plugin:

        *,
org.apache.xerces.dom;resolution:=optional,org.apache.xerces.parsers;resolution:=optional,
oracle.xml.parser;resolution:=optional, oracle.xml.parser.v2;resolution:=optional,
org.jaxen;resolution:=optional, org.jaxen.jdom;resolution:=optional,
org.apache.xml.resolver;resolution:=optional,org.apache.xml.resolver.helpers;resolution:=optional,
org.apache.xml.resolver.tools;resolution:=optional,org.apache.tools.ant.launch;resolution:=optional,
org.apache.tools.ant.taskdefs.optional;resolution:=optional,org.apache.tools.ant.util.optional;resolution:=optional,
org.apache.avalon.framework.logger;resolution:=optional,sun.misc;resolution:=optional,
sun.rmi.rmic;resolution:=optional,sun.tools.javac;resolution:=optional,org.apache.bsf;resolution:=optional,
org.apache.env;resolution:=optional,org.apache.bcel.classfile;resolution:=optional,kaffe.rmi.rmic;resolution:=optional,
com.sun.jdmk.comm;resolution:=optional,com.sun.tools.javac;resolution:=optional,javax.jms;resolution:=optional,
antlr;resolution:=optional,antlr.collections.impl;resolution:=optional,org.jdom;resolution:=optional,
org.jdom.input;resolution:=optional,org.jdom.output;resolution:=optional,com.werken.xpath;resolution:=optional,
org.apache.tools.ant;resolution:=optional,org.apache.tools.ant.taskdefs;resolution:=optional,
org.apache.log;resolution:=optional,org.apache.log.format;resolution:=optional,org.apache.log.output.io;resolution:=optional,

Saturday, April 18, 2015

Tuesday, April 7, 2015

How to enable SSH X11 forwarding in Linux?

How to enable SSH X11 forwarding in Linux?

The  X11 forwarding from putty using Xming was not working, the DISPLAY variable is not set(echo $DISPLAY) after opening the remote server session in putty(X11 forwarding is enabled in putty and also the display is specified as localhost:0.0)

The actual issue is the X11 forwarding was not enabled in remote linux server.

The following steps can be followed to enable the X11 forwarding in linux server.

Login to linux server through putty

vi /etc/ssh/sshd_config

Enable the following flags

AllowAgentForwarding yes
AllowTcpForwarding yes
X11Forwarding yes

Execute the following commands

service sshd restart

yum -y update xauth
yum -y install xauth

Now you will be able to perform X11 forwarding.

Saturday, April 4, 2015

How to craete/manage the groups and users through Java API in AEM/Adobe CQ5?

How to create/manage the groups and users through Java API in AEM/Adobe CQ5?

This post will explain how to create/manage the groups and users through Java API in Adobe Experience Manager(AEM).

import java.io.IOException;
import java.security.Principal;

import javax.jcr.PropertyType;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.servlet.Servlet;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
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.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service(value = Servlet.class)
@Component(immediate = true, metatype = true)
@Properties({
@Property(name = "sling.servlet.paths", value = "/services/manageGroupsAndUsers"),
@Property(name = "service.description", value = "ManageGroupsAndUsers"),
@Property(name = "label", value = "ManageGroupsAndUsers") })

public class ManageGroupsAndUsers extends SlingAllMethodsServlet{

/**
*
*/
private static final long serialVersionUID = 1L;

@Reference
ResourceResolverFactory resolverFactory;

private static Logger logger = LoggerFactory.getLogger(ModifyCartServlet.class);

protected final void doPost(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws IOException {

String groupName="sampleGroup";
String userName="sampleUser";
String password="sampleUser";

ResourceResolver adminResolver = null;
Session adminSession=null;
try {
      adminResolver = resolverFactory.getAdministrativeResourceResolver(null);
      adminSession = adminResolver.adaptTo(Session.class);
      final UserManager userManager= adminResolver.adaptTo(UserManager.class);
         
     if(null==userManager.getAuthorizable(groupName)){
   
     Group group=userManager.createGroup(groupName,new SimplePrincipal(groupName),"/home/groups/test");
   
     Value value=adminSession.getValueFactory().createValue("Sample Group", PropertyType.STRING);
     group.setProperty("./profile/givenName", value);
   
     value=adminSession.getValueFactory().createValue("Test Group", PropertyType.STRING);
     group.setProperty("./profile/aboutMe", value);
   
     value=adminSession.getValueFactory().createValue("albin@gmail.com", PropertyType.STRING);
     group.setProperty("./profile/email", value);    
         
      }else{
     response.getWriter().write("Group already exist..");
      }
   
     if(userManager.getAuthorizable(userName)==null){
     User user=userManager.createUser(userName, password,new SimplePrincipal(userName),"/home/users/test");
     Value value=adminSession.getValueFactory().createValue("Issac", PropertyType.STRING);
     user.setProperty("./profile/familyName", value);
   
     value=adminSession.getValueFactory().createValue("Albin", PropertyType.STRING);
     user.setProperty("./profile/givenName", value);
   
     value=adminSession.getValueFactory().createValue("Test User", PropertyType.STRING);
     user.setProperty("./profile/aboutMe", value);
   
     value=adminSession.getValueFactory().createValue("albin@gmail.com", PropertyType.STRING);
     user.setProperty("./profile/email", value);    
   
      }else
      {
      response.getWriter().write("User already exist..");
      }
   
   
     Group group = (Group)(userManager.getAuthorizable(groupName));
     group.addMember(userManager.getAuthorizable(userName));
                     
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write("Not able to perform User Management.."+resolverFactory);
} finally {
      if (adminResolver != null) adminResolver.close();
         
}

}

protected final void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws IOException {
doPost(request, response);
}

Friday, April 3, 2015

How to create different renditions for the Image in AEM/Adobe CQ5?

How to create different renditions for the Image in AEM/Adobe CQ5?

While uploading the images to DAM,Adobe Experience Manager(AEM) will create renditions of an image that include different sizes of the same image.This can be helpful when we need to create thumbnails or smaller views of large, high-resolution images.



We can configure the DAM Update Asset workflow to create the different renditions.
  • Login to http://localhost:4502/etc/workflow/models/dam/update_asset.html
  • In the workflow model select the thumbnail creation step and edit, in the process tab of the step we can add custom rendition values.
  • Save the workflow


How to use HTML5 adaptive image in AEM/Adobe CQ5?

How to use HTML5 adaptive image in AEM/Adobe CQ5?

This post will explain how to use HTML5 adaptive image in Adobe Experience Manager(AEM)

The srcset attribute in HTML5 <img> element, allows us to specify different images for varying viewport widths and pixel densities. This allows us to load a larger image for new high resolution devices while displaying lower resolution images for others

<img src="image-src.png" srcset="image-1x.png 1x, image-2x.png 2x,image-3x.png 3x, image-4x.png 4x">

The width also can be specified to select the images.

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="Sample Image">

While uploading the images to DAM, Adobe CQ5 will create renditions of an image that include different sizes of the same image.This can be helpful when we need to create thumbnails or smaller views of large, high-resolution images.


The original or different rendition images can be used in HTML5 Adaptive image to display the images based on pixel density of the device,  browser will serve the image based on the resolution of the client.

<img src="/content/dam/Albin/Untitled.jpg/jcr:content/renditions/original" srcset="/content/dam/Albin/Untitled.jpg/jcr:content/renditions/cq5dam.thumbnail.319.319.png 1x,/content/dam/Albin/Untitled.jpg/jcr:content/renditions/original" alt="Sample Image">

Saturday, March 28, 2015

NullPointerException: currentDesign.getDoctype(currentStyle).toRequest(request) - AEM/Adobe CQ5

NullPointerException:  currentDesign.getDoctype(currentStyle).toRequest(request) - AEM/Adobe CQ5

We were getting the NullpoiterException while accessing the pages in Adobe Experience Manager(AEM)

Caused by: java.lang.NullPointerException
at org.apache.jsp.apps.sample.design.components.pages.pageShell.pageShell_jsp._jspService(pageShell_jsp.java:227)
at org.apache.sling.scripting.jsp.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.apache.sling.scripting.jsp.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:502)
... 117 more

NullpointerException is thrown while getting the Doctype of the page design.

if (currentDesign != null) {
        currentDesign.getDoctype(currentStyle).toRequest(request);
    }

This issue was getting resolved after restarting the server.

After analysis the currentDesign  and currentStyle objects are not null and getDoctype method is throwing NullpoiterException.

The currentStyle  refers to the path (currentStyle.getPath())- /etc/designs/default.

By default /etc/designs/default/jcr:content path will not have cq:doctype property specified.

To resolve the issue we have added the  cq:doctype - html_5 property to /etc/designs/default/jcr:content

doctype_html5

If the property is already available then delete the same and add again.

Sunday, March 22, 2015

How to enable SSL debug tracing in Weblogic Server?

How to enable SSL debug tracing in Weblogic Server?

Add the following start up options to the start up file startWebLogic.cmd/startWebLogic.sh or startManagedWebLogic.cmd/startManagedWebLogic.sh based on which file is used to start the server to enable SSL debug tracing in Weblogic Server.

JAVA_OPTIONS="${JAVA_OPTIONS} -Dweblogic.debug.DebugSecuritySSL=true -Dweblogic.debug.DebugSSL=true -Dweblogic.StdoutDebugEnabled=true -Dweblogic.log.StdoutSeverityLevel=Debug -Dweblogic.log.LogSeverity=Debug"

Invocation of https/SSL service is not working from OSB

Invocation of https/SSL service is not working from OSB

We were trying to install the wildcard certificate to enable the communication from OSB to end system, but the following exception was displayed in the log file and also the communication to the end system is failing even though the certificate installation was successful;

<Jan 23, 2015 10:45:05 PM PST> <Notice> <Security> <localhost> <AdminServer> <[ACTIVE] ExecuteThread: '12' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <bac54c313ca42523:46f5522b:14b61066510:-7ffd-000000000008b798> <1423456801909> <BEA-090898> <Ignoring the trusted CA certificate "CN=*.sample.com,O=Sample,L=Sample,ST=Sample,C=US". The loading of the trusted certificate list raised a certificate parsing exception PKIX: Unsupported OID in the AlgorithmIdentifier object: 1.2.840.113549.1.1.11.> 
After analysis, we found that JSSE flag should be enabled along with Custom Host Name Verification (weblogic.security.utils.SSLWLSWildcardHostnameVerifier) to support wildcard certificate.

ssl_config

 After enabling the JSSE flag, none of the https communication from OSB is working but https communication from BPEL is working fine even with the wildcard certificate(BPEL and OSB is running in the same server).

The following exception is thrown while invoking the https service from OSB.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server</faultcode>
<faultstring>
BEA-380000: General runtime error: java.lang.NullPointerException
</faultstring>
<detail>
<con:fault xmlns:con="http://www.bea.com/wli/sb/context">
<con:errorCode>BEA-380000</con:errorCode>
<con:reason>
General runtime error: java.lang.NullPointerException
</con:reason>
<con:location>
<con:node>RouteToSFDC_SearchService_BS</con:node>
<con:path>request-pipeline</con:path>
</con:location>
</con:fault>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>

This is the internal OSB server issue; the cause of the issue is that the AsyncResponseHandler does not properly register JSSEFilter for JSSE SSL.
The Weblogic patch 11866509 based on the Weblogic server version (this issues is identified in Weblogic server version 10.3.4 and 10.3.5) should be installed to resolve the issue.

Saturday, March 14, 2015

How to get the UserInfo through Java API in AEM/Adobe CQ5

How to get the UserInfo through Java API in AEM/Adobe CQ5

The below Java API helps to get the UserInfo details in Adobe Experience Manager(AEM)
@Reference
ResourceResolverFactory resolverFactory;

ResourceResolver adminResolver = null;
try {
       adminResolver = resolverFactory.getAdministrativeResourceResolver(null);
       final Session adminSession = adminResolver.adaptTo(Session.class);
       final UserManager userManager = adminResolver.adaptTo(UserManager.class);
       final User user = (User) userManager.getAuthorizable(adminSession.getUserID());
         
       logger.info("user.getID().."+user.getID());
       logger.info("user.isAdmin().."+user.isAdmin());
       logger.info("user.getPrincipal().getName().."+user.getPrincipal().getName());

       String lastName=user.getProperty("./profile/familyName")!=null?user.getProperty("./profile/familyName")[0].getString():null;
     String firstName=user.getProperty("./profile/givenName")!=null?user.getProperty("./profile/givenName")[0].getString():null;
     String aboutMe=user.getProperty("./profile/aboutMe")!=null?user.getProperty("./profile/aboutMe")[0].getString():null;
     String email=user.getProperty("./profile/email")!=null?user.getProperty("./profile/email")[0].getString():null;
   
     logger.info("lastName.."+lastName);
     logger.info("firstName.."+firstName);
     logger.info("aboutMe.."+aboutMe);
     logger.info("email.."+email);
         
       Iterator<Group> itr=user.memberOf();
       while(itr.hasNext())
       {
         Group group=(Group)itr.next();
          logger.info("group.getID().."+group.getID());
           logger.info("group.getPrincipal().getName().."+group.getPrincipal().getName());
        }        
                             
} catch (Exception e) {
        e.printStackTrace();
} finally {
       if (adminResolver != null) adminResolver.close();
}

Thursday, March 12, 2015

Browser cookie values are not setting in IE10 and IE11

Browser cookie values are not setting in IE10 and IE11

While trying to set the cookies in IE10 and IE11 through Java, the values are not stetting in the browser.

The code snippet used to set the cookie is

cookie = new javax.servlet.http.Cookie(cookieHeaderName,"Sample Cookie");
cookie.setPath("/");
ookie.setMaxAge(365*24*60*60);
cookie.setSecure(false);
cookie.setVersion(0);
response.addCookie(cookie);

After long struggle we found the issue might be with the value of Expires is not set, IE10 and IE11 expecting the value for Expires and it is not considering the value set in Max-Age.

Fix for the issue - Use the below code to set the cookie value

int expiration = 365*24*60*60;
StringBuilder cookieString = new StringBuilder("TestCookie=Test; ");

DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, expiration);
cookieString.append("Expires=" + df.format(cal.getTime()) + "; ");
//cookieString.append("Domain="+request.getServerName()+"; ");
cookieString.append("Version=0; ");
cookieString.append("Path=/; ");
cookieString.append("Max-Age=" + expiration + "; ");
cookieString.append("HttpOnly");
response.addHeader("Set-Cookie", cookieString.toString());

Sunday, March 8, 2015

How to connect to oracle database using datasource pool from OSGI- Adobe Experience Manager(AEM)

How to connect to oracle database using datasource pool from OSGI- Adobe Experience Manager(AEM)

This post will explain how to connect to oracle database using datasource pool from Adobe Experience Manager(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

osgi_bundle

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.

Tuesday, March 3, 2015

How to Customize/Configure the 404 error handler for multi sites in AEM/Adobe CQ5?

How to Customize/Configure the 404 error handler for multi sites in AEM/Adobe CQ5?

This post will explain how to configure the 404 error handler in multi site scenario for Adobe Experience Manager(AEM) - This will configure different 404 pages for different sites..

If the error handler is configured for first time then copy /libs/sling/servlet/errorhandler to /apps/sling/servlet (create the folder structure before copying )

Modify /apps/sling/servlet/errorhandler/404.jsp file to modify the 404 error handling rules.

<%  
//setting response code as 404
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
try {
    String uri = request.getRequestURI();
         
    if(uri.matches("(/content/Sample/en/)(.*)"))
    {
        pageContext.include("/content/Sample/en/404.html");
    } else if(uri.matches("(/content/Sample/es/)(.*)"))
    {
        pageContext.include("/content/Sample/es/404.html");
    } else if(uri.matches("(/en/)(.*)"))
    {
        pageContext.include("/content/Sample/en/404.html");
    }
    else if(uri.matches("(/es/)(.*)"))
    {
        pageContext.include("/content/Sample/es/404.html");
    } else
    {
        pageContext.include("/content/Sample/en/404.html");
    }

} catch (Exception e) {

%>
        Page Not Found
<%
}

%>

The conditions can be added to handle different sites, if the sites are running on different virtual host names then get the server name from the request
(request.getServerName()) and add the condition based on the server name.

This will redirect the user to site specific 404 pages.

How to find the Email Group Id in Eloqua?

 How to find the Email Group Id in Eloqua? 

This post will explain  how to find the Email Group Id in Eloqua

There will be different approach to find the Email Group id. Here. This post explains the approach used by me.
Use any of the REST client(here i am using Advance Rest Client)

Provide the below URL - https://secure.p03.eloqua.com/API/REST/1.0/assets/email/groups

Select the Http Method as GET

Provide the Authorization header

Authorization: Basic xxxxxxxxxxx

Replace xxxxxxxxxxx with base64 encoded string of companyName\userName:password

Send the request

The response will have all the Email Group id details - id and name of the Emial group can be found in the response.

{
  elements: [2]
  0:  {
         type: "ContactEmailSubscription"
         contactId: "1"
         emailGroup: {
             type: "EmailGroup"
             id: "1"
            depth: "minimal"
            description: ""
            name: "Sample1"
            permissions: "fullControl"
            updatedAt: "1423758721"
           updatedBy: "1"
        }
       isSubscribed: "true"
       updatedAt: "1423219686"
   }
  1:  {
         type: "ContactEmailSubscription"
         contactId: "1"
         emailGroup: {
             type: "EmailGroup"
             id: "2"
            depth: "minimal"
            description: ""
            name: "Sample2"
            permissions: "fullControl"
            updatedAt: "1423758721"
           updatedBy: "1"
        }
       isSubscribed: "true"
       updatedAt: "1423219686"
   }
  page: 1
 pageSize: 1000
 total: 2
}

Sunday, March 1, 2015

How to get the child Pages of a root Page through Java API -AEM/ Adobe CQ5

How to get the child Pages of a root Page through Java API - AEM/Adobe CQ5

This post will explain how to get the child Pages of a root Page through Java API in Adobe Experience Manager(AEM)

public static PageFilter getPageFilter() {
PageFilter pf = new PageFilter();
return pf;
}

public static Iterator<Page> getPageIterator(Page page){
Iterator<Page> children = page. listChildren(getPageFilter());
return children;
}

Filter can be changed to restrict child pages e.g Get the child pages created only with the template "/apps/sample/templates/samplePage"

public static PageFilter getPageFilter() {
PageFilter pf = new PageFilter() {
public boolean includes(Page p) {
ValueMap props = p.getProperties();
String templatePath = props.get("cq:template",String.class);
if("/apps/sample/templates/samplePage".equals(templatePath))
{
return true;
} else
{
return false;
}
}
};
return pf;
}

How to find a Page has child Pages thorough Java API - AEM/Adobe CQ5

How to find a Page has child Pages thorough Java API - AEM/Adobe CQ5

This post will explain how to find a Page has child Pages thorough Java API in Adobe Experience Manager(AEM)

public static boolean hasPageChildren(Page rootPage) {
          boolean isTrue = false;
          if (rootPage != null&& rootPage.listChildren(getPageFilter()).hasNext()) {
       isTrue = true;
          }
        return isTrue;
}

public static PageFilter getPageFilter() {
PageFilter pf = new PageFilter();
return pf;
}

How to get the published date of a page through Java API - Adobe Experience Manager(AEM)

How to get the published date of a page through Java API - Adobe Experience Manager(AEM)

This post will explain how to get the published date of a page through Java API in Adobe Experience Manager(AEM)

public static Date getPublishDate(Page page) {
Date newDate = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd", Locale.getDefault());
if (page != null) {
String publishedDate =  page.getProperties().get("publisheddate", "");
if(!"".equals(publishedDate)){
try {
newDate = sdf.parse(publishedDate);
} catch (ParseException e) {

}
}
}
return newDate;
}

How to send the email through Java API in Eloqua

How to send the email through Java API in Eloqua

This post explains how to send the email through Eloqua API.

Create the required model classes:

public class EmailTestDeployment 

    public String contactId ;
    public String sendFromUserId ;
    public Email email;
    public String name;
    public String type;       

}

public class Email 
{
public int emailGroupId;
public RawHtmlContent htmlContent; 
public int id; 
public boolean isPlainTextEditable; 
public String name; 
public String plainText; 
public boolean sendPlainTextOnly; 
public String subject; 

}

public class RawHtmlContent 
{
    public String type;
    public String html;

}

RestClient class to connect to Eloqua:


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{
    private String authToken;
    private String baseUrl;       
    public RestClient(String user, String password, String url)
    {
       baseUrl = url;             
       String authString = user + ":" + password;
      authToken = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());           
    }             
                          
    public String execute(String uri, String method, String body)  throws Exception
    {
       String response ="";
       try
       {           
          URL url = new URL(baseUrl + uri);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();                         
          conn.setInstanceFollowRedirects(false);
          conn.setRequestMethod(method.toString());
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("Accept", "application/json");
          System.out.println(authToken);
          conn.setRequestProperty("Authorization", authToken);         
                  
          if (method == "POST" || method == "PUT")
          {
              if(null != body){
                  conn.setDoOutput(true);
                  final OutputStream os = conn.getOutputStream();
                  os.write(body.getBytes());
                  os.flush();
                  os.close();
               }
           }
                      
           InputStream is = conn.getInputStream();
           BufferedReader rd = new BufferedReader(new InputStreamReader( is));
           String line; 
           while ((line = rd.readLine()) != null)
           {
               response += line;
           }           
           rd.close();
           conn.disconnect();
         }
         catch (Exception e)
         {
            throw e;
         }
       return response;
      }

}