Search

Dark theme | Light theme
Showing posts with label Cocoon. Show all posts
Showing posts with label Cocoon. Show all posts

March 9, 2009

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 8)

The previous parts(part 1, part 2, part 3, part 4, part 5, part 6, part 7) where all about the settings provided with Spring Configurator. In this part we look at another component that is part of the Spring Configurator: the BeanMap.

The BeanMap can store beans found in the Spring context in a map, hence the name. We can define the type of beans we want to store in the map and the BeanMap component will find those beans. The name or id of the found bean is used as the key for storing it in the map.

We extend our little example from the previous parts and introduce a simple interface (yes, a really simple, do-nothing, marker interface) named SampleService:

package com.mrhaki.netbeans.mavenapp;

public interface SampleService {
    // Simple marker interface.
}

Next we change the Sample and let it implement the SampleService interface:

package com.mrhaki.netbeans.mavenapp;

import org.apache.cocoon.configuration.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Sample implements SampleService{

    private Settings settings;

    private String text;

    private int timeout = 1000;

    @Autowired
    public void setSettings(Settings settings) {
        this.settings = settings;
    }

    public void setText(String name) {
        this.text = name;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public String getMachine() {
        return settings.getProperty("machine");
    }
    
    @Override
    public String toString() {
        return "Running in [" + settings.getRunningMode() + "] mode. "
                + "Text = [" + text + "] and timeout = [" + timeout + "].";
    }
}

We can now define a BeanMap in our applicationContext.xml that needs to store all beans found in the Spring context which implement the SampleService interface. The BeanMap can be defined standalone and have it's own name or id or it can be assigned to a property of another bean. For this example we use it standalone. We need to set the attribute type to the type of class we want to find, which in our case is com.mrhaki.netbeans.mavenapp.SampleService:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:configurator="http://cocoon.apache.org/schema/configurator"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://cocoon.apache.org/schema/configurator http://cocoon.apache.org/schema/configurator/cocoon-configurator-1.0.1.xsd">

    <context:component-scan base-package="com.mrhaki.netbeans.mavenapp"/>
    <configurator:settings>
        <configurator:include-properties dir="classpath*:META-INF/app-config/properties"/> 
        <configurator:include-beans dir="classpath*:META-INF/app-config/spring"/> 
    </configurator:settings>

    <configurator:bean-map type="com.mrhaki.netbeans.mavenapp.SampleService" name="beanMap" />

    <bean name="sample" class="com.mrhaki.netbeans.mavenapp.Sample">
        <property name="text" value="${sample.text1:Default value}"/>
    </bean>

</beans>

In our test code we add statements to print out the key/value pairs of the BeanMap:

package com.mrhaki.netbeans.mavenapp;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTest extends TestCase {

    public AppTest(String testName) {
        super(testName);
    }

    public static Test suite() {
        return new TestSuite(AppTest.class);
    }

    public void testApp() {
        final ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        final Map<String, Object> map = (Map) appContext.getBean("beanMap");
        for (String key : map.keySet()) {
          System.out.println("key[" + key + "] = value[" + map.get(key) + "].");
        }
    }
}

Now if we run our little test (mvn test) we can see in the following output both Sample beans are found:

key[anotherSample] = value[Running in [prod] mode. Text = [I am the other sample from anotherContext.xml.] and timeout = [1000].].
key[sample] = value[Running in [prod] mode. Text = [We are alive!] and timeout = [1000].].

Of course this is just a simple example, but if we assign the BeanMap as a property we can write application code which have access to all beans of a certain type defined in the Spring context. So we can access beans we don't know about, because they can be defined in a third-party jar, but still use them in our code.

March 8, 2009

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 7)

The Spring Configurator makes it very easy to configure beans in the Spring configuration files. We can read in the previous parts (part 1, part 2, part 3, part 4, part 5, part 6) the configurator by defaults assumes we put property files in directories named cocoon. That is because the Spring Configurator was first developed as part of Cocoon 2.2. But we can also use our own directory names so we don't see any cocoon in our definitions.

