Archive for October, 2012

Automatic versioning of CQ DAM assets

How do you enable automatic versioning for DAM assets? The basic answer is, you can’t in CQ, as is. Pages can have automatic versioning when they are activated. DAM assets, on the other hand, don’t have the same capability without customization to CQ.

In CQ a DAM asset version must be explicitly created by a user in the DAM asset editor. The instructions on how to do this can be found in Versioning in CQ5 DAM.

Automating versioning of CQ DAM assets is more problematic.

One strategy would be to use packages to contain versions. Whole groups of DAM assets could be versioned at the same time using this method. To create a snapshot, make a new package containing the assets, give it a version, and build it. To make a snapshot of a new version of the assets, create a new version of the package and build it. This can be automated by creating scripts that periodically use curl or wget to build the packages with Package Manager.

Another option is to either a listener for change events within the DAM folder or by adding a versioning step to an existing workflow.

This is sample code that shows how to create a version within a workflow step (from Henry Saginor and David Collie):

....
@Reference
private ResourceResolverFactory resolverFactory;
private ResourceResolver getResourceResolver(Session session)
                         throws LoginException
{
     Map authInfo = new HashMap();
     authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, session);
     return resolverFactory.getResourceResolver(authInfo);
}
.....
Resource res = getResourceResolver(session).getResource(assetPath);
Asset asset = res.adaptTo(Asset.class);
Revision rev = asset.createRevision(revisionLabel, null);
.....

 

Internationalization within Sling (and CQ)

Sling, and as an extension, CQ, both use a model for internationalization that is very similar to the one used by Java and Flex. Java and Flex store translations as key/value pairs within properties files. Within Sling, translations are stored within the repository as key/value pairs. Once defined, the developer is able to use the key/value pairs stored in the repository to populate strings used in a graphic interface such as a Web page.

CQ has additional tools for internationalization than those provided by Sling. The CQ additions are not part of the scope of this article.

Locales

Before using internationalization within Sling the developer must be knowledgeable about the concept of locale. Locales within Java can be defined by three different properties: the language, the region and the variant. The primary defining property of a locale is a human language. Regions are used because each language can have several dialects and usage of the language varies greatly based on the region it is spoken and written. For that reason, a region code can be associated with a language. In that way, Canadian French may have its own definitions and translations and European French a different set. Additional information about the locale can be defined in the variant property. This property can contain information about a specific locale that is not covered by the other two properties. Examples of variant information for a locale is type of the language used, the target operating system or the text encoding.

Sling uses a standard representation of locale. The language is represented as the ISO 639‑1 code for the language in lower case. This is usually a two letter code. English, for example, would be represented as en. If needed, a region code can be specified. This is done by adding an underscore plus the ISO 3166-1 region code in upper case to the language code. So for English as spoken and written in the USA, the full locale code would be en_US. Very rarely would there be a variant defined in a locale for Sling.

Sling uses this standard because browsers use this standard for locale. Within Sling, the typical usage of internationalization would be to return the content of a Web page using the default locale of the Web browser. The default locale or locales are passed to Sling as part of the request. The site developer has the choice of respecting the locale of the Web browser and sending back content appropriate for that locale.

Key/value pairs

What do key/value pairs define? I call them translations but technical they are translation segments. Translation implies taking a word or phrase and finding the best match in another language. Translation segment is what you get after someone has done the translation for a specific use and the results are saved in a look-up table. The value of translation segment has a very specific meaning. When the phrase, OK, is used on a button the translation segment in another locale for that phrase is not necessarily a direct translation of the word, OK, but what the OK button is called in the target locale. Translation segment is very context driven. Because of that it can contain style information or substitutions indicated for data set at run time. It can even be a pattern for how information, such as a date or number, is rendered in a locale.

Within Sling, key/value pairs are organized by locale. If a site supports two languages, matching key/value pairs should exist for both. The locales CQ defines key/value pairs for can be seen at /libs/wcm/core/i18n.

