Tuesday, December 30, 2014

Building a executable JAR file with external libraries through JDeveloper

This post explain the different approaches to build the executable JAR file with external libraries through JDeveloper.

Referring the external libraries from JAR:

Right Click project and select properties
Click on Deployment and create new JAR deployment profile.
Select "Include Manifest File" option.
Select the main class.



Create a manifest file(any location) and add the required jar files to the Class-Path header

Class-Path.mf

Class-Path: json.jar log4j.jar

 End the Class-Path.mf file by a carriage return.


Add the Class-Path.mf file to Additional Manifest Files to Merge into Manifest.mf


Then right click on project select the profile created under deploy. Select Deploy to JAR File.
Click finish.

META-INF\MAIFEST.MF file in the generated file will have the Main-Class and Class-Path headers defined.



Executing the jar:

Place the dependent jars to the same folder where the jar file generated in the previous step exists.


java -jar TokenizerService.jar


Including the content of external libraries to JAR:

Right Click project and select properties
Click on Deployment and create new JAR deployment profile.
Select "Include Manifest File" option.
Select the main class.
Create New File Group of type Dependency Analysis


Select the Contributors under new file group you have created
Select the Libraries Tab.
Select the required libraries  and select the default option "Include Contents in Output".


Then right click on project select the profile created under deploy. Select Deploy to JAR File.
Click finish.
The content of the json.jar file will be included into the generated jar.



Executing the jar:

java -jar TokenizerService.jar



Saturday, December 20, 2014

Encrypting/Decrypting data in Adobe CQ5

com.adobe.granite.crypto.CryptoSupport service can be used to encrypt/decrypt the data in Adobe CQ5.

Add the below dependency in POM.xml

<dependency>
  <groupId>com.adobe.granite</groupId>
        <artifactId>com.adobe.granite.crypto</artifactId>
         <version>0.0.18</version>
         <scope>provided</scope>
 </dependency>

Service to encrypt/decrypt the message:

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;

@Component(immediate = true, metatype = true)
@Service(value = EncrypionService.class)
public class EncrypionService {
@Reference
private CryptoSupport cryptoSupport;

public String encrypt(String plainText) throws Exception
{
try {
return cryptoSupport.protect(plainText);
} catch (CryptoException e) {
throw e;
}
}

public String decrypt(String encryptedText) throws Exception
{
try {
return cryptoSupport.unprotect(encryptedText);
} catch (CryptoException e) {
throw e;
}
}
}




org.apache.sling.engine.impl.SlingRequestProcessorImpl service: Uncaught Throwable java.lang.LinkageError: loader constraint violation - Adobe CQ5

Sometimes we may receive the following exception while invoking the Adobe CQ5 services.

20.12.2014 11:15:31.816 *ERROR* [0:0:0:0:0:0:0:1 [1419054331815] GET /services/EmailServlet HTTP/1.1] org.apache.sling.engine.impl.SlingRequestProcessorImpl service: Uncaught Throwable java.lang.LinkageError: loader consaint violation: when resolving interface method "com..commerce.connector.CommerceService.getSession(Ljavax/servlet/http/HttpServleequest;Ljavax/servlet/http/HttpServleesponse;)Lcom//commerce/connector/session/CommerceSession;" the class loader (instance of org/apache/felix/framework/BundleWiringImpl$BundleClassLoaderJava5) of the current class, com///servlet/EmailServlet, and the class loader (instance of org/apache/felix/framework/BundleWiringImpl$BundleClassLoaderJava5) for resolved class, com//commerce/connector/CommerceService, have different Class objects for the type connector.CommerceService.getSession(Ljavax/servlet/http/HttpServleequest;Ljavax/servlet/http/HttpServleesponse;)Lcom//commerce/connector/session/CommerceSession; used in the signature
at com...servlet.EmailServlet.doPost(EmailServlet.java:67)
at com...servlet.EmailServlet.doGet(EmailServlet.java:56)
at org.apache.sling.api.servlets.SlingSafeMethodsServlet.mayService(SlingSafeMethodsServlet.java:268)
at org.apache.sling.api.servlets.SlingAllMethodsServlet.mayService(SlingAllMethodsServlet.java:139)