For example we rename the src/main/resources/META-INF/cocoon directory of our example to src/main/resources/META-INF/app-config. Next we must add extra elements to the configurator:settings in our applicationContext.xml, see lines 13 and 14. The configurator:include-properties element contains a Spring resource path. In our case all properties from META-INF/app-config/properties and META-INF/app-config/properties/[runningMode] in the classpath are loaded, where [runningMode] is replaced with the current running mode. So if we run the application in prod running mode the path will be META-INF/app-config/properties/prod. The configurator:include-beans elements loads Spring configuration files from the META-INF/app-config/spring and META-INF/app-config/spring/[runningMode] directories in the classpath. The runningMode is replaced by the current running mode, just as with the properties.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:configurator="http://cocoon.apache.org/schema/configurator"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://cocoon.apache.org/schema/configurator http://cocoon.apache.org/schema/configurator/cocoon-configurator-1.0.1.xsd">

    <context:component-scan base-package="com.mrhaki.netbeans.mavenapp"/>
    <configurator:settings>
        <configurator:include-properties dir="classpath*:META-INF/app-config/properties"/> 
        <configurator:include-beans dir="classpath*:META-INF/app-config/spring"/> 
    </configurator:settings>

    <bean name="sample" class="com.mrhaki.netbeans.mavenapp.Sample">
        <property name="text" value="${sample.text}"/>
    </bean>

</beans>

Now we can run our application (mvn test) and all properties and Spring configuration files are read from META-INF/app-config/properties, META-INF/app-config/properties/prod, META-INF/app-config/spring and META-INF/app-config/spring/prod.

We can put as many configurator:include-properties and configurator:include-beans elements in the configuration file as we want.

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 6)

In the previous parts (part 1, part 2, part 3, part 4, part 5) we learned a lot about the Spring Configurator. But the documentation of the Spring Configurator is a bit sparse (if we can find it on the website, which is a task in itself).

So browsing the mailing lists and source code I found a hidden feature. We can define default values for a property in the property references. If the value for the property cannot be found the default value is used. The following Spring configuration contains this default value for the property sample.text1. This property is not defined anywhere so the default value after the colon is used (see line 15):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:configurator="http://cocoon.apache.org/schema/configurator"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://cocoon.apache.org/schema/configurator http://cocoon.apache.org/schema/configurator/cocoon-configurator-1.0.1.xsd">

    <context:component-scan base-package="com.mrhaki.netbeans.mavenapp"/>
    <configurator:settings/>

    <bean name="sample" class="com.mrhaki.netbeans.mavenapp.Sample">
        <property name="text" value="${sample.text1:Default value}"/>
    </bean>

</beans>

If we run our test (mvn test) with the test class from part 1, we get as output:

Running in [prod] mode. Text = [Default value] and timeout = [1000].

We see how the property text now contains the default value we specified in the property reference in the Spring configuration file.

March 5, 2009

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 5)

We look into the Spring Configurator a bit more, because we have not seen all of the possibilities. If we read the previous parts (part 1, part 2, part 3, part 4) we already experienced the power of the Spring Configurator. In this part we learn how to add our own properties to the configurator.

It is a good idea to extract settings from the Java code and externalize into a configuration file. This configuration file can be a Java properties file. In the application we can load the properties files and use the property values in our code. This mechanism is very easy to implement with the Spring Configurator. The only thing we need to do is place the Java properties file at a certain location and inject the Spring Configurator settings object in our application. Every property in the properties file is then available via the Spring Configurator.

Let's see how this works with our example. First we create a new property file at src/main/resources/META-INF/cocoon/properties/settings.properties and define the property machine:

machine=My muscle machine

We change our Sample class so we can display the value of this property (see lines 28-30):

package com.mrhaki.netbeans.mavenapp;