Those keen of eye may notice that the locale code, en, is not there. In Java, if the value of a key is requested for a locale and that key does not exist, an exception is thrown. Not so in Sling. If a key is not defined in a locale Sling does not throw an exception. Instead, the key itself is returned. The keys for the key/value pairs in /libs/wcm/core/i18n are the translations in English. Since the locale for English does not exist the key is returned when the value of a key for the locale, en, is requested.

In CQ, the default for a key is the English phrase. The key and the English phrase are the same. Using the English phrase as the key for the key/value pair is an architectural decision and is not the only way to build translation memory in CQ.

I prefer to not use defaults for the phrases as keys. One thing that is constant in development is change. And it is likely that the text for the user interface will change. If it does, the key must be changed in all instances in the code and for each locale. Where multiple teams edit each of these items this can get to be a logistical challenge. I would use, hello_world, as a key versus the default, English, value for the phrase, Hello World! Doing things in that way allows the translators and the developers to work relatively independently of one another once the key/value pairs are defined.

Using the English phrase as the key does have its advantages and this is the reason this is the convention CQ uses. The advantage to using a default phrase as key is that the keys themselves will show up in the interface when the translation does not yet exist in a locale. Having non-phrase keys within a user interface does look like a mistake. When the phrase in English is the key and the translation does not exist in the target locale then the English phrase is shown.

Which convention to use is a matter of preference and the specific use case.

Translations in the repository

As can be seen for the CQ translations at /libs/wcm/core/i18n, the key/value pairs are stored by locale. The locale node must use the mixin, mix:language, and have the property, jcr:language, defined with a locale. In addition, the locale node may have the property, sling:basename. The sling:basename property is either a String or String array of names that can be used a labels or tags to filter translations with. The name of the locale node is not significant and can be anything. Be nice to others who have to edit what you have done, though. Name the locale node to match the locale within jcr:language or name of the language. For example, name a locale node for English either English or en. The primaryType of the locale node is not significant for translations.

Within the locale node are key/value child nodes, each one containing the information for a single key/value pair. These child nodes must either have the primaryType of sling:MessageEntry or they must have sling:Message as a mixin. The key/value node must contain a property, sling:message, that is the value for the key. If the property, sling:key, exists then that value is used as the key. If the sling:key property does not exist then the name of the node is used as the key. Following the Be Nice Rule, name the key/value node the name of the key. If you do that, the sling:key property is redundant.

Here is an example of key/value pairs for both English and French:

/apps/myapp/i18n
             +-- en (nt:folder, mix:language)
             |    +-- jcr:language = "en"
             |    +-- hello_world (sling:MessageEntry)
             |    |    +-- sling:key = "hello_world"
             |    |    +-- sling:message = "Hello world!"
             |    +-- goodbye (sling:MessageEntry)
             |         +-- sling:key - "goodbye"
             |         +-- sling:message = "Goodbye!"
             +-- fr (nt:folder, mix:language)
                  +-- jcr:language = "fr"
                  +-- hello_world (nt:unstructured,sling:Message)
                  |    +-- sling:key = "hello_world"
                  |    +-- sling:message = "Bonjour tout le monde!"
                  +-- goodbye (nt:unstructured,sling:Message)
                       +-- sling:key - "goodbye"
                       +-- sling:message = "Au revoir!"
-

Using internationalization within JSP

Within this blog post I will only give an example of using key/value pairs for locales within JSP. They can be used elsewhere in Sling, as well.

When the <sling:defineObjects /> tag is used within a JSP page, the slingRequest value is created. The slingRequest implements the SlingHttpServletRequest interface and has a couple of very useful methods for internationalization: getLocale(), getLocales(), getResourceBundle(Locale), and getResourceBundle(String, Locale).

The getLocale() method gets the default Locale of the request. The getLocales() method gets all of the methods for a request. Typically the value for these come from the browser.

