Main | Next page »

Webtest wrapped as maven project

Jun 13 2009, 12:14:52 AM CEST in category [Java]

I have wrapped the canoo webtest project as a maven project. By default canoo webtest is shipped with ant script, only. My intention is to avoid downloading the webtest jars manually, but using the maven dependency, and downloading mechanism for downloading the webtest jars. The webtest jars are expressed as maven dependencies.

Directory Layout

The webtest maven project has following directory layout

etc/webtest
webtest resources except jars
lib
maven-ant-task jar
src/assembly
maven assembly for building a bin distribution of this project
src/dist
ant, and groovy scripts packed into the bin distribution
src/test/resource
webtestLog4j.properties log4j configuration
src/test/webtest
webtest scripts as ant, and groovy scripts
build.xml
ant script for running webtests using webtest dependencies defined in pom.xml
pom.xml
maven pom, goals for running webtest, and building bin distribution
build-maven-antrun.xml
ant script invoked from maven antrung plugin

Running Webtest

There are two ways to run webtest:

Launch mvn test, or run ant; both uses the webtest dependency expressed in the maven pom.xml.

"mvn test" uses internally maven antrun, and build-maven-antrun.xml to run the tests.

"ant" uses build.xml, and maven-ant-task jar for running the webtests.

Both ways store the webtest results in target/webtests-result.

Bin distribution

Running "mvn assebly:assembly" a zip file is created in the target directory. This zipfile stores all webtest jars in the directory lib. After unzipping the file, you can run the webtests by launching "ant".

Have fun!

Permalink

First Experience With Grape

Apr 20 2009, 08:34:40 PM CEST in category [groovy]

This blog summarizes my first experiences with groovy's Grab annotation.

As I have downloaded groovy 1.6.1, I have become aware of the Grab annotation.

Using Grab

I defined a simple groovy script which shall use apache's commons-lang abbreviate method from org.apache.commons.lang.StringUtils#abbreviate.

Thus I defined a script, like:


import org.apache.commons.lang.StringUtils

@Grab(group='commons-lang', module='commons-lang', version='2.4')

def strings = ['Hello', 'Groovy', 'AVeryLongWord!', 'A simple sentence']
strings.each { String aString ->
    println "$aString: ${StringUtils.abbreviate(aString)}"
}
        
Sadly this script, did not work, I experienced following exception stack trace:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed,
...\groovy\Grab1_1.groovy: 1: unable to resolve class org.apache.commons.lang.StringUtils
 @ line 1, column 1.
   import org.apache.commons.lang.StringUtils
   ^

1 error
        

Probably I have not read the doumentation close enough, put defining a method after the @Grab annotation, the problem, disappeared.

Thus the script becomes now:


import org.apache.commons.lang.StringUtils

@Grab(group='commons-lang', module='commons-lang', version='2.4')

def abbreviate(String s) {
    StringUtils.abbreviate( s, 10 )
}

def strings = ['Hello', 'Groovy', 'AVeryLongWord!', 'A simple sentence']
strings.each { String aString ->
    println "$aString: ${abbreviate(aString)}"
}
        

Running this script the commons-lang jar is downloaded, and the script prints:


Hello: Hello
Groovy: Groovy
AVeryLongWord!: AVeryLo...
A simple sentence: A simpl...
        

Reusing Maven Repository

I really like the @Grab feature, as it saves me from downloading additional jars manually. As I was using maven already, maven has downloaded some jars already into my local repository at the ~/.m2/repository directory. So I wonder if it is possible to tell grapes to reuse these jars.

The solution I use today, is reusing the maven jars from my local repository, grapes copies these jars over to the local grapes repository at ~/groovy/grapes. Thus this solution just saves me some bandwith and time, as accessing my local maven repository is surly faster than reaching out to the offical maven repositories at ibiblio.

The grapes documentation states that you can define the ivy settings by specifying ~/.groovy/grapeConfig.xml. So I created this file, which is by the way the default setting used by grapes:


<ivysettings>
  <settings defaultResolver="downloadGrapes"/>
  <resolvers>
    <chain name="downloadGrapes">
      <filesystem name="cachedGrapes">
        <ivy pattern="${user.home}/.groovy/grapes/[organisation]/[module]/ivy-[revision].xml"/>
        <artifact pattern="${user.home}/.groovy/grapes/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]"/>
      </filesystem>
      <!-- todo add 'endorsed groovy extensions' resolver here -->

      <ibiblio name="codehaus" root="repository.codehaus.org/" m2compatible="true"/>
      <ibiblio name="ibiblio" m2compatible="true"/>
      <ibiblio name="java.net2" root="download.java.net/maven/2/" m2compatible="true"/>
    </chain>
  </resolvers>