import org.apache.cocoon.configuration.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Sample {

    private Settings settings;

    private String text;

    private int timeout = 1000;

    @Autowired
    public void setSettings(Settings settings) {
        this.settings = settings;
    }

    public void setText(String name) {
        this.text = name;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public String getMachine() {
        return settings.getProperty("machine");
    }
    
    @Override
    public String toString() {
        return "Running in [" + settings.getRunningMode() + "] mode. "
                + "Text = [" + text + "] and timeout = [" + timeout + "].";
    }
}

The Settings class has two methods to get properties:

  • getProperty(String propertyName) to get the value for the property with propertyName
  • getProperty(String propertyName, String defaultValue) to get the value for the property and if it is not found use a default value
This way we can get the value for all available properties.

To test if we really get the value for our property we change our test class to output the property value:

package com.mrhaki.netbeans.mavenapp;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTest extends TestCase {

    public AppTest(String testName) {
        super(testName);
    }

    public static Test suite() {
        return new TestSuite(AppTest.class);
    }

    public void testApp() {
        final ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(((Sample)appContext.getBean("sample")).getMachine());
    }
}

If we run the test (mvn test) we get the following output:

Muscle machine

But wait that is not all. If we use the Settings object we also have access to the standard Java system properties and environment variables. The Java system properties can be accessed with their property name. The environment variables are prefixed with env.:

System.out.println(settings.getProperty("os.name"); // Output: Windows Vista
System.out.println(settings.getProperty("env.PROMPT"); // Output: $p$g

In this part we have learned how to access our own defined properties, Java system properties and environment variables.

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 4)

The Spring configurator has even more to offer than the things we have learned in the previous parts (part 1, part 2, part 3). If we place Spring configuration files at certain locations in our application classpath then they will be added to the existing Spring application context. This means we don't have to explicitly add the configuration files another configuration with an import, it is available automatically. And as we can guess we can use this even per running mode.

In the documentation we can see where we must place the Spring configuration files. For our example we create a new Spring configuration file in the src/main/resources/META-INF/cocoon/spring directory and name it anotherContext.xml. Here is the contents of the file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean name="anotherSample" class="com.mrhaki.netbeans.mavenapp.Sample">
        <property name="text" value="I am the other sample from anotherContext.xml."/>
    </bean>
</beans>

We define another bean for the same sample class and give the property text a new value (see line 8).

In our test class we add a statement to print out the value for this property (see line 21). So we get the following test:

package com.mrhaki.spring.mavenapp;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTest extends TestCase {

    public AppTest(String testName) {
        super(testName);
    }

    public static Test suite() {
        return new TestSuite(AppTest.class);
    }

    public void testApp() {
        final ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(appContext.getBean("sample"));
  System.out.println(appContext.getBean("anotherSample"));
    }
}

When we run the test (mvn test) we get the following output:

Running in [prod] mode. Text = [We are alive!] and timeout = [1000].
Running in [prod] mode. Text = [I am the other sample from anotherContext.xml.] and timeout = [1000].

So we see we didn't define anywhere to load anotherContext.xml, but we can use all beans defined in it! The Spring configuration file is loaded by the Spring configurator, because of the placement of the file in the classpath.

March 1, 2009

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 3)

Okay we have learned about the running modes in part 1 and we saw how to use the property configurer in part 2. In this part we see how we can use the property overrider.

Suppose we have a Java class configured in the Spring context with a default value and want to override this value for a specific running mode. That is where the property overrider comes into play.

We add a new timeout property to our Sample class:

package com.mrhaki.spring.mavenapp;

import org.apache.cocoon.configuration.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Sample {

    private Settings settings;

    private String text;
 
    private int timeout = 1000;

    @Autowired
    public void setSettings(Settings settings) {
        this.settings = settings;
    }

    public void setText(String name) {
        this.text = name;
    }
 
    public void setTimeout(int timout) {
        this.timeout = timeout;
    }

    @Override
    public String toString() {
        return "Running in [" + settings.getRunningMode() + "] mode. "
                + "Text = [" + text + "] and timeout = [" + timeout + "].";
    }
}

If we read the documentation we see we must define a property file and can place it in different locations. For our example we create a property file at src/main/resources/META-INF/cocoon/spring/dev/timeout.properties. And we use the following content:

sample/timeout=42

This property file will be used in the dev running mode by the Spring Configurator. The property file will override bean configurations set in the Spring context. The Spring Configurator uses the / to separate the bean name and property. In our example we override the timeout property of the sample bean.

When we run the test in dev running mode, mvn test -Porg.apache.cocoon.mode=dev, we get the following output:

Running in [dev] mode. Text = [We are developing!] and timeout = [42].

And if we run the example in prod mode, mvn test, we get the following output:

Running in [prod] mode. Text = [We are alive!] and timeout = [1000].

This way we can easily override properties already set by code in Spring configurations! In the next part we see how the Spring Configurator can load Spring configuration files automatically.

February 17, 2009

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 2)