The method, getResourceBundle(Locale), gets a ResourceBundle instance that has all of the found key/value pairs for the locale. The method, getResourceBundle(String, Locale), gets a ResourceBundle with all of the key/value pairs for a base name and a locale. The ResourceBundle interface has a method, getString(String), in which the argument is the key and the value of the key is returned. If the ResourceBundle does not have that key, the value returned is the key itself. One thing to keep in mind is that a ResourceBundle is not the same thing as an OSGi bundle. They are two different concepts using the same name.

An example:

<%@ page contentType=”text/html; charset=UTF-8″ language=”java” errorPage=”” %><%
%><%@ page session=”false” %><%
%><%@ page import=”javax.jcr.*,
org.apache.sling.api.resource.Resource”
%><%
%><%@ taglib prefix=”sling” uri=”http://sling.apache.org/taglibs/sling/1.0″ %><%
%><sling:defineObjects /><%
%><!DOCTYPE HTML>
<html>
<head>
<meta charset=”UTF-8″>
<title>Test</title>
</head>
<body>
<%= slingRequest
.getResourceBundle(slingRequest.getLocale())
.getString(“hello_world”) %>
</body>
</html>
/xml]

See also:

Apache Sling – Internationalization Support

Purging long-lived processes in LiveCycle

The amount of data, both disk space and database rows, that is saved by LiveCycle can build over time. Sooner or later the LiveCycle administrator will probably find himself having to clean up and get rid of old, unused, completed, long-lived processes.

The revolution will be self-fabricated

The Internet has already fostered changes that completely and irreversibly alters cultures around the world. It will be interesting to see if the same happens when manufacturing moves from the factory to the desktop: How to Make Almost Anything.

GlobalOptimizer NullPointerException when packaging AIR applications for iOS

In some circumstances, attempting to package an AIR application for Apple iOS platform using  ipa-ad-hoc and ipa-app-store targets can result in a NullPointerException. A workaround for this problem may be to use a debug version of your SWF in the package.

When using the Project->Export Release Build… menu item to create a package, click Next on the first screen. You will notice that it will build the release SWF as it switches from this screen to the Package Settings screen.

Before you click Finish on the Package Settings screen of the Export Release Build dialog, go to your project within Finder (or File Explorer on Windows). With the Export Release Build dialog open you will not be able to do the next step within Flash Builder and you will have to do it within Finder. Copy the ePresenter.swf file found in the bin-debug directory and replace the same file in the bin-release-temp directory with the one from the bin-debug.

Once you copied the debug version into the bin-release-temp folder, you can click Finish. When I tested this, it was able to create the IPA.

Example: customizing the SpinnerList in mobile AIR

Question:

Can a SpinnerList on Android or iOS AIR be changed so that certain items in the list have a different background? For example, in a list of states, make Alaska have a black background even when it is not selected.

Answer:

That can be done with a custom item renderer for the SpinnerList. It would extend the existing item renderer and would switch how it is rendered based on data in the data source.

As with so many things in Flex, there is more than one way to do this. This example is just a suggestion. Each project is different and this example may not be the best way for each one.

Item Renderer’s Data

Item renderers should rely solely on the data property for information on how to draw themselves. Item renderers can be reused, so when the data property changes the items renderer needs to change along with it or old information may be displayed. I suggest whatever data source is used for the SpinnerList should include a flag to indicate whether the state name needs to be pre-hilited. Giving the item renderer the logic to figure out if it needs to have a different background color based on the state name makes it so you will have to change your program whenever the list of states that need to be pre-hilited changes.

A very simple data source for the SpinnerList that does this would look like this:

var rawData : Array = [
{"value":"al","hilite":false,"name":"Alabama"},
{"value":"ak","hilite":true,"name":"Alaska"},
{"value":"az","hilite":false,"name":"Arizona"},
{"value":"ar","hilite":false,"name":"Arkansas"}
];
var myDataSource : ArrayCollection = new ArrayCollection(rawData);
 

How to Change the Color of the Item Renderer Background

The code for the default item renderer should be opened up and examined to see how it is rendered. The default item renderer for the SpinnerList can be found at:

[Flex sdk]\frameworks\projects\mobilecomponents\src\spark\components\SpinnerListItemRenderer.as

Item renderers tend not to use skins in order to keep them relatively lightweight. Instead of relying on skins, they usually contain the drawing logic. This particular skin, SpinnerListItemRenderer, draws a transparent box behind itself so it can capture click events. We can override this and draw a colored box instead.

Create a new item renderer that extends the SpinnerListItemRenderer. I created a class named BackgroundColorItemRenderer within my package com.adobe.example.spinner. In this new class override the method, drawBackground, that draws this transparent box and change it so it makes the background a color. Here is my logic: if the data property does not contain a value of hilite that is equal to true then pass the method to the ancestor class for rendering. Otherwise, give the background a color.

override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void
{
    if (! data.hilite)
    {
        // if no hilite, use the existing logic to draw the background
        super.drawBackground(unscaledWidth, unscaledHeight);
    }
    else
    {
        // if data.hilite == true, draw a black background
        graphics.beginFill(0x000000, 1.0);
        graphics.lineStyle();
        graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
        graphics.endFill();
    }
 }
 

In this method the color for the background is hard-coded. Create a style that sets a value for this for the component to move this value from the component to the style sheet. The name for the style property can be relatively arbitrary as long as it is not the same name as any other style for the component. I added styles, spinnerBackgroundColor and spinnerBackgroundAlpha, for the item renderer. Since, when using a black background, the text color is no longer visible, I changed it to white.

@namespace spinner "com.adobe.example.spinner.*";
spinner|BackgroundColorItemRenderer {
 spinnerBackgroundColor : #000000;
 spinnerBackgroundAlpha : 1.0;
 color : #FFFFFF;
}
 

I change the drawBackground method use the value from the style sheet:

override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void
{
    if (! data.hilite)
    {
        // if no hilite, use the existing logic to draw the background
        super.drawBackground(unscaledWidth, unscaledHeight);
    }
    else
    {
        // if data.hilite == true, draw a black background
        graphics.beginFill(
                getStyle(“spinnerBackgroundColo”), 
                getStyle(“spinnerBackgroundAlpha”));
        graphics.lineStyle();
        graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
        graphics.endFill();
    }
 }
 

Now, all that is left to do is to assign my data source and my item renderer to the SpinnerList:

<fx:Script>
<![CDATA[
    import mx.collections.ArrayCollection;
    import mx.events.FlexEvent;

    private static const SPINNER_DATA : Array = 
        [
            {"value":"al","hilite":false,"name":"Alabama"},
            {"value":"ak","hilite":true,"name":"Alaska"},
            {"value":"az","hilite":false,"name":"Arizona"},
            {"value":"ar","hilite":false,"name":"Arkansas"}
        ];

    [Bindable]
    public var spinnerData : ArrayCollection = new ArrayCollection(SPINNER_DATA);

 ]]>
 </fx:Script>
<s:SpinnerList 
            dataProvider="{spinnerData}" 
            labelField="name" 
            width="400" 
            itemRenderer="com.adobe.example.spinner.BackgroundColorItemRenderer" />
 

Friction and the software architect

Scientific American’s article, Make Technology–and the World–Frictionless, describes user experience design wonderfully but never calls it that. Actually, they describe the evil opposite of user interface design. They call it friction. Friction is making things harder than they have to be for others: be they your customer, viewers, or constituents. The writer describes examples of friction in both the retail market and politics.

This idea of friction can be expanded much more and I thought of examples in the design of frameworks, coding languages and APIs. There are several ways to add or remove friction for the software developer. One way to lower friction is to make sure that everything makes sense. There are common models for organizing code that attempt to bring an understandable structure to code. Some examples are object oriented, model/view/controller, and service oriented programming. Another way to lessen friction is to reduce the number of magic strings that have to be memorized. This can be done by using constants instead of numbers, strings, or flags that need to be memorized. These constants need to be extremely simple (LogEventLevel.DEBUG) or available via code hinting within the IDE. Another way to reduce friction in programming is to use conventions. If there were twenty Java classes, each with a String property called, title, most of the classes will probably have a getter method, String getTitle(). And most the classes that allow this property to be set will have a setter method, void setTitle(String value).