This error will be thrown while invoking the service of one bundle from another bundle.

To fix this issue, make sure the required packages from the target bundle is imported to the source bundle.





Thursday, December 18, 2014

org.apache.sling.security.impl.ReferrerFilter Rejected empty referrer header for POST request - Adobe CQ5

We will receive the following exception while testing the Adobe  CQ5 POST Servlets from Restclient.


15.12.2014 22:55:01.434 *INFO* [0:0:0:0:0:0:0:1 [1418664301434] POST /services/EmailServlet HTTP/1.1] org.apache.sling.security.impl.ReferrerFilter Rejected empty 
referrer header for POST request to /services/EmailServlet

This error is is due to the Apache Sling Referrer Filter will not allow empty Referer address by default.

For testing purpose, we can allow empty referrer by changing the Apache Sling Referrer Filter.

Go to the Felix Console - http://localhost:4502/system/console/configMgr
Search for "Apache Sling Referrer Filter"
Select "Allow Empty"


This should be only enabled for testing purpose in dev environment.




Wednesday, December 17, 2014

Sending mail through Java API with Gmail server – Adobe CQ5

This post will explain the steps required to send mail in Adobe CQ5 through Java API with Gmail server.

Configure mail service:

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

SMTP Server Host   - smtp.gmail.com
SMTP Server Port    - 465
SMTP User              - your gmail username
SMTP Password      - your password
From Address          - your email
SMTP Use SSL      - true


You may need to enable the access for less secure apps in google account - https://www.google.com/settings/security/lesssecureapps

Email Template:

Create the email template as text file and store it in repository - /etc/email/template/emailTemplate.txt (change the path accordingly)


Create the Email servlet:

Create a servlet to send the email with the provides details.

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.jcr.Node;
import javax.jcr.Session;
import javax.mail.internet.InternetAddress;
import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.apache.commons.mail.HtmlEmail;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.mailer.MessageGateway;
import com.day.cq.mailer.MessageGatewayService;

@SuppressWarnings({ "serial" })
@Component(metatype = false)
@SlingServlet(name = "EmailServlet", description = "EmailServlet", methods = "POST", generateComponent =false, paths = "/services/EmailServlet")
@Service(Servlet.class)
public class EmailServlet extends SlingAllMethodsServlet {

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

       @Reference
       private MessageGatewayService messageGatewayService;
       @Reference
       public SlingRepository repository;

       @Override
       protected void doGet(SlingHttpServletRequest request,
                     SlingHttpServletResponse response) throws ServletException,
                     IOException {
              doPost(request, response);
       }
   
       @Override
       protected void doPost(SlingHttpServletRequest request,
                     SlingHttpServletResponse response) throws ServletException,
                     IOException {
              String results = sendEmail(request);
              if (results != null && results.equalsIgnoreCase("success")) {
                     response.getWriter().write("success");
              } else {
                     response.getWriter().write("fail");
              }          
       }  

