Wednesday, January 30, 2013

Cross Referencing Text between pages

If you want to reference images on the same page, read this blog entry.

The Problem

You have a range of products with prices that you want to update in several places on your site.

The Solution

1. Create the product/price pair list with a each price pair being a custom component, or a text component.

<TextComponent> Square   $10.00 </TextComponent>
<TextComponent> Triangle   $20.00 </TextComponent>
<TextComponent> Circle   $30.00 </TextComponent>

2. In your target pages, use a Reference component where you would like the price listed.
3. Double click on the reference component
4. Click on the magnifying glass, and navigate to your prices page, and select the price that you want.

Whenever you update the price list, all pages containing the prices will be automatically updated for you.

Bonus Points

You can lock the price page for editing, so that authors won't accidently update your prices across the entire website.

1. Go to the pricing page you have set up
2. Click on the Page tab on the sidebar

3. click on Lock Page
4. The page is now successfully locked so that only you can edit it.

To allow users who have write access to the page to edit again, click on unlock page.

CQ5 - Reference copy of images to reduce download time

The Problem

You have an image that should be exactly the same on different parts of the same page.

The Solution

Copy and Paste the image by reference.

1. Go to the page containing the original image.
2. Highlight the image, and press Ctrl-C to copy
3. Highlight the area where you want to display the second instance of the same image. Press Ctrl-Alt-V to paste as reference.

You will notice that when you update the image content and refresh the page, the same image URL is used.

It is worth noting that you must refresh the page for changes to take effect for referenced image copies.

If you want to cross reference data, read this blog entry.

Setting up GMail as your SMTP server in CQ5

The Problem

You want to set up an SMTP server to let you send mail out of your local instance of CQ5 author.

The Solution

Set up a GMail account (or use your own if you feel comfortable where you are storing the information).

The steps:

1. Go to the Felix Console
2. Scroll down and click to edit the Day CQ Mail Service OSGi config.
3. Enter the following details:
    SMTP Server Host   -
    SMTP Server Port    - 465
    SMTP User              - your username (i.e.
    SMTP Password      - your password
    From Address          - your email
    SMTP Use SSL      - true

4. Hit Save
5. Run a user through a workflow containing a group of which you are a member, or send out a newsletter to a group which you are a part of.

You should receive the email in your inbox.

It is worth noting that for production environments, you should set up a production grade SMTP service rather than use GMail.

Sunday, January 27, 2013

How to restrict activation rights in cq5 to a particular user group

The Problem

You want to prevent a particular user group from having the rights to activate a DAM image and instead require them to follow a publish workflow.

The Solution

1. Log in as administrator.

2. Click on the Users link
3. Double click on the user group you wish to restrict Activate / Deactivate access to.

In this case, we will use content-authors

4. Click on the permissions link
Navigate down to /libs/wcm/core/content/damadmin/tabs/searchpanel/actions/
Unselect Read Access for Activate and Deactivate.

Navigate down to /libs/wcm/core/content/damadmin/actions
Unselect Read Access for Activate and Deactivate.

Next, log in as a user who belongs to only the content-authors group such as author.

Alternately, you can impersonate the user, by clicking on Administrator in the top right hand corner, and selecting author as the user to impersonate. If you accidently select a user without dam rights, have a look at this post.

If you navigate to the dam, you will notice that under this user, the activate and deactivate options are no longer available to this user.

Next, Using a Workflow to publish DAM images through an approval process.

Thursday, January 24, 2013

CQ5 - Gotchya - when impersonating as another user, cannot access admin

The Problem

When impersonating as a user without admin rights, you are immediately locked out of cq5 admin, and cannot log back in, even as an administrator.

The Solution

You need to have read rights to the admin section to be able to log in, even when as an administrator. The cleanest way to get your admin user account back, is to log out, by pasting the following URL into your browser. (Assuming you are on localhost and your port is 4502).


Wednesday, January 23, 2013

How to create a custom multifield component

The Problem

You are trying to capture a list of key/pair values in a custom component in the admin interface.

The Solution

Create a custom multified component to capture values.

1. Create multifield component

1.1 Create the component

The first thing we are going to do is to create a new component for our tutorial project. This component will be visible in the siteadmin editor.

Open up CRXDE and create a new components directory in the following location:

Right click on the apps folder-> New -> Folder. Name this tutorial
Right click on the tutorial folder->New -> Folder. Name this components
Right click on the components folder -> New -> Component

Label -> ConfigComponent
Title -> Config Component
Description -> Key pair configuration component
Super Resource Type -> blank
Group -> Admin (Or whatever group you want this component to live in)

Click on next

in AllowedParents enter

Click on finish.

You have now created your new skeleton component. 

1.2 Create the component display

If you look into the ConfigComponent directory, you will see a ConfigComponent.jsp file.

This jsp will be the component as it renders for display.

In this case, I have decided both for backwards compatibility reasons, and simplicity, to use a table. You can style this in whatever fashion that you desire, however, for the purposes of this tutorial, we will keep it vanilla.

Note, we could also abstract this functionality out into seperate java classes etc, but again, for simplicity, we will just do this in a vanilla fashion.

<%@include file="/libs/foundation/global.jsp"%>Configuration Settings
   PropertyIterator propertyIterator= currentNode.getProperties();
  Property currentProperty=propertyIterator.nextProperty();
  String currentValue="";
  if(currentProperty!=null && 
  currentProperty.getName()!=null && 
  Value[] values=currentProperty.getValues();
  for(Value value:values)
  String[] splitValue=currentValue.split("#");
  for(int splitLoop=0; splitLoop< splitValue.length; splitLoop++)
       %><td><%= splitValue[splitLoop] %></td><%
      %><td><%= currentValue %></td><%

What we are doing in this code, is taking the current node:
PropertyIterator propertyIterator= currentNode.getProperties();

and iterating through its properties.


We then get the values from the property keyvaluepairs, and split the value by the delimitation of a hashtag.

We follow the route of separating values by hashtag, as we wish to avoid having to rewrite the multi-field component entirely. Note that if the # character is a requirement for the field, you can use a multi character delimeter.

1.3 Create the component Dialog

Right click on the ConfigComponent folder -> New Dialog

Name -> dialog
Title -> Key Value Pairs

Click on finish
Navigate down to the tab 1 node, and change the title to Key Value Pairs

Right click on tab1 -> new -> Node
Name -> items
Type -> cq:WidgetCollection

Click Finish

Right click on items -> new -> Node
Name-> trainingmulti 
Type -> cq:Widget

Set the following properties on the trainingmulti node
fieldLabel -> Key Value Pairs
jcr:primaryType -> cq:Widget
name -> ./keyvaluepairs
xtype -> multifield

So what have we done so far? We've created a component that displays a table of values coming from ./keyvaluepairs.

So if we go to our siteadim, open a geometrixx page, and create a template with a parsys such as wide page.

On the sidekick, click on switch to design mode.

Click on edit, scroll down to Admin, or whatever group you've added the component to, and enable the component for inclusion in the sidekick.

If you expand the sidekick again, you should be able to see the component either in Admin section, or the Other section, depending on how many other groups you have enabled.

Add the component to parsys on the left by dragging and dropping it on.

You won't see any key pairs or information at this point in time.

Double click on the component to open the edit dialog.

Click the add button to add a new row, and enter the following:
Test Pair one
Test#Pair two

2. Create custom dual textfields

2.x Hooking in the custom xtype
create  new node on the trainingmulti node of an nt:unstructured type

Add the xtype property of trainingSelection.

Add the xtype component -> list out error

3. Customize display to show read only fields

How to create a custom multifield component.


1. XType component not registered/found

Tuesday, January 22, 2013

gotchya! cq:console has problems with vanitypath

The Problem

You are trying to implement a cq:console mixin to a page component to provide a custom admin interface by using the cq:console mixin, and now the welcome screen no longer renders, as you get the following error:

GET /apps/cq/core/content/welcome.html HTTP/1.1] service: Uncaught SlingException An exception occurred processing JSP page /apps/cq/core/components/welcome/welcome.jsp at line 135

The Solution

What is happening here, is that the sling:vanityPath is failing, as the mixin by default specifies a String[], but the underlying Java component expects sling:vanityPath to be a single String.

Delete the sling:vanityPath variable, and recreate it as just a flat String, rather than an arrayed String[].

Thursday, January 10, 2013

How to write a custom SlingServlet

The Problem(s)

You want to write a custom SlingServlet to render a HTML page, or generate JSON to be consumed by a front end such as a mobile device.

You also want the OSGI bundle to have its settings editable in the Felix Console.

The Solution

So you want to make a configurable OSGI bundle to allow various items to be changed in the Felix Console?

Let's take look at a servlet that reads some settings from the internal config, and replaces any text from a webpage and re-renders the text in the client.

Note, if you are getting code complete issues due to some packages not being recognized by CRXDE, then take a look here to see if it solves your problem.

Step 1 - Create a bundle

Bundles are a set of files with a manifest that CQ5 can install.

Create standard nt:folder to represent your application. In this case, we'll call it SlingServlet.

1. Open up CRXDE Lite. 
2. Right click on the apps folder, click on create folder, and call it SlingServletExample.
3. VERY IMPORTANT: Right click on the SlingServletExample folder and create a folder called install. Note, the install folder should be /apps/SlingServletExample/install. Failure to do so will mean your bundle will not automatically be deployed. See the gotchya below for full details
4. Right click on the SlingServletExample folder, click on new->Create Bundle. Fill in the Symbolic Name and Name to be WebpageTransformer. Type "Transforms webpages" into the description, and give it a package name of org.example.slingservlet.transformer. Click OK.
Congratulations. You've created a bundle. 


Bit of a gotchya here. If you look at the WebpageTransformer.bnd package, you'll see the following two lines:
# Export-Package: *
# Import-Package: *

This is a bit of a nasty one, as to access this bundle from the outside world, you'll need to remove the # from both lines, or else all packages will remain as private only.

For full details, see the gotchya link below.

Step 2 - Create the Transformer Sling Servlet

Right click on the transformer folder, and click New -> Class

Name it TransformerClass, and set superclass to be

Click on Finish.

This example takes a webpage, and transforms a supplied set of text into another set of text.

Here is the full contents.

package org.example.slingservlet.transformer;

import java.rmi.ServerException;
import java.util.Dictionary;

import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.osgi.service.component.ComponentContext;

@SlingServlet(paths="/bin/mySearchServlet", methods = "GET", metatype=true)
@org.apache.felix.scr.annotations.Property(name="PAGE-PROVIDER", description="Page Provider Address", value=""),
@org.apache.felix.scr.annotations.Property(name="SOURCE-TEXT", description="Source Text to Replace", value="Search"),
@org.apache.felix.scr.annotations.Property(name="TARGET-TEXT", description="Target Replacement Text", value="Find of Awesomeness")
public class TransformerClass extends SlingSafeMethodsServlet {
private static final long serialVersionUID = 2598426539166789515L;

public static final String PAGE_PROVIDER="PAGE-PROVIDER";
public static final String SOURCE_TEXT="SOURCE-TEXT";
public static final String TARGET_TEXT="TARGET-TEXT";
private String pageProvider;
private String sourceText;
private String targetText;
private SlingRepository repository;
protected void activate(ComponentContext componentContext){
protected void configure(Dictionary<?, ?> properties) {
this.pageProvider=OsgiUtil.toString(properties.get(PAGE_PROVIDER), null);
this.sourceText=OsgiUtil.toString(properties.get(SOURCE_TEXT), null);
this.targetText=OsgiUtil.toString(properties.get(TARGET_TEXT), null);
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
URL serverAddress=null;
BufferedReader reader=null;
HttpURLConnection internalHttpRequest=null;
PrintWriter responseWriter = response.getWriter();
serverAddress=new URL(pageProvider);
internalHttpRequest = (HttpURLConnection)serverAddress.openConnection();
InputStream in=null;
in = internalHttpRequest.getInputStream();
catch(Exception e)
reader = new BufferedReader(new InputStreamReader(in));
String line=null;
while((line=reader.readLine()) != null)
responseWriter.append(line.replace(sourceText, targetText) + "\n");

Servlet Address
@SlingServlet(paths="/bin/mySearchServlet", methods = "GET", metatype=true)

CQ5 utilises Java Annotations to configure classes.

Here, we are setting the SlingServlet annotation to have 3 values:
paths, methods and metatype.
The paths variable allows you to set the url that will resolve to the slingservlet.

In our case, if you access http://localhost:4502/bin/mySearchServlet, you will be served the servlet, rather than whatever may reside there in the JCR.

Methods specifies a GET method

The metatype option being set to true, instructs CQ5 to provide a config page in the Felix console.

Servlet Properties

The @Properties annotation contains multiple @Property annotations contained in our Sling Servlet.

It is worth noting that if you are using javax.jcr.Property to get a property from a JCR Node, you will have a common namespace conflict with the org.apache.felix.scr.annotations.Property.

I personally think that it's best to use org.apache.felix.scr.annotations.Property as the inline declaration, rather than javax.jcr.Property, as the Property is something that is generally still readable in long format, and won't influence the legibility of your code.

@SlingServlet(paths="/bin/mySearchServlet", methods = "GET", metatype=true)
@org.apache.felix.scr.annotations.Property(name="PAGE-PROVIDER", description="Page Provider Address", value=""),
@org.apache.felix.scr.annotations.Property(name="SOURCE-TEXT", description="Source Text to Replace", value="Search"),
@org.apache.felix.scr.annotations.Property(name="TARGET-TEXT", description="Target Replacement Text", value="Find of Awesomeness")

Here you can see that the individual @Property has a number of values that will be visible via the OSGI console:

Property NamePurpose
nameThe name of the property used as the key to retrieve it later in the configure function
descriptionThe text that is used to describe the property in the OSGi property editor
valueThe default value that should be used for the property in the OSGi console.
*It is worth noting that if you add a subsequent property to a previously configured or saved OSGi console, the default value will not be used. Also, if the default value is changed in code, the default settings will need ot be manually invoked during a deploy, even if the package has been reinstalled.

Each servlet Class is instantiated as a stateless singleton when CQ5 is started, save for any global configuration values. These values need to be loaded from the config when the servlet is activated in the following function:

protected void activate(ComponentContext componentContext){

The activate function is called via the SlingServlet interface (If you know the specific interface, please comment below, short on time to find it right now.) when the Bundle is activated.

The activate function calls our own configure function, which gets a property dictionary.

protected void configure(Dictionary<?, ?> properties) {
this.pageProvider=OsgiUtil.toString(properties.get(PAGE_PROVIDER), null);
this.sourceText=OsgiUtil.toString(properties.get(SOURCE_TEXT), null);
this.targetText=OsgiUtil.toString(properties.get(TARGET_TEXT), null);

Here, we set our private variables with the OsgiUtil.toString function. Note that this class has been deprecated, but as of CQ5.5, I am not aware of a cleaner way of doing this. If you know of one, please comment below.

The final thing you need to know is that you must override the following function:

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {

Note, that you have access to both the request and response, and can do whatever you need it to do.

I shall leave it to the reader to go through my code for the page transformation.

Step 3 - Build the servlet

The first thing to make sure of is that your install folder is in the right place. (read Step 1-3 very carefully. IF YOU DO NOT DO THIS, YOUR COMPONENT WILL NOT AUTOMATICALLY INSTALL DURING BUILD).

Double click on the WebpageTransformer.bnd file, and increment the Bundle Version number. If you do not increment the number, CQ5 may get confused and not automatically deploy your bundle.

When you are happy, right click on the ProviderAssets.bnd file, navigate to the Build sub menu, and click on Build Bundle.

If everything goes well, your bundle should be built and deployed.

Step 4 - Configuring your bundle

Navigate to your felix OSGi console.


Find your WebpageTransformer Bundle in this list. To the right, you should see a pencil icon. If you don't, check your metadata is correct, and contains metatype=true.
@SlingServlet(paths="/bin/mySearchServlet", methods = "GET", metatype=true)

take note of the settings, and make sure that they are default.

Navigate to http://localhost:4502/bin/mySearchServlet

If nothing comes up, you may need to change Apache Sling Servlet/Script Resolver and Error Handler config on this page.

Search for it, and click the pencil to edit your config, and look at your execution paths. You may need to add /bin/ to your execution paths if any are specified.

Once you can see the page, notice that it displays the google page, except the Search button displays Find of Awesomeness as the button label.

You can play with the settings, update them, and see the changes on the servlet page.


Sling Servlets are a very handy tool to convert anything in your JCR to JSON, to aggregate and expose data sources to other components and applications in your ecosystem, or to provide an endpoint for the wild for any information you need to supply.

You can integrate the servlet with your security engine, and generally do whatever needs to be done.

If you want to access the JCR repository from a sling servlet, this tutorial may possibly be of assistance to you.

How to limit the number of characters in a DAM Dialog text field

The Problem

You want to limit the number of characters that can be entered into a DAM Dialog's text field.

The Solution

If you are using a textarea xtype, you can just add maxLength as a property with the number of characters you would like it to be limited to, set by the value. This leverages an in built validator to limit the number of characters.

Gotchya! My OSGI bundle is not displaying the edit button to configure settings

The Problem

Your newly minted custom OSGI bundle is using annotations for configurable properties, but there is no edit button visible to edit your properties in the Felix Config Console.

The Solution

In your @Component or @SlingServlet or similar annotation, you need to set  metatype=true for the edit settings to appear. 

@Property(name="MY-PROPERTY", description="", value="")

@Property(name="MY-PROPERTY", description="", value="", metatype=true)

To see the setting in flight, take a look at my other blog post on how to write a custom SlingServlet here.

GOTCHYA: CRX Explorer Error when deploying packages - Item cannot be saved because it has been modified externally: node

Item cannot be saved because it has been modified externally: node

The Problem

I came across this nasty little error when altering some configs in the JCR content explorer and updating packages.

I had updated a setting in CRX/Explorer, not clicked the Save All button, and in another window installed and deployed a package. (That I didn't think altered any of these configs).

It turns out that it did, and whenever I tried to save my changes, I got the above error.

The Solution

Right click on the offending node that's causing the issue, click on revert, and apply your changes.

Package Deployment Cheatsheet

This cheatsheet is all about how to deploy a package. To create a package, please take a look at this previous post

1. Upload the package

Click on the Upload Package button

Click on the Browse button to select your package.

It is recommended to click on the Force Upload button, as sometimes the package changes, but the filename doesn't.

In this case, install the package from the previous post.

2. Install the package

Click on the Install button

Set Access Control Handling to Overwrite.

Click on Install

The package has now been successfully installed on the author instance. Note, that the publisher instances do not yet have the contents of the package. This must occur via the Replicators, through the process of replication.

Note that replicators must be set up, and both the author and publisher instances be running for this to work.

3. Replicating the package

Click on More->Replicate, and in the Activity log below, you should see:

Replicating Package

Package is replicated asynchronously in (xx)ms

You should now be able to hit the pages/content of your package on the publish server.

Packaging Cheatsheet

This cheatsheet is on how to package up an application and a set of content pages that you have developed in the following folders in the JCR structure. Alter as necessary.


1. Create the package

Click on Create Package

Fill in the following details
Package Name: DemoSite
Version: 0.1
Leave group as default

Click on OK

Then click on Edit

2. General Tab

Add your description, and a Thumbnail. Thumbnails are good to quickly recognise the different packages.

3. Filters Tab

Enter /content/DemoSite into Root path: and click on Done.
repeat for the remaining directories:


You can add rules to specifically exclude directories and include sub directories of excluded directories here as well.

4. Dependencies Tab

It is important to keep an eye upon which version of CQ5, uncluding service packs that the package has been built and tested with. There are differences between the varying versions, and this can be useful later on to track what may have gone wrong between them.

As of Adobe CQ5-5.5.0, Package Depends on and Replaces is simply a text list. Although useful, and an item that should be filled in to make maintenance easier, it does not enforce replacement, nor dependency.

5. Advanced Tab

The Advanced Tab allows you to put your details in, so that anyone installing the package in future has an easy reference for whom to contact.

If you need Admin priviliges or a restart, check the check boxes.

Set the AC Handling to what your default should be.


Ignores the packaged access control and leaves the target unchanged.
Applies the access control provided with the package to the target. This also removes existing access control.
Tries to merge access control provided with the package with the one on the target. This is currently not fully supported and behaves like Overwrite for existing ACLs. ACLs not in the package are retained.
Tries to merge access control provided with the package with the one on the target. This is currently not fully supported and behaves like Ignore for existing ACLs. ACLs not in the package are retained.
Clears all access control on the target system.

By default we pick Overwrite to force ACL settings in.

6. Screenshots Tab

This is where you can place any images that you wish to keep with the packages. We generally have no use for this feature. Please comment below if there is a good use case for them.

Click on Save, and your settings are complete.

7. Building the package

Click on the build button.

You can now download the package using the download button. You will get a zip file, which you can then deploy onto another cq5 instance, as outlined in this post.

CQ5 Tree Replication - Cowardly Refusing to tree-activate - Forcing to activate

The Problem

When you are in the tree activation component:

You have a first level folder that you want to replicate to a publish instance, but you get a message "Cowardly refusing to tree-activate \"%s\"

For instance, when trying to activate /content

You could individually go through and replicate the second level tree elements down, but this will take too much time to do.


If you are still reading, you are doing something else wrong on a strategic level.

If you are tree replicating the /content folder, chances are you should be activating your page on the http://localhost:4502/siteadmin Website Management component.

If you really do have a lot of child folders outside of the /content folder, you should be managing with packages, which will replicate for you. See my cheatsheets on how to package, and how to deploy.

If you have made your own folder on the root level, then you should consider putting it under a more strategic position, or grouping your second level folders into a more logical structure. You shouldn't have a lot of second level folders for your code for a single project.

In the meantime, if something has gone wrong, and you don't want to suffer from carpal tunnel syndrome from overclicking your mouse, here is how to turn off the safeguard that prevents you from replicating down. (Note, this safeguard is here for a reason, mainly to prevent you from just shotgun replicating the /etc or the /lib folder)

How to ignore and do it anyway

Open up CRXDE or CRXDE Lite and point it to your author instance.

If you plan to use CRXDE Lite, go to

Then navigate to:

either by navigating down the folder structure on the left, or pasting the folder slashes into the search box.

Open up POST.jsp, and navigate down to line 176, where you will find the following:

            // reject root and 1 level paths

            /*if (path.lastIndexOf('/') <= 0) {
                if (path.length() == 0) {
                    path = "/";
                out.printf("<div class=\"error\">Cowardly refusing to tree-activate \"%s\"</div>", path);


Add the /* and */ comments (in red) and save the file.

Now go back to http://localhost:4502/etc/replication/treeactivation.html, and the check has been released.

Again, use this at your own risk, as this can cause problems with the replicators.