I consider the language, Perl, to be an example of how friction can be removed from coding. But, perversely enough, the stripping of friction can increase friction. A great way to decrease friction for a person coding in a language is to provide several different ways to accomplish the same task. Perl does that. Another way to help the programmer is to reduce the amount of typing that needs to be done. Perl does that as well by using several implicit variables that don’t need to be referenced directly to use. The increase of friction in Perl is when one person has to edit the code someone else has written. The very things that have reduced friction have made it hard to read someone else’s code.

I tend to believe that the software architect’s role is to Keep It Simple Stupid for the other developers. Many times that means adding complexity to the architecture.

For example, when I write code I try to never trust that someone else’s code will do what they are supposed to. For me, that means always verifying the arguments that come into a method. If someone provides null for an argument that really never should be null I throw an illegal argument exception and say which argument is the offender. Not doing that can be a big problem. If a value is not verified, it is easy to pass that same null value into another method, which does the same, which does the same. Finally, an exception is thrown and the programmer ends up with a NullValueException and a long stack trace with no idea what value was the culprit.

There is an art to writing a good framework or API. And a large part of this art is to consider the user experience design. It is not enough to be clever. It has to be usable.

Setting default values on CQ components

Components are self-contained portions of code within CQ. While not necessarily visual or part of the user interface, oftentimes they are. Within the CQ framework components can be dragged from the SideKick and placed within a page layout.

Within the CQ page editor, a component can have a dialog to configure values for the component instance that is on the page. Documentation exists that describes how to create a component for use within CQ. It is not necessary for the page author to open the component editor and edit all of the values each time a component is used. Properties can be defined with a default value which is applied automatically.

Prerequisites

To create a default value on a component, knowledge of how to create and edit components within CRXDE or CRXDE Lite is necessary.

Setting a default value on a CQ component

Go to the widget within the component’s dialog that is used to set the property on the component and add a property to the widget itself: defaultValue. If it is possible to select multiple values the defaultValue property should be an array.

Example

In this example I will have a simple viewer component that has a single configurable property: alignProp. Alignment may either be a Left or Right. By default, the value should be Left.

Within the /apps/dekesmith/examples/components/ directory I created a new component node called simple-viewer:

{
    " jcr:title":"Simple Viewer",
     "allowedParents":["*/*parsys"],
     "sling:resourceSuperType":"foundation/components/parbase",
     "componentGroup":"Media",
     "jcr:primaryType":"cq:Component",
     "dialog":{
          "jcr:primaryType":"cq:Dialog",
          "items":{
               "jcr:primaryType":"cq:WidgetCollection"
               "items":{
                    "jcr:primaryType":"cq:WidgetCollection",
                    "tab1":{
                        "jcr:primaryType":"cq:Panel",
                        "title":"tab1",
                        "items":{
                            "jcr:primaryType":"cq:WidgetCollection",
                            "alignment":{
                                  "jcr:primaryType":"cq:Widget",
                                  "fieldLabel":"Alignment",
                                  "type":"select",
                                  "xtype":"selection",
                                  "defaultValue:","Left",
                                  "name":"alignProp",
                                  "options":{
                                       "jcr:primaryType":"cq:WidgetCollection",
                                       "Left":{
                                            "jcr:primaryType":"nt:unstructured",
                                            "value":"Left",
                                            "text":"Align Left"    
                                       },
                                       "Right":{
                                            "jcr:primaryType":"nt:unstructured",
                                            "value":"Right",
                                            "text":"Align Right"
                                       }
                                  }
                            }
                        }               
                    } 
                }
          }
     }
}
 