       public String sendEmail(SlingHttpServletRequest request) {

              ArrayList<InternetAddress> emailRecipients = new ArrayList<InternetAddress>();
              Session session = null;
              String results = "Success";
              String fromAddress=request.getParameter("fromAddress");
              String toAddress=request.getParameter("toAddress");
           
              String firstName=request.getParameter("firstName");
              String lastName=request.getParameter("lastName");
           
              String templateLink=request.getParameter("templateLink");
           
              try {
                     session = repository.loginAdministrative(null);
                     String templateReference = templateLink.substring(1)+ "/jcr:content";

                     Node root = session.getRootNode();
                     Node jcrContent = root.getNode(templateReference);
                     InputStream is = jcrContent.getProperty("jcr:data").getBinary().getStream();

                     BufferedInputStream bis = new BufferedInputStream(is);
                     ByteArrayOutputStream buf = new ByteArrayOutputStream();
                     int resultNumber = bis.read();
                     while (resultNumber != -1) {
                           byte b = (byte) resultNumber;
                           buf.write(b);
                           resultNumber = bis.read();
                     }                

                     String bufString = buf.toString();
                     LOG.info("template.."+bufString);
                     bufString = bufString.replace("${firstName}", firstName);
                     bufString = bufString.replace("${lastName}", lastName);
                     LOG.info("mesage.."+bufString);
                     HtmlEmail email = new HtmlEmail();
                 
                     emailRecipients.add(new InternetAddress(toAddress));
                     email.setCharset("UTF-8");
                     email.setFrom(fromAddress);
                     email.setTo(emailRecipients);
                     email.setSubject("This is the test mail");
                     email.setHtmlMsg(bufString);
                     MessageGateway<HtmlEmail> messageGateway = this.messageGatewayService.getGateway(HtmlEmail.class);
                     messageGateway.send(email);
                     emailRecipients.clear();                    
                 
              } catch (Exception e) {
                     results = "fail";
                     LOG.info("e.getMessage"+e.getMessage());
                     e.printStackTrace();
              } finally {
                     if(session != null) {
                           session.logout();
                     }
              }
              return results;
       }
}

The email can be send now by invoking the servlet with required details.

fromAddress=albinsharp@gmail.com
toAddress=albin.issac@tcs.com
firstName=Albin
lastName=Issac
templateLink=/etc/email/template/emailTemplate.txt



Sunday, December 14, 2014

Programmatically create a page in Adobe CQ5

This post will explain how to create a page programmatically in Adobe CQ5

Create the service to create the page.

import javax.jcr.Node;
import javax.jcr.Session;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.ComponentContext;

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;

@Component(immediate = true, label = "Create Page Service", description = "Create Sample Page", metatype = true)
@Service(value = CreateSamplePage.class )
public class CreateSamplePage   {

@Reference
private ResourceResolverFactory resolverFactory;
private ResourceResolver resourceResolver;
 
private void createPage() throws Exception {
String path="/content/poc";
String pageName="samplePage";
String pageTitle="Sample Page";
String template="/apps/geometrixx/templates/homepage";
String renderer="geometrixx/components/homepage";

this.resourceResolver = this.resolverFactory.getAdministrativeResourceResolver(null);
    Page prodPage = null;
    Session session = this.resourceResolver.adaptTo(Session.class);
    try {
    if (session != null) {

    // Create Page    
    PageManager pageManager = this.resourceResolver.adaptTo(PageManager.class);
    prodPage = pageManager.create(path, pageName, template, pageTitle);
    Node pageNode = prodPage.adaptTo(Node.class);

Node jcrNode = null;
if (prodPage.hasContent()) {
jcrNode = prodPage.getContentResource().adaptTo(Node.class);
} else {                
jcrNode = pageNode.addNode("jcr:content", "cq:PageContent");
}
          jcrNode.setProperty("sling:resourceType", renderer);
     
     
         Node parNode = jcrNode.addNode("par");
         parNode.setProperty("sling:resourceType", "foundation/components/parsys");

 Node textNode = parNode.addNode("text");
 textNode.setProperty("sling:resourceType", "foundation/components/text");
 textNode.setProperty("textIsRich", "true");
 textNode.setProperty("text", "Test page");

session.save();
        session.refresh(true);
 }
       
} catch (Exception e) {
throw e;

   }    
}







Saturday, December 13, 2014

java.net.ConnectException,Bootstrap to server failed while deploying the compoite - Orace SOA Suite

Sometimes we may receive the following exception while deploying the composite to Oracle SOA Suite server using even though the sever is running fine and reachable.

oracle.rc.asadapter.connection.ConnectionException
at oracle.rc.asadapter.weblogic.connection.spi.Weblogic10JndiProvider.getPresentation(Weblogic10JndiProvider.java:86)

Caused by: javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://127.0.0.1:8000: Bootstrap to localhost/127.0.0.1:8000 failed. It is likely that the remote side declared peer gone on this JVM]
at weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:40)