In the previous part we learned about the Spring Configurator. In this part we learn how to create properties for different environments (or running modes) and how to use them.

First we add a simple String property with the name text to our Sample class:

package com.mrhaki.spring.mavenapp;

import org.apache.cocoon.configuration.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Sample {

    private Settings settings;

    private String text;

    @Autowired
    public void setSettings(Settings settings) {
        this.settings = settings;
    }

    public void setText(String name) {
        this.text = name;
    }

    @Override
    public String toString() {
        return "Running in [" + settings.getRunningMode() + "] mode. "
                + "Text = [" + text + "].";
    }
}

Notice how we changed the toString method so we can see the value for the text property. Next we add the bean definition for the Sample class in our applicationContext.xml. Therefore we add the following lines after <configurator:settings/>:

<bean name="sample" class="com.mrhaki.spring.mavenapp.Sample">
 <property name="text" value="${sample.text}"/>
</bean>

At line 2 we assign the text property a variable value, which is not set yet. The value will be set if we run the application and is read from a property file. We can now use the Spring Configurator to define a different value for sample.text for every running mode we want to support. For this example we assume a dev and test running mode. If we read the Spring Configuration manual we notice we can place the property files at many locations. This is what makes the Spring Configurator so flexible and useful.

First we create in the src/main/resources directory the following directories: META-INF/cocoon/properties/dev and META-INF/cocoon/properties/test. We create a sample.properties file in the src/main/resources/META-INF/cocoon/properties/dev directory. In the file we define:

sample.text=We are developing!

We save the file and if we run mvn test -Dorg.apache.cocoon.mode=dev we get the following output:

Running in [dev] mode. Text = [We are developing!].

The Spring Configurator has replaced our variable sample.text with the value from the property file. We also create a sample.properties file in the src/main/resources/META-INF/cocoon/properties/test directory and give a different value for the property:

sample.text=Ready for testing!

We run the test again, but now use the test running mode:mvn test -Dorg.apache.cocoon.mode=test. And we get this output:

Running in [test] mode. Text = [Ready for testing!]

Finally we create a sample.properties in the src/main/resources/META-INF/cocoon/properties directory with a default value, which is used by the default running mode (prod):

sample.text=We are alive!

We run mvn test and we see in the output:

Running in [prod] mode. Text = [We are alive!].

So in this part we have learned how to use property files for different running modes to replace variables in the Spring configuration files. In the next part we learn how override properties of beans defined in Spring configuration files.

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 1)

We develop an application usually on a development environment: our computer. Then the application gets deployed to a test environment to be tested by users. And finally we deploy the application to the production environment so the application is live. This scenario is the most simple one and can of course be more complicated with extra environments for integration testing or other things.

The Spring configuration files are usually different for each of the environments. For example we can define a database JDBC URL in the Spring configuration files for a development database, but that is different from the database JDBC URL in the production enviroment. Spring provides some kind of support with PropertyPlaceHolderConfigurer and PropertyOverrideConfigurer to define properties. But the Spring Configurator provides transparent support for Spring configuration in different environments or running modes.

Let's start with a simple example to get the Spring Configurator working. We create a new Maven project with the QuickStart archetype (mvn archetype:generate, choose the QuickStart archetype, groupId is com.mrhaki.spring.mavenapp and artifactId is springconfapp). We add the Spring configurator to the pom.xml dependencies section:

<dependency>
 <groupId>org.apache.cocoon</groupId>
 <artifactId>cocoon-spring-configurator</artifactId>
 <version>2.0.0</version>
</dependency>

Next we add a basic Spring configuration file to the src/main/resources directory with the name applicationContext.xml and the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:configurator="http://cocoon.apache.org/schema/configurator"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://cocoon.apache.org/schema/configurator http://cocoon.apache.org/schema/configurator/cocoon-configurator-1.0.1.xsd">

    <context:component-scan base-package="com.mrhaki.spring.mavenapp"/>
    <configurator:settings/>