This component has an edit dialog for setting properties of the component within the CQ site editor. The edit dialog has a single tab with a single selection menu, alignment, that sets a property for the component, alignProp. The alignment menu has two choices, Right and Left. The default value should for the property should be added on the widget that sets that property. To give the alignProp property a default of Left I added a defaultValue to the selection widget, alignment.

Using sling:Mapping to expose repository values

Besides conventional client access to Web sites using a browser, client applications can be built within applications such as Flex and still access data in our repositories. A quick way of doing this is by having Flex access that data as JSON. There is one thing that makes this problematic for production. When a publish instance is accessed through Dispatcher it is suggested that any access to URLs ending with the .json suffix should be forbidden. For security reasons many directories in the repository should not be accessible through outward facing connections. Like I mentioned, this can be problematic if JSON is being accessed by Flex.

Sling, and by extension CQ, has a redirect mechanism that can selectively expose values.

Pre-requisites

Knowledge of the use of CRXDE or CRXDE Lite to edit nodes and properties is required for the example.

What are sling:Mapping nodes?

Sling uses sling:Mapping nodes much the same way that Apache’s mod redirect uses its configurations in httpd to define redirect behavior. The Apache Sling Web site has documentation for mappings. Existing mappings can be seen in the Sling Resource Resolver Console at http://[host]:[port]/system/console/jcrresolver.

A brief explanation is that redirect behavior can be configured by setting properties on sling:Mapping nodes. There should be one sling:Mapping node per redirect rule. The sling:Mapping nodes can have nested sling:Mapping nodes, but that is not needed for my simple example and I won’t go there at this time. Add the sling:Mapping nodes to the repository within the /etc/map/ directory. Sub-folders can be created in this directory and that has an effect on how URLs are matched for redirecting. Once again, this article does not need this and I won’t get into that. This framework can be very powerful and has many ways of being configured. The use case for the sling:Mapping node will be basic and simple in this example.

Using redirection to access JSON data behind a securely configured Dispatcher

For this example I will show how to create a redirect that allows access to the possible values of a dialog used to configure a component. The component is the Flash component. The values are for the menu property of the Flash component. That value is contained within the dialog configuration of the Flash component:

|- libs
   |- foundation
      |- components
         |- flash
            |- dialog
               |- items
                  |- menu
                     |- options
 

The url I used to get the JSON version of this on my local, sample server is [1]. Calling this JSON as admin returns:

{
     "jcr:primaryType":"cq:WidgetCollection",
     "show":{
          "value":"show",
          "jcr:primaryType":"nt:unstructured",
          "text":"Show"
     },
     "hide":{
          "value":"hide",
          "jcr:primaryType":"nt:unstructured",
          "text":"Hide"
     }
}
 

The direct URL to this value is not available behind Dispatcher. Dispatcher should not allow calls either to the /libs directory nor any resource with a .json suffix.

To make it so the Flex client can query this value we need to set up a mapping for it.

  1. Create a node called, menudata, of type sling:Mapping within the /etc/maps/ directory
  2. Create a property called, sling:internalRedirect, of type String to the menudata node. Set it to:/libs/foundation/components/flash/dialog/items/advanced/items/menu/options.1.json
  3.  Create a property called, sling:match, of type String to the menudata node. Set it to:^[^/]+/[^/]+/menu-options$

Once saved, the redirect takes effect. You should see the values of this mapping if you go to Sling Resource Resolver Console.

The sling:internalRedirect property is the relative URL to a resource within the repository. There are, of course, exceptions. But for this example the value of the internalRedirect property is returned without sending a redirect message back to the browser.

The sling:match property is a regular expression pattern used to match the URL. If this property were not present in the sling:Mapping node it would use the node’s name to match with.

Now, when I go to the URL that calls menu-option ([2] on my local server), the value of the options node is returned.

Standard cautions apply. Be very conservative about what you expose to the outside world. But the redirect mechanism in Sling is very powerful and it is worth exploring.

[1] http://localhost:4502/libs/foundation/components/flash/dialog/items/advanced/items/menu/options.1.json

[2] http://localhost:4502/menu-options