Posts tagged "Sling"

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

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

Place simple HTML and image files online with CRX and CQ

The Sling underpinnings of CRX and CQ allow for complex, conditional, rendering of content. That is fine and good, but what if you are just wanting to render a simple HTML page? CRX/CQ can serve static content as well. This includes any HTML files, images, SWFs and PDFs. This is a quick description of three ways to add this sort of content to your repository.

Using cURL

The most basic way to get static content into the CRX/CQ repository is to place it there using HTTP. Here is a simple example showing how to upload a page, sample.html, to a CRX server using curl:

curl -u admin:admin -T sample.html http://localhost:8080/content/sample.html

The resulting page is accessed at the same URL it was placed to.

Using WebDAV

By default, CRX/CQ allow WebDAV connections. With any WebDAV client, point to the CRX/CQ WebDAV endpoint at http://<host>:<port>/crx/repository/crx.default. I have a laptop with Windows 7 64 bit. WebDAV does not work with that operating system so I had to download a WebDAV client. My personal preference for a WebDAV client is CyberDuck (http://cyberduck.ch).

Once you connect to your CRX/CQ instance you can place your static content within the repository.

Using Package Manager

The third way to add content to your repository is to create a package and import the package. The advantage of this method is that your content becomes a single file that is portable and able to archived. Packages can be created using tools such as Maven. The method I describe here uses no build tools.

First, create a folder node to contain your content within your repository using CRXDE Lite. Right click on the node you want to contain your new node and select the Create->Create folder… from the context menu.

This will bring up a dialog to name your new folder.

Once you have created and named your new folder, be sure to press the Save All… button within CRXDE Lite. Any changes are lost if you leave the page before saving.

At this stage go back to the main screen by pressing the CRXDE Lite logo at the top and the screen. On the main screen, select the Packages link to go to the Package Manager.

In the Package Manager you can create a new, empty, package for the folder you just created in your repository. Select the Create Package button.

This will open a dialog. Enter the name and version of your package. The group of the package should be the default, my_packages. Press OK.

The package is listed within the Package Manager. Right now this package is completely empty. Within the listing for the new package select the Edit… button.

Within the dialog that is opened, select the Filters tab and press the Add Filter button. Specify the root path of the package. Press the search button next to the root path field and select the folder within the repository for the Web pages. Press OK to select the folder and press the Save button in the Edit Package dialog.

In the listing for the new package press the Build button to the right of the Edit button. The Activity Log at the bottom of the page will show you the progress of the build. Once built, press the Download button in the package’s listing to save a copy to your computer.

This package file will be a zip file with content directories and manifest files. At this stage we finally get to your content. Place the content you want to include in your repository inside the package file. Place the content inside the directory of the zip file that matches the folder in the repository you wish to place it. Once the package file contains all of your content you can upload it to any CRX/CQ repository.

To upload the package, go once again to the Package Manager. Within the Package Manager is the Upload Package button.

A dialog to select a package file appears after the Upload Package button is pressed. Select your package file. Pressing OK adds the Package you selected to CRX/CQ. The package will be listed in the Package Manager. It very important to know that the package itself has not been applied to the repository. To apply the content changes found in the package file, press the Install button within that package’s listing.

Once the package is installed the content can be access through your CRX/CQ instance.

See Also

Apache Sling –  Discover Sling in 15 minutes has instructions on how to use the curl command to add and edit content within the Sling instance. This works the same way in CRX/CQ.

The documentation site for CRX/CQ, dev.day.com, contains documentation on WebDAV access to CRX/CQ and how to work with packages.