Wednesday, 30 July 2014

How to use SOAP in CQ5 ?



Step 1:

Add below code into pom.xml

<plugin>
    <groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${apache-cxf-version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
<wsdlRoot>${basedir}/src/main/wsdl</wsdlRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/wsdl/helloworld.wsdl</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>

Step 2:

<!-- Axis2 Dependencies -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-adb</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-kernel</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-http</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-local</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.neethi</groupId>
<artifactId>neethi</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.schema</groupId>
<artifactId>XmlSchema</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>stax</groupId>
<artifactId>stax</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>stax</groupId>
<artifactId>stax-api</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.2</version>
</dependency>


Step 3:



Step 4:








How to Convert a jar File into an OSGi Bundle

Step 1:


Start by creating a the jar's manifest file:
Manifest-Version: 1.0
Created-By: myself
Bundle-ManifestVersion: 2
Bundle-Name: JUnit 4.4 bundle
Bundle-Description: Package junit 4.4 in an OSGi bundle
Bundle-Version: 4.4.0
Bundle-ClassPath: .,junit-4.4.jar
Bundle-SymbolicName: org.junit.framework
Export-Package: junit.framework,junit.extensions,org.junit.runner,org.junit,junit.textui


Step 2 :
Create the bundle jar file by running the following command:
jar cvfm junit-4.4-bundle.jar manifest.txt junit-4.4.jar 

Where manifest.txt is the name of the manifest file created above.


Tuesday, 22 July 2014

Render image rendtions dynamically in CQ5 - 2nd method


import java.awt.Dimension;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.commons.ImageHelper;
import com.day.cq.commons.SlingRepositoryException;
import com.day.cq.dam.api.Asset;
import com.day.cq.wcm.commons.AbstractImageServlet;
import com.day.image.Layer;

/**
 * Renders the image dynamically
 * Usage: /content/geometrixx/en/products/circle.thumbnail.500.500.jpg
 */
@Component
@Service
@org.apache.felix.scr.annotations.Properties({
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.resourceTypes", value="sling/servlet/default"),
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.selectors", value={"resize","thumb","thumbnail"}),
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.extensions", value={"jpg", "png", "gif"}),
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.methods", value="GET")
})
public class CustomThumbnailServlet extends AbstractImageServlet {

private static final long serialVersionUID = 1L;
private final Logger log = LoggerFactory.getLogger(this.getClass());

private final String ORIGINAL_PATH = "/jcr:content/renditions/original/jcr:content";
private Dimension DEFAULT_DIMENSION = null;

protected void writeLayer(SlingHttpServletRequest request, SlingHttpServletResponse response, AbstractImageServlet.ImageContext c, Layer layer)
        throws IOException, RepositoryException {

log.error("Calling  writeLayer");

int size = layer.getHeight() * layer.getWidth();
   if (size < 1048576)
   {
     ByteArrayOutputStream out = new ByteArrayOutputStream(size);
     layer.write(getImageType(), getImageQuality(), out);
     byte[] bytes = out.toByteArray();
     response.setContentLength(bytes.length);
     response.getOutputStream().write(bytes);
   }
   else {
     layer.write(getImageType(), getImageQuality(), response.getOutputStream());
   }
}

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException{
Session session = null;
try {
 String[] selectors = request.getRequestPathInfo().getSelectors();
 String extension = request.getRequestPathInfo().getExtension();
 String imagePath = request.getRequestPathInfo().getResourcePath().substring(0, request.getRequestPathInfo().getResourcePath().indexOf("."));

 String type = getImageType(extension);
     if (type == null) {
       response.sendError(404, "Image type not supported");
       return;
     }
     response.setContentType(type);
   
     ImageContext context = new ImageContext(request, type);    
     session = (Session)request.getResourceResolver().adaptTo(Session.class);
   
     Resource resource = context.request.getResourceResolver().getResource(imagePath+"."+extension);
     Asset asset = resource.adaptTo(Asset.class);
   
     Layer layer = ImageHelper.createLayer(session.getNode(imagePath+"."+extension).getSession(), asset.getOriginal().getPath());
         
     DEFAULT_DIMENSION = new Dimension(layer.getWidth(), layer.getHeight());
     int maxHeight = selectors.length > 1 ? Integer.valueOf(selectors[1]).intValue() : (int)DEFAULT_DIMENSION.getHeight();
 int maxWidth = selectors.length > 2 ? Integer.valueOf(selectors[2]).intValue() : (int)DEFAULT_DIMENSION.getWidth();
   
     if (layer != null) {
     layer.resize(maxWidth, maxHeight, true);
         applyDiff(layer, context);
       }    
     writeLayer(request, response, context, layer);
   
} catch (RepositoryException e) {
     throw new SlingRepositoryException(e);
   }finally{
    if(session != null)
    session.logout();
   }
 }

protected Layer createLayer(ImageContext paramImageContext) throws RepositoryException, IOException {
return null;
}

 @Override
 protected String getImageType()
 {
   return "image/png";
 }

 @Override
 protected String getImageType(String ext)
 {
   if ("png".equals(ext))
     return "image/png";
   if ("gif".equals(ext))
     return "image/gif";
   if (("jpg".equals(ext)) || ("jpeg".equals(ext))) {
     return "image/jpg";
   }
   return null;
 }
}

Monday, 21 July 2014

Renders the image dynamically in CQ5


import java.awt.Dimension;
import java.io.IOException;

import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.commons.ImageHelper;
import com.day.image.Layer;

/**
 * Renders the image dynamically
 * Usage: /content/geometrixx/en/products/circle.thumbnail.500.500.jpg
 */
@Component
@Service
@org.apache.felix.scr.annotations.Properties({
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.resourceTypes", value="sling/servlet/default"),
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.selectors", value={"resize","thumb","thumbnail"}),
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.extensions", value={"jpg", "png", "gif"}),
      @org.apache.felix.scr.annotations.Property(name="sling.servlet.methods", value="GET")
})
public class CustomThumbnailServlet extends SlingSafeMethodsServlet {

private static final long serialVersionUID = 1L;
private final Logger log = LoggerFactory.getLogger(this.getClass());

private final String ORIGINAL_PATH = "/jcr:content/renditions/original/jcr:content";
private static final Dimension DEFAULT_DIMENSION = new Dimension(100, 100);

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException{
try {
 String[] selectors = request.getRequestPathInfo().getSelectors();
 String extension = request.getRequestPathInfo().getExtension();
 String imagePath = request.getRequestPathInfo().getResourcePath().substring(0, request.getRequestPathInfo().getResourcePath().indexOf("."));
 int maxHeight = selectors.length > 1 ? Integer.valueOf(selectors[1]).intValue() : (int)DEFAULT_DIMENSION.getHeight();
 int maxWidth = selectors.length > 2 ? Integer.valueOf(selectors[2]).intValue() : (int)DEFAULT_DIMENSION.getWidth();  
 boolean margin = (selectors.length > 3) && (selectors[3].equals("margin"));

 Session session = (Session)request.getResourceResolver().adaptTo(Session.class);
 Node imageNode = session.getNode(imagePath+"."+extension+ORIGINAL_PATH);

 Property data = imageNode.getProperty("jcr:data");
     Layer imageLayer = ImageHelper.createLayer(imageNode.getSession(), imageNode.getPath());
 imageLayer.resize(maxWidth, maxHeight);

 response.setContentLength((int)data.getLength());
 response.setContentType(imageLayer.getMimeType());
 imageLayer.write(imageLayer.getMimeType(), imageLayer.getMimeType().equals("image/gif") ? 255 : 1.0, response.getOutputStream());

} catch (PathNotFoundException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}  
 }
}

Thursday, 17 July 2014

Power shell - Get remote machine service and manage it (start/stop)

$computername = "REMOTE_COMPUTERNAME"
$spadmin = "REMOTE_USERNAME"
$service = "REMOTE_SERVICE_NAME"
$password = convertto-securestring "REMOTE_PASSWORD" -asplaintext -force
Try
{
    $credential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $spadmin, $password
    $session = New-PSSession -Credential $credential -ComputerName $computername
    $param1 = $service
    $returnValue = Invoke-Command -Session $session -ScriptBlock { Param($param1) $status = (get-service $param1 | where {$_.status -eq 'running'});return $status} -ArgumentList $param1
echo $returnValue;
Invoke-Command -Session $session -ScriptBlock { Param($param1) $status = stop-service $param1;return $status} -ArgumentList $param1
$returnValue = Invoke-Command -Session $session -ScriptBlock { Param($param1) $status = (get-service $param1);return $status} -ArgumentList $param1
echo $returnValue;
    Remove-PSSession -Session $session
}
Catch [Exception]
{
     Write-Host $_.Exception.Message
    [Environment]::Exit(1)
}

Tuesday, 15 July 2014

Upload in CQ5

Example:
Type 1)
<form action="http://localhost:4502/content/dam/einstants/*" method="POST" enctype="multipart/form-data"> 
<input name="./jcr:content/renditions/original" type="file"> 
<input name="./jcr:primaryType" value="dam:Asset" type="hidden"> 
<input name="./jcr:content/jcr:primaryType" value="dam:AssetContent" type="hidden"> 
<input name="./jcr:content/renditions/original@TypeHint" value="nt:file" type="hidden"> 
<input name="./jcr:content/metadata/jcr:primaryType" value="nt:unstructured" type="hidden"> 
<input name="./jcr:content/metadata/dc:title" value="Title of the asset" type="hidden"> 
<input type="submit"> 
</form>