</beans>

Notice at line 11 we set-up Spring to autodetect components in the com.mrhaki.spring.mavenapp package. And in line 12 we create the Spring Configurator settings object. We create a new Java class Sample in the com.mrhaki.spring.mavenapp package:

package com.mrhaki.spring.mavenapp;

import org.apache.cocoon.configuration.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Sample {

    private Settings settings;

    @Autowired
    public void setSettings(Settings settings) {
        this.settings = settings;
    }

    @Override
    public String toString() {
        return "Running in [" + settings.getRunningMode() + "] mode.";
    }
    
}

For the example we add the Spring Configurator settings object as a property to the Sample class. In the toString() method we return the current environment that is used. Now we change the AppTest class and use our Sample class and display which running mode is used:

package com.mrhaki.spring.mavenapp;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTest extends TestCase {

    public AppTest(String testName) {
        super(testName);
    }

    public static Test suite() {
        return new TestSuite(AppTest.class);
    }

    public void testApp() {
        final ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(appContext.getBean("sample"));
    }
}

Now if we run the test (mvn test) we get the following output:

Running in [prod] mode.

The prod running mode is the default running mode for the Spring Configurator if we don't do anything else. We can change the running mode by using the environment property org.apache.cocoon.mode. For example if we run the test again, but now use mvn test -Dorg.apache.cocoon.mode=dev we get the following output:

Running in [dev] mode.

This way we can easily change the running mode to be used. This is part 1 of the Spring Configurator. In the next part we will see how we can define and use properties for different environments.

January 12, 2009

Add request logging to Cocoon 2.2

Cocoon 2.2 uses the Jetty Maven plugin to run the application. We can add request logging to the configuration of the Jetty plugin so we can see which URLs are invoked to the Jetty server.

First we must look in our pom.xml of our Cocoon 2.2 project. We must find the maven-jetty-plugin plugin block. Here we add to the configuration element the following:

<requestLog implementation="org.mortbay.jetty.NCSARequestLog">
    <filename>target/work/log/yyyy_mm_dd.request.log</filename>
    <retainDays>5</retainDays>
    <append>false</append>
    <extended>true</extended>
    <logTimeZone>GMT+1</logTimeZone>
</requestLog>

This configures request logging for the Jetty server. Now when we run our Cocoon application we can see in the target/work/log directory a file with the requests logged.

The API documentation shows all options we can set for this logger.

November 27, 2008

Add Cocoon Sitemap template in NetBeans

I really like to use NetBeans to develop Cocoon 2.2 applications. NetBeans has great support for XSLT 2.0, XML and Maven. And those are the technologies I use when I develop a Cocoon 2.2 application, so the choice is obvious. To speed up development we can make a new template for a sitemap.xmap file. Once we have a template we can select it when we add a new file with File | New File.

To create a template we use an existing sitemap.xmap from a Cocoon 2.2 project. We must right-click on the file and select Save As Template....

NetBeans opens a dialog window where we must select in which category the template must be saved. We select XML to save the template and then press the OK button.

Now we can select the template when we go to File | New File (or press Ctrl+N in Windows). In the XML category we find our sitemap.xmap template. We can select and press the Next button.

We can type a new name and the location where we want to save the sitemap file. We press the Finish button and we can start editing the new sitemap file.

November 21, 2008

Add Cocoon XML filetypes to NetBeans 6.5

In a previous blog entry we learned how to add documents with different file extensions as XML type to NetBeans. In NetBeans 6.5 this has become much easier and with more support for XML types. For example we could add other documents in earlier versions of NetBeans, but the Navigator view did not show the XML structure of these new added documents. In NetBeans 6.5 we cannot only add other extensions as XML types, but also the Navigator view will be fully functional!

I use Cocoon for many projects and Cocoon has several XML configuration files. These files have the extensions xmap, xconf and xweb. Let's add XML support for the xmap file extension in NetBeans 6.5. First we go to Tools | Options | Miscellaneous | Files. This is new in NetBeans 6.5, we don't have to go to Advanced Options it is right here in the Options window.

Then we click on the New button and NetBeans shows a dialog window. Here we type the File Extension: xmap and press the OK button.