Caused by: java.net.ConnectException: t3://127.0.0.1:8000: Bootstrap to localhost/127.0.0.1:8000 failed. It is likely that the remote side declared peer gone on this JVM

Caused by: java.rmi.ConnectException: Bootstrap to localhost/127.0.0.1:8000 failed. It is likely that the remote side declared peer gone on this JVM
at weblogic.rjvm.ConnectionManager.bootstrap(ConnectionManager.java:334)


This issue can be resolved by configuring valid machine IP or complete name of the machines, including the domain extension as listen address in weblogic server.


On client side,  enter the host entry for the server in the hosts file -C:\Windows\System32\drivers\etc





Thursday, December 11, 2014

Can not write to the specified destfile - Error while deploying through jenkins

Some times we may receive the following error "Can not write to the specified destfile"  while performing the deployment through Jenkins.


The error is due to the user running the Jenkins(the user installed the Jenkins) is not having the permission to write the content to the specified file.

To fix the issue make the owner of the file/folder to the user running the Jenkins

chown -R jenkins:jenkins hybris

Provide the required permission to the file/folder

chmod 777




Tuesday, December 9, 2014

Implementing Internationalization with i18n in Adobe CQ5

This post will explain how to implement Internationalization with i18n in Adobe CQ5

Create a sling:folder i18n inside apps or apps/<<application>> or inside the components folder based on the scope. e.g. /apps/i18n or apps/myapp/i18n or apps/myapp/global/components/mycomponent/i18n


Create a folder for each language inside 118n folder
Assign mixin to the language folders created in the previous step (e.g. en, ar etc) from crx console mix:language
For the language nodes (e.g. en, ar etc) add String property jcr: language, value = ISO language code (en, es etc)

Create nodes of type sling:MessageEntry for each field label
Add 2 properties sling:key = <keyname> and sling:message = <message>


Save all the changes

Using the i18n keys in JSP:
<%@page session="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@page import="java.util.Locale,java.util.ResourceBundle,com.day.cq.i18n.I18n"%>
<%@include file="/libs/foundation/global.jsp"%>
<cq:setContentBundle/>
<%
final Locale pageLocale = currentPage.getLanguage(false);
final ResourceBundle resourceBundle = slingRequest.getResourceBundle(pageLocale);
I18n i18n = new I18n(resourceBundle);
%>
<%= i18n.get("cartItem") %>



Thursday, December 4, 2014

Invoking the SOAP services from Adobe CQ5

This post will explain how to invoke the SOAP services from Adobe CQ5

Add the  wsimport  plug in to the POM.xml

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>jaxws-maven-plugin</artifactId>
   <version>1.12</version>
   <executions>
      <execution>
         <goals>
            <goal>wsimport</goal>
         </goals>
      </execution>
   </executions>
   <configuration>
      <verbose>true</verbose>
      <args>
         <arg>-B-XautoNameResolution</arg>
      </args>
      <wsdlUrls>
         <wsdlUrl>http://localhost:8080/services/AddressService_1.0.wsdl</wsdlUrl>
      </wsdlUrls>
      <sourceDestDir>src/main/java/</sourceDestDir>
      <packageName>com.ws.address.validation</packageName>
   </configuration>
</plugin>

Change the wsdlurl,sourceDestDir and packageName accordingly.


Execute the generate-source target


This will generate the java code to the specified path.


Invoke the service :

AddressServiceV01_Service service = new AddressServiceV01_Service();
AddressServiceV01 port = service.getAddressServiceV01();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext().put("http://localhost:8080/services/AddressService");
String response = port.method(input);

Change the service and the endpoint accordingly.

Add com.sun.xml.internal.ws.* to sling.properties org.osgi.framework.bootdelegation property.

org.osgi.framework.bootdelegation=com.yourkit.*, ${org.apache.sling.launcher.bootdelegation}, com.sun.xml.internal.ws.*



Contact Form

Name

Email *

Message *