Type 2)


 CQ already has Apache Commons FileUploadinstalled, so you decide to use it to handle the file upload.
You write your servlet code and end up with something like this:
// Check that we have a file upload request
final boolean isMultipart = ServletFileUpload.isMultipartContent(request);
PrintWriter out = null;
try {
  out = response.getWriter();
  if (isMultipart) {
    final Map<String, RequestParameter[]> params = request.getRequestParameterMap();
    for (final Map.Entry<String, RequestParameter[]> pairs : params.entrySet()) {
      final String k = pairs.getKey();
      final RequestParameter[] pArr = pairs.getValue();
      final RequestParameter param = pArr[0];
      final InputStream stream = param.getInputStream();
      if (param.isFormField()) {
        out.println("Form field " + k + " with value " + Streams.asString(stream) + " detected.");
      } else {
        out.println("File field " + k + " with file name " + param.getFileName() + " detected.");
      }
    }
  }


Type 3)

<%@page import="javax.jcr.Session"%>
<%@page import="javax.jcr.Node"%>
<%@page import="java.io.ByteArrayInputStream"%>
<%@page import="java.util.Calendar"%>
<%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0"%>
<sling:defineObjects/>
<%// get the root nodeSession 
mySession = slingRequest.getResourceResolver().adaptTo(Session.class);
Node root = mySession.getRootNode();
// create a new node of type nt:fileNode
myNewNode = root.getNode("content").addNode("mynewnode", "nt:file");

