Monday, May 12, 2014

Sling I18n and IDE integration

CQ uses Sling I18n support plus provides a number of its own useful utilities/classes. For example it has Translator Tool for convenient editing localized resources directly in running CQ instance, it has I18n class which helps you to programmatically extract localized strings using standard java ResourceBundle dictionaries, it has JSP tag <cq:setContentBundle> for setting I18n localization context and some other useful features.

Inside your JSPs you can use standard JSTL fmt:message tag to retrieve localized string, i.e.
<fmt:message var="placeholderMsg" key='components.button.placeholder'/>

What frustrates me though, is the lack of IDE integration. Sling/CQ uses hierarchical structure for representing resource bundles as compared with standard properties-based approach. Therefore there is no out-of-the-box support inside modern IDEs: you cannot use key completion feature, IntelliSense, automatic relocation to the localized string inside your resource file, etc. For example, IntelliJIDEA always shows keys inside fmt:message tag in red color, because it cannot interpret xml files as resources.

Pic 1. No Sling I18n integration in IDE 

Simple solution I found is to use standard properties files for I18n support, so IDE can work with it using its "out-of-the-box properties editor", and later convert these properties files to Sling XMLs when you create CQ package. For maven-based project you can use standard exec-maven-plugin; the same is true for ant-based projects (exec task).

Example of maven plugin description:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.3</version>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>com.yvv.cq5.build.I18nPropertiesConverter</mainClass>
        <classpathScope>compile</classpathScope>
        <arguments>
            <!-- First argument is the folder with properties files to be read -->
            <argument>${basedir}/src/main/content/jcr_root/apps/myproject/i18n</argument>
            <!-- Second argument - output folder for converted XML files -->
            <argument>${basedir}/target/vault-work/jcr_root/apps/myproject/i18n</argument>
        </arguments>
    </configuration>
</plugin>

I18nPropertiesConverter is a simple java utility which checks input folder (argument 1) for the existence of properties files, reads them and converts data into sling xml files which will be written to the output folder (argument 2). This utility can be downloaded here.

The result is full I18n support of your project which comes in your IDE "for free". Below you can see how it looks like in IDEA (11.*).


Pic 2. Out-Of-The-Box I18n integration in IDE