Thursday, 8 January 2015

Multi image component using MultiField - AEM 5.6 / 6.0

Create Component


1) In your CRXDE Lite http://localhost:4502/crx/de, create below folder and save changes

                      /apps/imagemultifield

2) Copy the component /libs/foundation/components/logo and paste it in path /apps/imagemultifield

3) Rename /apps/imagemultifield/logo to /apps/imagemultifield/imagemultifield

4) Rename /apps/imagemultifield/imagemultifield/logo.jsp to /apps/imagemultifield/imagemultifield/imagemultifield.jsp

5) Change the following properties of /apps/imagemultifield/imagemultifield

                     componentGroup - My Components
                     jcr:title - Image MultiField Component

6) Add the following to dialog (/apps/imagemultifield/imagemultifield/dialog) xml



<?xml version="1.0" encoding="UTF-8"?>
    jcr:primaryType="cq:Dialog"
    activeTab="{Long}0"
    title="Multi Image"
    xtype="tabpanel">
    <items jcr:primaryType="cq:WidgetCollection">
        <basic
            jcr:primaryType="cq:Widget"
            title="Images"
            xtype="panel">
            <items jcr:primaryType="cq:WidgetCollection">
                <images
                    jcr:primaryType="cq:Widget"
                    border="false"
                    hideLabel="true"
                    name="./images"
                    xtype="imagemultifield">
                    <fieldConfig
                        jcr:primaryType="cq:Widget"
                        border="false"
                        hideLabel="true"
                        layout="form"
                        padding="10px 0 0 100px"
                        xtype="imagemultifieldpanel">
                        <items jcr:primaryType="cq:WidgetCollection">
                            <image
                                jcr:primaryType="cq:Widget"
                                cropParameter="./imageCrop"
                                ddGroups="[media]"
                                fileNameParameter="./imageName"
                                fileReferenceParameter="./imageReference"
                                height="250"
                                mapParameter="./imageMap"
                                name="./image"
                                rotateParameter="./imageRotate"
                                sizeLimit="100"
                                xtype="imagemultifieldsmartimage"/>
                        </items>
                    </fieldConfig>
                </images>
            </items>
        </basic>
    </items>
</jcr:root>



Add JS Logic and Register XTypes


1) Create node /apps/imagemultifield/imagemultifield/clientlib of type cq:ClientLibraryFolder and add the following properties

             categories - String - cq.widgets

2) Create file (type nt:file) /apps/imagemultifield/imagemultifield/clientlib/js.txt and add the following

              imagemultifield.js

3) Create file (type nt:file) /apps/imagemultifield/imagemultifield/clientlib/imagemultifield.js and add the following code




CQ.Ext.ns("ImageMultiField");
 
ImageMultiField.Panel = CQ.Ext.extend(CQ.Ext.Panel, {
    initComponent: function () {
        ImageMultiField.Panel.superclass.initComponent.call(this);
 
        var multifield = this.findParentByType('imagemultifield');
        var image = this.find('xtype', 'imagemultifieldsmartimage')[0];
 
        var imageName = multifield.nextImageName;
 
        if(!imageName){
            imageName = image.name;
 
            if(!imageName){
                imageName = "demo";
            }else if(imageName.indexOf("./") == 0){
                imageName = imageName.substr(2); //get rid of ./
            }
 
            var suffix = multifield.nextImageNum = multifield.nextImageNum + 1;
            imageName = this.name + "/" + imageName + "-" + suffix;
        }
 
        image.name = imageName;
 
        var changeParams = ["cropParameter", "fileNameParameter","fileReferenceParameter",
                                "mapParameter","rotateParameter" ];
 
        CQ.Ext.each(changeParams, function(cItem){
            if(image[cItem]){
                image[cItem] = imageName + "/" +
                    ( image[cItem].indexOf("./") == 0 ? image[cItem].substr(2) : image[cItem]);
            }
        });
 
        CQ.Ext.each(image.imageToolDefs, function(toolDef){
            toolDef.transferFieldName = imageName + toolDef.transferFieldName.substr(1);
            toolDef.transferField.name = toolDef.transferFieldName;
        });
    },
 
    setValue: function (record) {
        var multifield = this.findParentByType('imagemultifield');
        var image = this.find('xtype', 'imagemultifieldsmartimage')[0];
 
        var recCopy = CQ.Util.copyObject(record);
 
        var imagePath = multifield.path + "/" + image.name;
        var imgRec = recCopy.get(image.name);
 
        for(var x in imgRec){
            if(imgRec.hasOwnProperty(x)){
                recCopy.data[x] = imgRec[x];
            }
        }
 
        recCopy.data[this.name.substr(2)] = undefined;
 
        var fileRefParam = image.fileReferenceParameter;
        image.fileReferenceParameter = fileRefParam.substr(fileRefParam.lastIndexOf("/") + 1);
 
        image.processRecord(recCopy, imagePath);
        image.fileReferenceParameter = fileRefParam;
    },
 
    validate: function(){
        return true;
    }
});
 
CQ.Ext.reg("imagemultifieldpanel", ImageMultiField.Panel);
 
ImageMultiField.SmartImage = CQ.Ext.extend(CQ.html5.form.SmartImage, {
    syncFormElements: function() {
        if(!this.fileNameField.getEl().dom){
            return;
        }
 
        ImageMultiField.SmartImage.superclass.syncFormElements.call(this);
    } ,
 
    afterRender: function() {
        ImageMultiField.SmartImage.superclass.afterRender.call(this);
 
        var dialog = this.findParentByType('dialog');
        var target = this.dropTargets[0];
 
        if (dialog && dialog.el && target.highlight) {
            var dialogZIndex = parseInt(dialog.el.getStyle("z-index"), 10);
 
            if (!isNaN(dialogZIndex)) {
                target.highlight.zIndex = dialogZIndex + 1;
            }
        }
 
        var multifield = this.findParentByType('multifield');
        multifield.dropTargets.push(target);
 
        this.dropTargets = undefined;
    }
});
 