Node contentNode = myNewNode.addNode("_jcr_content", "nt:resource");
// set the mandatory properties

contentNode.setProperty("jcr:data", new ByteArrayInputStream(request.getParameter("myfile").getBytes()));
contentNode.setProperty("jcr:lastModified", Calendar.getInstance());
contentNode.setProperty("jcr:mimeType", "mymimetype");

mySession.save();%>

Friday, 20 June 2014

Sling Authentication

Let's look at generic request processing of Sling: Sling is linked into the outside world by registering the Sling Main Servlet – implemented by the SlingMainServlet class in the Sling Engine bundle – with an OSGi HttpService. This registration is accompanyied with an implementation instance of the OSGi HttpContext interface, which defines a method to authenticate requests: handleSecurity.
This method is called by the OSGi HTTP Service implementation after the servlet has been selected to handle the request but before actually calling the servlet's service method.




  1. First the OSGi HTTP Service implementation is analyzing the request URL to find a match for a servlet or resource registered with the HTTP Service.
  2. Now the HTTP Service implementation has to call the handleSecurity method of the HttpContext object with which the servlet or resource has been registered. This method returns true if the request should be serviced. If this method returns false the HTTP Service implementation terminates the request sending back any response which has been prepared by the handleSecurity method. Note, that the handleSecurity method must prepare the failure response sent to the client, the HTTP Service adds nothing here. If the handleSecurity method is successful, it must add two (or three) request attributes described below.
  3. When the handleSecurity method returns true the HTTP Service either calls the Servlet.service method or sends back the requested resource depending on whether a servlet or a resource has been selected in the first step. {column} {section}
The important thing to note here is, that at the time the handleSecurity method is called, the SlingMainServlet is not yet in control of the request. So any functionality added by the SlingMainServlet, notably the SlingHttpServletRequest and SlingHttpServletResponse objects are not available to the implementation of the handleSecurity method.


Deprecation of administrative authentication

Originally the ResourceResolverFactory.getAdministrativeResourceResolver and SlingRepository.loginAdministrative methods have been defined to provide access to the resource tree and JCR Repository. These methods proved to be inappropriate because they allow for much too broad access.
Consequently these methods are being deprecated and will be removed in future releases of the service implementations.
The following methods are deprecated:
  • ResourceResolverFactory.getAdministrativeResourceResolver
  • ResourceProviderFactory.getAdministrativeResourceProvider
  • SlingRepository.loginAdministrative