Now we must select from Associated File Type (MIME) the option XML Files (text/xml). This will bind the xmap extension to the XML filetype.

We can now open a sitemap.xmap file in NetBeans and we get full XML support, even in the Navigator window:

Copy template for XSLT in NetBeans

Cocoon has a great way to split up big XSL stylesheet into multiple little stylesheets. With the Cocoon pipeline we can go from one stylesheet to the other. This results in better maintainable stylesheets. Because one stylesheet is executed after another in a pipeline we want to pass around the XML. For example one stylesheet will handle a product element from an order XML and we want to give the rest of the order XML to the next stylesheet. The code to do this is easy:

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

Because we need this code so much it is easy to make a code template for it in NetBeans. We go to Tools | Options | Editor | Code Templates and select XML as the language. We click on the New button to create a new code template. NetBeans shows a dialog window with an input field for the abbreviation we want to use. We type ct and click the OK button. We now see our abbreviation is added and we can type our code in the Expanded text tab. We type

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
We can add a short description in the Description tab. Let's type Copy template for XSLT. Finally at the bottom we see Expand Template on. Here we can define which character NetBeans will react to after we type ct in an XSL stylesheet to expand the template code. Let's leave it to the Tab character.

Now when we return to the NetBeans code editor and we are working on a XSL stylesheet, we can type ct, press the Tab key and we get the complete code inserted into our stylesheet.

November 10, 2008

Using a different log4j configuration in a Cocoon 2.2 block

The Cocoon 2.2 Maven plugin provides a good method for developing a block. When we configure the plugin correctly we can start Jetty and have a reloadable web application. This means every change we make to a source file is reflected immediately in the web application. The plugin also has a default Log4j configuration file. The configuration defines a FileAppender with the filename ./target/work/log/log4j.log. The append property is set to true. This can result in a very big log4j.log file, because as long we don't run mvn clean all logging is added to the existing file.

We can change the configuration for Log4j by setting a parameter in the Cocoon 2.2 Maven plugin. We must add the parameter customLog4jXconf to our plugin definition:

<plugin>
 <groupId>org.apache.cocoon</groupId>
 <artifactId>cocoon-maven-plugin</artifactId>
 <version>1.0.0-M2</version>
 <executions>
  <execution>
   <id>prepare</id>
   <phase>compile</phase>
   <goals>
    <goal>prepare</goal>
   </goals>
   <configuration>
    <customLog4jXconf>src/main/etc/log4j.xml</customLog4jXconf>
   </configuration>
  </execution>
 </executions>
</plugin>

Notice we defined the parameter customLog4jXconf and set it to the file src/main/etc/log4j.xml. Now we can create the new log4j.xml file and save it in src/main/etc:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="CORE" class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="./target/work/log/log4j.log"/>
        <param name="Append" value="true"/>
        <param name="MaxBackupIndex" value="10"/>     
        <param name="MaxFileSize" value="5MB"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %t %-5p %c{2} - %m%n"/>
        </layout>
    </appender>    
    <root>
        <priority value="\${org.apache.cocoon.log4j.loglevel}"/>
        <appender-ref ref="CORE" />
    </root>
</log4j:configuration>

Notice: in line 14 we must escape the $ sign with a \. The plugin will run this file through StringTemplate and therefore we must escape the $ sign.

Now when we run mvn jetty:run our new Log4j configuration file is used.

September 22, 2008

Add CDATA section to output with XMLSerializer in Cocoon 2.2

We can use Cocoon to put the contents of XML elements in a CDATA section. To achieve this we must configure the XMLSerializer. In Cocoon 2.2 we add a new bean definition to the file src/main/resources/META-INF/cocoon/spring/block-servlet-service.xml.

<bean name="org.apache.cocoon.serialization.Serializer/cdata-xml" class="org.apache.cocoon.serialization.XMLSerializer"
 scope="prototype" parent="org.apache.cocoon.serialization.AbstractTextSerializer">
 <pipeline:component mime-type="text/xml;charset=utf-8"/>
 <property name="format">
  <props>
   <prop key="encoding">UTF-8</prop>
   <prop key="cdata-section-elements">contents title</prop>
  </props>
 </property>
</bean>