CQ.Ext.reg('imagemultifieldsmartimage', ImageMultiField.SmartImage);
 
CQ.Ext.override(CQ.form.SmartImage.ImagePanel, {
    addCanvasClass: function(clazz) {
        var imageCanvas = CQ.Ext.get(this.imageCanvas);
 
        if(imageCanvas){
            imageCanvas.addClass(clazz);
        }
    },
 
    removeCanvasClass: function(clazz) {
        var imageCanvas = CQ.Ext.get(this.imageCanvas);
 
        if(imageCanvas){
            imageCanvas.removeClass(clazz);
        }
    }
});
 
CQ.Ext.override(CQ.form.SmartImage.Tool, {
    processRecord: function(record) {
        var iniValue = record.get(this.transferFieldName);
 
        if(!iniValue && ( this.transferFieldName.indexOf("/") !== -1 )){
            iniValue = record.get(this.transferFieldName.substr(this.transferFieldName.lastIndexOf("/") + 1));
        }
 
        if (iniValue == null) {
            iniValue = "";
        }
 
        this.initialValue = iniValue;
    }
});
 
CQ.Ext.override(CQ.form.MultiField.Item, {
    reorder: function(item) {
        if(item.field && item.field.xtype == "imagemultifieldpanel"){
            var c = this.ownerCt;
            var iIndex = c.items.indexOf(item);
            var tIndex = c.items.indexOf(this);
 
            if(iIndex < tIndex){ //user clicked up
                c.insert(c.items.indexOf(item), this);
                this.getEl().insertBefore(item.getEl());
            }else{//user clicked down
                c.insert(c.items.indexOf(this), item);
                this.getEl().insertAfter(item.getEl());
            }
 
            c.doLayout();
        }else{
            var value = item.field.getValue();
            item.field.setValue(this.field.getValue());
            this.field.setValue(value);
        }
    }
});
 
ImageMultiField.MultiField = CQ.Ext.extend(CQ.form.MultiField , {
    Record: CQ.data.SlingRecord.create([]),
    nextImageNum: 0,
    nextImageName: undefined,
 
    initComponent: function() {
        ImageMultiField.MultiField.superclass.initComponent.call(this);
 
        var imagesOrder = new CQ.Ext.form.Hidden({
            name: this.getName() + "/order"
        });
 
        this.add(imagesOrder);
 
        var dialog = this.findParentByType('dialog');
 
        dialog.on('beforesubmit', function(){
            var imagesInOrder = this.find('xtype','imagemultifieldsmartimage');
            var order = [];
 
            CQ.Ext.each(imagesInOrder , function(image){
                order.push(image.name.substr(image.name.lastIndexOf("/") + 1))
            });
 
            imagesOrder.setValue(JSON.stringify(order));
        },this);
 
        this.dropTargets = [];
    },
 
    addItem: function(value){
        if(!value){
            value = new this.Record({},{});
        }
        ImageMultiField.MultiField.superclass.addItem.call(this, value);
    },
 
    processRecord: function(record, path) {
        if (this.fireEvent('beforeloadcontent', this, record, path) !== false) {
            this.items.each(function(item) {
                if(item.field && item.field.xtype == "imagemultifieldpanel"){
                    this.remove(item, true);
                }
            }, this);
 
            var images = record.get(this.getName());
            this.nextImageNum = 0;
 
            if (images) {
                var oName = this.getName() + "/order";
                var oValue = record.get(oName) ? record.get(oName) : "";
 
                var iNames = JSON.parse(oValue);
                var highNum, val;
 
                CQ.Ext.each(iNames, function(iName){
                    val = parseInt(iName.substr(iName.indexOf("-") + 1));
 
                    if(!highNum || highNum < val){
                        highNum = val;
                    }
 
                    this.nextImageName = this.getName() + "/" + iName;
                    this.addItem(record);
                }, this);
 
                this.nextImageNum = highNum;
            }
 
            this.nextImageName = undefined;
 
            this.fireEvent('loadcontent', this, record, path);
        }
    }
});
 
CQ.Ext.reg('imagemultifield', ImageMultiField.MultiField);

Rendering Images


1) Images created in the CRX using MultiImage componet are rendered using /apps/imagemultifield/imagemultifield/imagemultifield.jsp. Add the following code in jsp
<%@include file="/libs/foundation/global.jsp"%>
 
<%@ page import="java.util.Iterator" %>
<%@ page import="com.day.cq.wcm.foundation.Image" %>
<%@ page import="org.apache.sling.commons.json.JSONArray" %>
 
<%
    Iterator<Resource> children = resource.listChildren();
 
    if(!children.hasNext()){
%>
 
        Click here to add images
 
<%
    }else{
        Resource imagesResource = children.next();
        ValueMap map = imagesResource.adaptTo(ValueMap.class);
        String order = map.get("order", String.class);
 
        Image img = null; String src = null;
        JSONArray array = new JSONArray(order);
 
        for(int i = 0; i < array.length(); i++){
            img = new Image(resource);
            img.setItemName(Image.PN_REFERENCE, "imageReference");
            img.setSuffix(String.valueOf(array.get(i)));
            img.setSelector("img");
 
            src = img.getSrc();
%>
            <img src='<%=src%>'/>
<%
        }
    }
%>




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