</ivysettings>
        

Now I wonder how to add my local maven repository, I defined an addtion ibiblio entry, defining as root my local maven repository, so the grapeConfig.xml became:


<ivysettings>
  <settings defaultResolver="downloadGrapes"/>
  <resolvers>
    <chain name="downloadGrapes">
      <filesystem name="cachedGrapes">
        <ivy pattern="${user.home}/.groovy/grapes/[organisation]/[module]/ivy-[revision].xml"/>
        <artifact pattern="${user.home}/.groovy/grapes/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]"/>
      </filesystem>
      <!-- todo add 'endorsed groovy extensions' resolver here -->

      <ibiblio name="local" root="file:${user.home}/.m2/repository/" m2compatible="true"/>

      <ibiblio name="codehaus" root="repository.codehaus.org/" m2compatible="true"/>
      <ibiblio name="ibiblio" m2compatible="true"/>
      <ibiblio name="java.net2" root="download.java.net/maven/2/" m2compatible="true"/>
    </chain>
  </resolvers>
</ivysettings>
        

By adding my local maven repository I'm able to reuse my local maven repository. You can add your local maven proxy, too by adding an additional ibiblio entry in the ~/.groovy/grapeConfig.xml file.

Have fun!

Permalink

First experiences with jasperreports, ireport, and barcode

Feb 25 2009, 12:13:05 AM CET in category [Java]

This blog summarizes my first experienced with iReport-nb-3.1.2.

As a first example I have created a report for the XML result of webtest.

spacer

Next I have created a report for the Junit XML.

spacer

As I become familiar with jasperreport, and iReport, I want to evaluate, if it is possible to print a barcode with jasper-report. As I have downloaded jasperreports-3.1.4, too, there are two barcode samples in the demo folder. I run them standalone, and I wanted to view them in the iReport tool.

Especially the barcode folder shows a nice sample. I open the BarcodeReport.jrxml in the iReport application, but there are some classloader problems, as there are some sample specific classes needed for this sample.

As iReport allows to defined extra jars in the Options|iReport dialog, I add two jars there.

The first jar is the barbecue-1.5-beta1.jar from the barcode/lib directory. The second jar - I have created from the barcode/build/component classes.

Next I restart iReport, and after the restart the additional jars are active, and I'm now able to view the barcodes as defined by the BarcodeReport.jrxml.

spacer

Have fun!

Permalink Comments [2]

Using unit-testing code using Netbeans' Repository class

Jan 28 2009, 12:08:42 AM CET in category [NetBeans]

This blog is about unit-testing using netbeans Repository. I'm using the solution described below on Netbeans 6.5.

In my netbeans plugin-project I have code like


        Repository r = Repository.getDefault();
        FileSystem fs = r.getDefaultFileSystem();
        FileObject root = fs.getRoot();
        FileObject baseFolder = FileUtil.createFolder(root, "nb-xpath/data");
        final String foName = "history.xml";
        FileObject historyFileObject = baseFolder.getFileObject(foName);
...
        File file = FileUtil.toFile(historyFileObject);

When you try to unit-test this code, the file instance is null.

Thus I read UsingFileSystemsMasterfs, and I installed the masterfs in the UnitTestLibary. By selecting "UnitTestLibraries|Add UnitTest Dependency", selecting "Show Non-API Modules, and searching for "masterfs", and selecting the Module "Master Filesystem".

The nbproject/project.xml results :


...
            </module-dependencies>
            <test-dependencies>
                <test-type>
                    <name>unit</name>
                    <test-dependency>
                        <code-name-base>org.netbeans.modules.masterfs</code-name-base>
                        <compile-dependency/>
                    </test-dependency>
                </test-type>
            </test-dependencies>
            <public-packages/>
...

But this does not help! The file instance is still null!

After examing the Repsitory sources, I came to the conclusion that if there is no Repository registered in META-INF/services, the MemoryFileSystem is used. Thus I need a way to register some repository class.

Thanks to InitializationOfDefaultLookup, MockServices can help.