In line 7 we define the XML elements we want to enclose in CDATA. We can use this serializer in our sitemap.xmap and the contents and title elements will have CDATA sections. Suppose we have the following input.xml file:

<root>
 <title>My special title.</title>
 <contents>Simple content with &lt;b&gt;html&lt;/b&gt; code.</contents>
 <field>Another field</field>
</root>

When we run it through the following pipeline:

<map:match pattern="output.xml">
 <map:generate src="input.xml"/>
 <map:serialize type="cdata-xml"/>
</map:match>

We get the following output:

<xml version="1.0" encoding="UTF-8"?><root>
 <title><![CDATA[My special title.]]></title>
 <contents><![CDATA[Simple content with <b>html</b> code.]]></contents>
 <field>Another field</field>
</root>

September 21, 2008

Debugging Cocoon 2.2 in NetBeans

Most of the time when we work with Cocoon we are writing XSLT to do transformations. But sometimes we write Java code to extend the functionality of Cocoon. And that means we want to be able to debug our Java code in NetBeans. Luckily this is easy to accomplish. First we must start Jetty with mvndebug. This will enable us to attach the NetBeans debugger to Jetty, which runs our Cocoon application.

We open a command prompt and go to the directory with our Cocoon application. In the directory we run the following command: mvndebug jetty:run. Maven now starts in debug mode. And because Jetty runs in the same process as Maven we also run Jetty in debug mode.

Now in NetBeans we go to Run | Attach Debugger. We get a dialog window with settings. We can leave the settings as-is and press the OK button. NetBeans will now attach the debugger to Jetty. In NetBeans we can set breakpoints in our Java code and debug our code.

September 15, 2008

Use properties from the Spring configurator in Cocoon 2.2 sitemap

Cocoon 2.2 has a new mechanism for working with configurations: the Cocoon Spring Configurator component. Adding the configurator to our application is easy, because we only have to add <configurator:settings/> to a Spring configuration file. Now we have support for running modes, property handling and Spring bean configurations. Just like that.

We will use a small example to see how properties are handled by the configurator. Suppose we have a simple Cocoon 2.2 block with a sitemap.xmap. In the sitemap.xmap we use the property enable.internal-only (see line 6.):

<?xml version="1.0" encoding="UTF-8"?>
<map:sitemap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://apache.org/cocoon/sitemap/1.0 http://cocoon.apache.org/schema/sitemap/cocoon-sitemap-1.0.xsd"
 xmlns:map="http://apache.org/cocoon/sitemap/1.0">
    <map:pipelines>
        <map:pipeline id="internal-resource" internal-only="${enable.internal-only}">
            <map:match pattern="resource/internal/**">
                <map:read src="resource/internal/{1}"/>
            </map:match>
        </map:pipeline>
        <map:pipeline id="external-resource">
            <map:match pattern="resource/external/**">
                <map:read src="resource/external/{1}"/>
            </map:match>
        </map:pipeline>
    </map:pipelines>
</map:sitemap>

To give the property a value we have different alternatives, not to say a lot of alternatives. For this example we create a new property file: src/main/resources/META-INF/cocoon/properties/sample.properties. In the file we define enable.internal-only=false. Now when we run the application we can access the pipeline internal-resource because the value of the property enable.internal-only is false.

September 11, 2008

Your first Cocoon application using Maven 2 in NetBeans

This blog post is a copy of the original Your first Cocoon application using Maven 2 tutorial, but this time we are going to use NetBeans to build the application!

To create a new Cocoon block we go to File | New Project. We get a new dialog window with a list of project categories. We start by selecting the Maven category and then select Maven Project.

Click on the Next button and we get a new screen where we can select the Maven Archetype. We need to scroll down the list until we get to Archetypes from Maven repositories. We click on the plus-sign to get a new list of archetypes. We scroll down to Cocoon 2.2 Archetype: Block and select it.

We click on the Next button to go to the last screen. Here we type myBlock1 at the Project Name input field. We type 1.0.0 in the Version input field and press the Finish button.

NetBeans will now generate a new project based on the Cocoon 2.2 block archetype. When we look at the project we can see a lot of directories are created and some sample files.

To run the block as Java web application we first go to the project properties. We right-click on the project and select Properties from the popup menu. In the project properties dialog window we must select the Actions category. Make sure Use external Maven for build execution is checked. See also Use external Maven to work with Cocoon. Then we redefine the Run project action and set Execute Goals to jetty:run. The Set Properties field must be empty. We click the OK button to finish up.

Now we can run the project (for example by using the shortcut Shift+F6 in Windows) and NetBeans will start Jetty. We can open a web browser and go to http://localhost:8888/myBlock1 and we get the sample page.

Because of an issue for Windows users (see issue 138116) we cannot shutdown Jetty from within NetBeans. We must use the task manager (or another tool) to kill the Jetty process. Or read Shutdown Jetty started by Maven in NetBeans.

September 10, 2008

Use external Maven to work with Cocoon 2.2 in NetBeans

Update: since NetBeans 6.5 we don't have to use the external Maven. We can use the internal Maven from NetBeans! So if you use NetBeans 6.1 you must apply what is described in this post, otherwise you are already to go.

Working with Cocoon 2.2 is a blessing compared to the previous versions. Cocoon 2.2 is now based on the Spring framework and uses Maven for the build process. Especially the dependency mechanism of Maven makes creating a new Cocoon application a lot easier. And if there is one IDE out there with superb Maven support than it is NetBeans.

NetBeans already has the Cocoon Maven archetypes available. To create a new Cocoon block for example is as easy as clicking on several menu options. The only thing we need to consider is that the Cocoon Maven plugin doesn't (yet) support the Maven 2.1-SNAPSHOT version, which is used by the NetBeans. Luckily we can define an external Maven in NetBeans to be used.

Make sure we have installed Maven 2.0.9 on our computer. Then in NetBeans we go to Tools | Options | Miscellaneous | Maven 2. Here we can define the path to our Maven 2.0.9 in the field External Maven Home.

After we have defined the path to Maven we can select a project and go to Project properties. In the Actions section we can select the checkbox Use external Maven for build execution.

September 5, 2008

Running the Cocoon 2.2 samples

Because Cocoon 2.2 now uses Maven we don't have to download the source code anymore. But if we want to see the samples web application we still do have to download the source code. We can checkout or export the source code from http://svn.apache.org/repos/asf/cocoon/trunk. We must have Maven 2.0.9 installed and in our path before we can continue. Now we can go the directory where we put the source code. We must first set the environment variable MAVEN_OPTS and give it the value -Xmx256m. This is to make sure Maven can compile all Cocoon sources. Then we type:

mvn -P allblocks install -Dmaven.test.skip=true

With this command all Cocoon code and samples are compiled. We don't need the tests to be executed for our sample web application. Once Maven is finished, we must go to the directory core/cocoon-webapp. We can now start the samples web application by typing:

mvn -P allblocks jetty:run

In our web browser we open http://localhost:8888/ and we get our sample application start screen. If we click on the samples link we get an overview page of all the samples of all the blocks of Cocoon 2.2.

Using Cocoon 2.2 without installing Cocoon

Cocoon is a very powerful XML publishing framework. With version 2.2 Cocoon switched from a "checkout the source, set your environment variables and run the build script" installation to building with Maven 2. And that makes life so much easier. We now only have to create a Maven project described by a pom.xml file. In this file we define our dependencies for Cocoon. So we don't need to download the source code and build it, we only have to define a Cocoon dependency. Maven will make sure the dependencies are downloaded if necessary and we are ready to go.

So if we don't have to download the source code anymore, how do we get Cocoon libraries in our project? Well that is the "magic" of Maven. The Cocoon libraries are available on the internet in Maven repositories. Maven will download the libraries from these repositories to our local computer. And once they are downloaded to our local computer we can use them for compiling and running our Cocoon application.

The following code is an example extract for a Cocoon application with the core dependencies defined:

<dependency>
 <groupId>org.apache.cocoon</groupId>
 <artifactId>cocoon-core</artifactId>
 <version>2.2.0</version>
</dependency>
<dependency>
 <groupId>org.apache.cocoon</groupId>
 <artifactId>cocoon-servlet-service-components</artifactId>
 <version>1.0.0</version>
</dependency>