I wrote a simple Repository implementation, and register it as Repository implementation to use:

The Repository implemenation for my test-case:


    public static final class MyRepositoryIOTempDir extends Repository {

        private static final long serialVersionUID = 20090127L;

        public MyRepositoryIOTempDir() {
            this(new LocalFileSystem());
        }

        private MyRepositoryIOTempDir(LocalFileSystem lfs) {
            super(lfs);
            // make the java.io.tmpdir the root of this lfs
            final String tmpDir = System.getProperty("java.io.tmpdir");
            assertNotNull(tmpDir);
            File rootFile = new File(tmpDir);
            assertTrue(rootFile != null);
            assertTrue(rootFile.canRead());
            assertTrue(rootFile.canWrite());
            assertTrue(rootFile.isDirectory());
            try {
                lfs.setRootDirectory(rootFile);
            } catch (Exception ex) {
                AssertionError ae = new AssertionError("Cannot set root directory");
                ae.initCause(ex);
                throw ae;
            }
        }
    }

My test-case setUp registers this class like:


    @Before
    public void setUp() {
        MockServices.setServices(MyRepositoryIOTempDir.class);
        // assert that for lookup(Repository.class) MyRepositoryIOTempDir is returned
        final Repository repositoryInstance = Lookup.getDefault().lookup(Repository.class);
        assertTrue(repositoryInstance instanceof MyRepositoryIOTempDir);
    }

Now my tests can run the above code, and the file instance is not null!

Now, that I removed the Master Filesystem dependency from the Unit Test Libraries, my test-cases still work, so it seems to me that when you use File instances retrieved via Repository, you don't need the masterfs test dependency, so far.

Have fun!

Permalink

Xhtmlrenderer plus Groovy's SwingBuilder

Oct 29 2008, 12:15:47 AM CET in category [groovy]

Today I integrated groovy's SwingBuilder into xhtmlrenderer.

Xhtmlrenderer is a pure-Java library for rendering arbitrary well-formed XML (or XHTML) using CSS 2.1 for layout and formatting, output to Swing panels, PDF, and images.

I downloaded the release flyingsaucer-R7final, and integrated Groovy's SwingBuilder as object tag element. I used the ElementFactory, as outlined in the svg-demo delivered as xhtmlrenderer demo; now I can write groovy SwingBuilder scripts inside the XHTML page, like:


...
            </p>
            <h2>header.one.
            <div style="border: 1px solid red; margin: 15px; text-align: left;">
                <object type="text/groovy"><![CDATA[
import net.miginfocom.swing.MigLayout
import net.miginfocom.layout.LC
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC

/**
 * A script expected to run in SwingBuilder#build
 *
 * It demonstrates defining the layout using LC, AC objects.
 */
final LC layC = new LC().fill().wrap();
final AC colC = new AC().align("right", 0).fill(1, 3).grow(100, 1, 3).align("right", 2).gap("15", 1);
final AC rowC = new AC().index(6).gap("15!").align("top").grow(100, 8);

final def migLayout = new MigLayout( layC, colC, rowC )
panel(layout: migLayout) {
    label("Last Name")
...

The resulting panel looks, like: spacer

Well, that's just the first step, I still face some problems with layout the groovy panel, according its parent panel. You will notice the problem in the screenshot, as the grey area is smaller then the div's red border.
But maybe I'll find some time to solve this, too.


Have fun!

Permalink Comments [1]

Webapplications using shared classloader

Oct 05 2008, 05:00:00 AM CEST in category [Java]

Discuss the possibilities to reuse jars among various web applications. [Read More]

Permalink Comments [1]

Grails Deployment Issues

Oct 04 2008, 11:52:44 PM CEST in category [grails]

I experienced an interesting problem with a grails-application.

The operating team noticed me that the grails-web application, is not deployed, after a restart of the tomcat application server, and the db-server.
After inquiring the details about the restart sequence I came to the conclusion that following scenario happened:

  1. The machine hosting tomcat, and the db was rebooted
  2. The tomcat application server was restarted
  3. The grails-application tried to restart, but failed as the db was not up and running, yet
  4. The db was restarted

As the db was started after tomcat the grails was not started successfully inside of tomcat.

The operating team launched the tomcat-manager, and restarted the grails-application manually, and voila the grails-application started successfully.

Now I tried to find a solution that the operating team does not have to restart the grails-application manually.

This leads me to the question what db-accesses are performed by a grails-application, when the grails-application is started.

I come to the following two db-accesses:
  1. If now hibernate-dialect is specified explicitly, grails looks up the jdbc meta-data to find the database, to set the hibernate dialect
  2. Regardless of the hibernate dialect, grails accesses the jdbc meta-data again to set the lob-handler

Now if the grail-application shall succeed even if no db is available, you have to avoid these two db-access, as they surely fails if no db is available, yet.

You can avoid the first db-access by specifying the hibernate dialect, explicitly in the grails-app/conf/DataSource.groovy, like:
dataSource {
    pooled = true
    driverClassName = "org.hsqldb.jdbcDriver"
    username = "sa"
    password = ""

   dialect = 'org.hibernate.dialect.HSQLDialect'
}

The second db-access is hard-coded into grails org.codehaus.groovy.grails.orm.hibernate.support.SpringLobHandlerDetectorFactoryBean. To avoid this db-access you have to replace this class by your own class, and configure it as spring-bean in grails-app/conf/resource.xml, or grails-app/conf/resource.groovy.

I wrote a simple preconfigurable MySpringLobHandlerDetectorFactoryBean :

package org.mycompany.orm.hibernate.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.jdbc.support.lob.OracleLobHandler;

/**
 * A simple LobHandler detector which does not access the dataSource for
 * detecting the appropriate LobHandler.
 * <p>
 * You must set the dbname explicitly, this has the advantage that no
 * db-access is needed at startup time. Hence the application starts even if
 * the database is not available at startup-time.
 * <p>
 * You this class by configuring a spring bean instance having the
 * id <code>lobHandlerDetector</code> in the grails spring configuration
 * <code>conf/spring/resources.xml</code>, like:
 * <code><pre>
 * <bean id="lobHandlerDetector" class="org.mycompany.orm.hibernate.support;.orm.hibernate.support.MySpringLobHandlerDetectorFactoryBean">
 * <property name="databaseProductName" value="Oracle"/>
 * </bean>
 * </pre></code>
 * @author HuberB1
 */
public class MySpringLobHandlerDetectorFactoryBean implements FactoryBean, InitializingBean {

    private final static Log log = LogFactory.getLog(MySpringLobHandlerDetectorFactoryBean.class);
    private static final String ORACLE_DB_NAME = "Oracle";
    private LobHandler lobHandler;
    private String databaseProductName;

    public void setDatabaseProductName(String databaseProductName) {
        this.databaseProductName = databaseProductName;
    }

    public Object getObject() throws Exception {
        return this.lobHandler;
    }

    public Class getObjectType() {
        return LobHandler.class;
    }

    public boolean isSingleton() {
        return true;
    }

    public void afterPropertiesSet() throws Exception {
        if (this.databaseProductName == null) {
            throw new IllegalStateException("DatabaseProductName is not set!");
        }

        final String dbName = this.databaseProductName;
        log.info("Using dbName " + dbName);

        if (ORACLE_DB_NAME.equals(dbName)) {
            this.lobHandler = new OracleLobHandler();
        } else {
            this.lobHandler = new DefaultLobHandler();
        }

    }
}

I added a bean configuration for an Oracle DB in conf/spring/resourcex.xml:

<bean id="lobHandlerDetector" class="org.mycompany.orm.hibernate.support;.orm.hibernate.support.MySpringLobHandlerDetectorFactoryBean">
<!--property name="databaseProductName" value="Other"/-->
<property name="databaseProductName" value="Oracle"/>
</bean>

Now with this simple MySpringLobHandlerDetectorFactoryBean, and specifying the hibernate dialect explicitly. The grails-application starts successfully even if no db is available. Of course the user will not be able to view any db-content, as long as the db is not available.

But the operating team does not have to fiddle around with any restart-sequence, and they don't have to restart the grails-application manually, neither.

Have fun!

Permalink

EJB3-SpringBeanAutowiringInterceptor

Oct 04 2008, 09:33:03 PM CEST in category [Java]

Some notes about using springframework's SpringBeanAutowiringInterceptor in an mdb, triggered by Quartz [Read More]

Permalink

Extending groovy's SwingBuilder2

Apr 22 2008, 11:36:50 PM CEST in category [groovy]

In my previous blog i have sketched some ideas for extending SwingBuilder. Today I'd like to introduce a small extension.

SwingBuilder offers already an items attribute for the combobox. Sadly this attribute is missing for the list node.

But it is not too complicate to extend SwingBuilder to make the items attribute available for the list node, too.

Fist create a new factory using the already existing groovy.swing.factory.ComboBoxFactory as starting template:


package org.huberb.groovy.swing.factory

import javax.swing.JList

/**
 * Create a JList, and handle the optional items attribute.
 * 
 * @author HuberB1
 */
public class ListFactory extends AbstractFactory {
    
    public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException {
        FactoryBuilderSupport.checkValueIsNull(value, name);
        //TODO expand to allow the value arg to be items
        Object items = attributes.remove('items');
        if (items instanceof Vector) {
            return new JList((Vector) items);
        } else if (items instanceof List) {
            List list = (List) items;
            return new JList(list.toArray());
        } else if (items instanceof Object[]) {
            return new JList((Object[]) items);
        } else {
            return new JList();
        }
    }
}

Next you have to register this factory, In fact you are overriding the original list registration.


import groovy.swing.SwingBuilder
def swing = new SwingBuilder()
swing.registerFactory( "list", new ListFactory() )

Now you can use swing for building lists like:


def panel = swing.panel() {
  scrollPane() {
    list( items: ['A', 'B','C'] )
  }
}

Have fun!

Permalink Comments [1]

Extending groovy's SwingBuilder

Apr 13 2008, 11:19:30 PM CEST in category [groovy]

Groovy's SwingBuilder builds swing user interfaces. It is simple, and has some nice extension points.

SwingBuilder provides all the swing's components, like JButton, JTextField, JSpinner, etc. So what's missing?

By the time I'm using SwingBuilder I have missed following features:

  • Easy integration of internationalized text
  • Easy linking JLabel using the labelFor method, and mnemonics

In the following sections I will describe each feature and sketch the implementation.

Internationalized Text

Using internationalized text in SwingBuilder you have to provide the internationalized text like:


            ResourceBundle rb = ResourceBundle.getBundle( "foo.bar.Bundle" )
            swingBuilder.panel() {
              button( text: rb.getString('someKey') )
              label( text: rb.getString('someLabelKey' )
              ...
        

Beside typing rb.getString over, and over again, it fails with a MissingResourceException if the specified key is not found.

The solution I have implemented so far, defines the attributes i15dText, and i15dTitle for specifying the message key, and a new closure-name i15dMessageSource for defining the resource bundle

Thus the above snippet changes to:


            ResourceBundle rb = ResourceBundle.getBundle( "foo.bar.Bundle" )
            swingBuilder.panel() {
              i15dMessageSource( resourceBundle: 'foo.bar.Bundle' )
              button( i15dText: 'someKey' )
              label( i15dText: 'someLabelKey' )
              ...
        

I think this is quite an improvment, regarding readability. Moreover the i15d* attribute implementations return the key as-is if the key is not defined in the resource bundle.

The implementation of the i15dMessageSource is quite simple to store the specified resource bundle as builder variable named i15dMessageSource.

The i15d* attribute implementation peeks the resource bundle from the builder variable, and retrieves the message. In case of i15dText, the message is set as new text attribute; in case of i15dTitle, the message is stored as new title attribute.

Linking JLabel, and mnemonics

Swing's JLabel has a method setLabelFor(JComponent). The javadoc explains:

Set the component this is labelling. Can be null if this does not label a Component. If the displayedMnemonic property is set and the labelFor property is also set, the label will call the requestFocus method of the component specified by the labelFor property when the mnemonic is activated.

SwingBuilder makes it not that easy to use this feature

The snippet below defines the label first, and gives it an id, next id defines the textfield. Finally it links the label with the textfield, by using the defined ids.


            label( id: 'myLabel', text: 'XXX', displayedMnemonic: 'X' )
            textField( id: 'myTextField', columns: 15)
            myLabel.labelFor = myTextField
        

I think it would be easier to use a snippet like:


            labelForGroup {
                label( id: 'l0', i15dText: 'View1.firstName')
                textField( id: 'tf0' )
            }            
        

Alternativly if you use a layout manager like MigLayout you can even skip the explicit label definition at all:


            textField( i15dLabel: 'View.firstName' )
        

The labelForGroup creates a node-list as dumm

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.