Archive

Archive for the ‘Java Tools’ Category

Enhance your javadoc with ULMGraph

May 24, 2010 Leave a comment

We can’t live without Javadoc, but even if it useful, it’s not complete. One missing thing is UML within the Javadoc.

To add UML to your Javadoc, is quite simple. You need to add Graphviz into your maven build.

First you need to download and install Graphviz. Go there Graphviz

After that you should add the variable GRAPHVIZ_HOME (that point to the installation folder) into your system.

The last step is to add the plugin into your pom.

Add the lines in bold.


<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-javadoc-plugin</artifactId>
  <version>2.6.1</version>
  <configuration>
    <links>
      <link>http://java.sun.com/javase/6/docs/api/</link>
    </links>
    <detectOfflineLinks />
    <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
    <!--
      use this line or use the variable GRAPHVIZ_HOME
      <docletPath>/path/to/UmlGraph.jar</docletPath>
    -->
    <docletArtifact>
      <groupId>org.umlgraph</groupId>
      <artifactId>doclet</artifactId>
      <version>5.1</version>
    </docletArtifact>

    <additionalparam>-operations</additionalparam>
    <additionalparam>-qualify</additionalparam>
    <additionalparam>-types</additionalparam>
    <additionalparam>-visibility</additionalparam>
    <additionalparam>-collpackages</additionalparam>
    <show>private</show>
  </configuration>
</plugin>

With that you will have nice UML into your javadoc. I hope that help.

A simplier way is to add that instead in the pom.xml


<plugin>
  <artifactId>maven-javadoc-plugin</artifactId>
  <configuration>
              <show>package</show>
              <version>true</version>
              <javadocVersion>${source.version}</javadocVersion>
              <links>
                  <link>http://java.sun.com/javase/6/docs/api/</link>
                  <link>http://java.sun.com/products/servlet/2.5/docs/servlet-2_5-mr2/</link>
                  <link>http://joda-time.sourceforge.net/api-release/</link>
                  <link>http://findbugs.sourceforge.net/api/</link>
                  <link>http://tomcat.apache.org/tomcat-6.0-doc/api/</link>
                  <link>http://jetty.mortbay.org/jetty/jetty-6/apidocs/</link>
                  <link>http://download.eclipse.org/jetty/stable-7/apidocs/</link>
                  <link>https://grizzly.dev.java.net/nonav/apidocs/</link>
              </links>          <source>1.6</source>
     <code>javadoc:aggregate</code>
      <code>javadoc:test-aggregate</code>
    <doclet>gr.spinellis.umlgraph.doclet.UmlGraphDoc</doclet>
    <docletArtifact>
      <groupId>gr.spinellis</groupId>
      <artifactId>UmlGraph</artifactId>
      <version>4.6</version>
    </docletArtifact>
    <additionalparam>
      -inferrel -inferdep -quiet -hide java.*
      -collpackages java.util.* -qualify
      -postfixpackage -nodefontsize 9
      -nodefontpackagesize 7
    </additionalparam>
  </configuration>
</plugin>
Categories: Java Tools Tags: , , , ,

Extends javadoc with custom tag

May 24, 2010 Leave a comment

I would like to show you how you could extend your javadoc to include samples directly into the javadoc without extra work.

What I don’t like about javadoc is the lack of code sample. Something is can be hard to find the starting point of a new framework.

Let’s show a example, it will be easier to understand, and so simple.


/**
*
* This in a javadoc with a custom tag @example.
*
* @author Sebastien Dionne
*
* @example.
* <pre>
*
* SSDPControler controler = new SSDPControler();
*
* // sends messages each 30 seconds.
* controler.getPeriodicMessageSender().setDelay(30000);
*
* controler.setPeriodicMessageSender(new SSDPPeriodicMessageSender(null) {
* @Override
* public List<String> returnHellos() {
* List<String> list = new ArrayList<String>();
*
* list.add("hello1");
* list.add("hello2");
*
* return list;
* }
* });
* controler.start();
* </pre>
*/

In this example, we used a custom tag @example. The result will look like this.


...
public class SSDPControler
extends Object
implements ISSDPControler
...
This in a javadoc with a custom tag @example.

Example :

SSDPControler controler = new SSDPControler();

// sends messages each 30 seconds.
controler.getPeriodicMessageSender().setDelay(30000);

controler.setPeriodicMessageSender(new SSDPPeriodicMessageSender(null) {
@Override
public List<String> returnHellos() {
List<String> list = new ArrayList<String>();

list.add("hello1");
list.add("hello2");

return list;
}
});
controler.start();

There is a thing that you need to know to avoid surprises :

Javadoc tool will cut the custom tag as soon as it detect another annotation, so don’t forget to convert to HTML code like
@ : become : “&”#64;

To acheive that you need to add little config into your pom. Add the lines in bold.


<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.6.1</version>
<configuration>
<links>
<link>http://java.sun.com/javase/6/docs/api/</link>
</links>
<detectOfflineLinks/>

<tags>
<tag>
<name>example.</name>
<placement>aoptcmf</placement>
<head>Example :</head>
</tag>
</tags>

</configuration>
</plugin>

Categories: Java Tools Tags: ,

Read web.xml with one line of code Part 2

May 24, 2010 Leave a comment

I did a <a href=”http://weblogs.java.net/blog/survivant/archive/2008/12/read_webxml_wit.html”>previous post</a> about how to do it with XMLBean or JABX, but it was more an example how to do it. This time is the real deal.

I used JABX to generate the java classes from the schemas and use that to parse the web.xml.

The result is a simple class : WebAppLoader that will load the web.xml.

Here a example :

WebappLoader webappLoader = new WebappLoader();
WebApp webapp = webappLoader.load(“/web-2.2.xml”);

The object WebApp contains all the infos extracted from the web.xml. The representation is based on webapp 3.0.

you can get the source code from my repository : <a href=”http://kenai.com/projects/sebastiendionne/sources/repository/show/dtd-schemas-generator”>http://kenai.com/projects/sebastiendionne/sources/repository/show/dtd-schemas-generator</a>

Categories: Java Tools, Web Tags: , ,

JAXB : web.xml : dtd and xsd classes generator

May 24, 2010 Leave a comment

I created a little demo to show how easy it can be to create a kit of classes from DTD and XSD using Maven and JAXB.

To generate from XSD schemas

In your pom.xml, you will have to add this.


<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<!-- if you want to put DTD somewhere else
<schemaDirectory>src/main/jaxb</schemaDirectory>
-->
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2-commons</groupId>
<artifactId>property-listener-injector</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

The important thing to know is that you have to generate your classes with one schema each time. If you put webapp schemas 2.2 and 2.3 in the same time,
you will obtain errors. Be sure to include all the files related to your webapp schema to generate your java classes.

Example : webapp 2.4 need
web-app_2_4.xsd
j2ee_1_4.xsd
jsp_2_0.xsd

You can even do some customization with a config file named : domain.jaxb (/src/main/resources).

To generate from DTD

In your pom.xml, you will have to add this.


<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<!-- if you want to put DTD somewhere else
<schemaDirectory>src/main/jaxb</schemaDirectory>
-->
<extension>true</extension>
<schemaLanguage>DTD</schemaLanguage>
<schemaIncludes>
<schemaInclude>*.dtd</schemaInclude>
</schemaIncludes>
<bindingIncludes>
<bindingInclude>*.jaxb</bindingInclude>
</bindingIncludes>
<args>
<arg>-Xinject-listener-code</arg>
</args>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2-commons</groupId>
<artifactId>property-listener-injector</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

The DTD generation is the same pattern as XSD. The principal differences are in the pom.xml

You can download a complete project that use webapp xsd and dtd to parse any web.xml. It could be useful when you want to keep it simple :)

You can browse the code from : my Kenai repository

Categories: Java Tools, Web Tags: , ,

Template Code Generator Part 2 : FreeMarker

May 24, 2010 1 comment

In my previous post, I covered Apache Velocity, Eclipse JET/JET2.
I got a suggestion to look the framework FreeMarker.

FreeMarker look like Velocity. You can even find converters : Velocity -> FreeMarker.
I’ll describe in this part how to create the same output but using FreeMarker.

Take a look at the generate method.

SampleFreeMarker.java


public void generate() {

try {
Configuration cfg = new Configuration();

cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);

Template tpl = cfg.getTemplate("./templates/GalleryTemplateFreeMarker.ftl");
OutputStreamWriter output = new OutputStreamWriter(System.out);

Map root = new HashMap();

root.put("list", mediaFileList);

tpl.process(root, output);

} catch (Exception e) {
s_logger.error("generate", e);
}

}


Let’s compare to the Velocity implementation.

SampleVelocity.java


public void generate() {

try {
Velocity.init();

VelocityContext context = new VelocityContext();
context.put("list", mediaFileList);

Template template = Velocity.getTemplate("./templates/GalleryTemplateVelocity.vm");

BufferedWriter writer = writer = new BufferedWriter(new OutputStreamWriter(System.out));

if (template != null)
template.merge(context, writer);

/*
* flush and cleanup
*/

writer.flush();
writer.close();

} catch (Exception e) {
s_logger.error("generate", e);
}

}


The main difference is with FreeMarker you need to create a root HashMap and put the objects in it.
With Velocity you put the objects within the context.

Now see the FreeMarker template.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<!-- include the required JavaScript file -->
</head>

<body>
<div align="center">
<table width="80%">
<#assign maxItembyRow = 2>
<#assign index = 0>
<#assign count = 0>
<#assign newLine = true>
<#foreach mediaFile in list>
<#if newLine>
<tr>
<#assign newLine = false>
</#if>
<td>
<a href="${mediaFile.name}" id="player${count}">
</a>
</td>
<#if index < maxItembyRow-1>
<#assign index = index + 1>
<#else>
<#assign index = 0>
<#assign newLine = true>
</#if>
<#if newLine>
</tr>
</#if>
<#assign count = count + 1>
</#foreach>
</tr>
</table>
</div>
</body>
</html>

It’s almost the same as Velocity except that the syntax change a little.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<!-- include the required JavaScript file -->
</head>

<body>
<div align="center">
<table width="80%">
#set( $maxItembyRow = 2)
#set( $index = 0)
#set( $newLine = true)
#foreach( $mediaFile in $list )
#if( $newLine )
<tr>
#set( $newLine = false)
#end
#if( $index<$maxItembyRow )
<td><a href="$mediaFile.name" id="player$velocityCount">
</a>
</td>
#set($index = $index+1)
#else
#set($index = 0)
#set( $newLine = true)
#end
#end
</tr>
</table>
</div>
</body>
</html>

What I didn’t like about FreeMarker is the lack of documentation.
There had good javadoc, but something you need more than that like “real life” samples.
The source code can be downloaded here.

Categories: Java Tools, Web Tags:

Template Code Generator : Apache Velocity – JET – JET2

May 24, 2010 2 comments

I wanted to use a template as input for my Code Generator, but the problem was to find one that worked in a stand alone mode, not a web based one. In my research a found few that do what I wanted. Apache Velocity and Eclipse JET/JET2.

I’ll explain in details theses Template Code Generator with a little application. I’ll create a web page as output.

Here the specs for the demo.

– The web page template should create a entry for each items in the list received in parameter
– The list could be created dynamically (so the number of items is not fixed)

Before starting to explain how to do it with theses frameworks, I’ll use a class : MediaFile that contains the info on a media file. I’ll create a html that display 2 items by row and just to kept the demo simpler, I’ll use a even number of items.

Take a look at the html that I would like to generate.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<!-- include the required JavaScript file -->
</head>

<body>
<div align="center">
<table width="80%">
<tr>
<td>
<a href="name1" id="player1">name1
</a>
</td>
<td>
<a href="name2" id="player2">name2
</a>
</td>
</tr>
<tr>
<td>
<a href="name3" id="player3">name3
</a>
</td>
<td>
<a href="name4" id="player4">name4
</a>
</td>
</tr>
<tr>
<td>
<a href="name5" id="player5">name5
</a>
</td>
<td>
<a href="name6" id="player6">name6
</a>
</td>
</tr>
</table>
</div>
</body>
</html>

I didn’t put <td> and <a> on the same line on purpose. The reason it because it’s easier to show the format’s problems with a code generator. I’ll explain it in more details later.

The MediaFile’s list will be populated like that :


public void init() {

mediaFileList = new ArrayList();

for (int i = 0; i < 5; i++) {
MediaFile mediaFile = new MediaFile();
mediaFile.setName("name" + i);
mediaFile.setFps("29.997");
mediaFile.setDuration("12:45");
mediaFile.setCodec("H264");
mediaFile.setWidth("320");
mediaFile.setHeight("240");
mediaFile.setStreamSize("2 Megs");

mediaFileList.add(mediaFile);
}

}

Apache Velocity

I known the framework by name, but I never used before. I have to say that it wasn’t too hard to get it to work. Apache have a good documentation for Velocity API. If you are not familiar with this API, go take a look at the user guide http://velocity.apache.org/engine/devel/user-guide.html

Apache Velocity use it’s own language, but it’s pretty simple. What I didn’t like at first was the lack of nested loop.

I wanted to do something like that (using the iterator in a nested loop):

 
for(Iterator it = list.iterator();it.hasNext();){
...
for(int i=0;i<2;i++){
Object element = iterator.next();
...
}
...
}

I’m not a expert in Velocity, but after looking around on the web, I didn’t find a simple answer, so I had to do it another way. The problem with a template like below, is that it could become hard to read, because if you let some blank lines for the readiness of the code, theses lines will appear in the generated code.

Let’s take a look at the template in Velocity that will give the desirable layout.

GalleryTemplateVelocity.vm

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<!-- include the required JavaScript file -->
</head>

<body>
<div align="center">
<table width="80%">
#set( $maxItembyRow = 2)
#set( $index = 0)
#set( $newLine = true)
#foreach( $mediaFile in $list )
#if( $newLine )
<tr>
#set( $newLine = false)
#end
#if( $index<$maxItembyRow )
<td><a href="$mediaFile.name" id="player$velocityCount">$mediaFile.name
</a>
</td>
#set($index = $index+1)
#else
#set($index = 0)
#set( $newLine = true)
#end
#end
</tr>
</table>
</div>
</body>
</html>

After that we need the main class that will call the template, and populate the list of MediaFile. If you want to pass variables to Velocity template, you have to put them in the context, like you do for a HttpRequest.

SampleVelocity.java


public void generate() {

try {
Velocity.init();

VelocityContext context = new VelocityContext();
context.put("list", mediaFileList);

Template template = Velocity.getTemplate("./templates/GalleryTemplateVelocity.vm");

BufferedWriter writer = writer = new BufferedWriter(new OutputStreamWriter(System.out));

if (template != null)
template.merge(context, writer);

/*
* flush and cleanup
*/

writer.flush();
writer.close();

} catch (Exception e) {
s_logger.error("generate", e);
}

}

Eclipse JET

JET can be used as a template code generator. It’s was made to run within Eclipse, but you can include two Eclipse jar and that will do the trick. JET is based on the JSP syntax. If you have done scriplet in JSP, you won’t find that hard to use.

The main differences between JEt and Velocity, is that JET only take 1 parameter in the template. Yes, only one… You can pass that by creating a java class that will contains all your variables. Yes it’s ugly, but when you know it, it’s not hard to use.

The second big difference is that JET framework compile the template into a java class, and you use this class in your application.

Take a look at the JET template (look like a JSP with the 2 first lines that you related to JET.

GalleryTemplateJet.jet


<%@ jet package="ca.sebastiendionne.gallery.jet" class="GalleryHtmlJET" imports="java.util.* ca.sebastiendionne.gallery.model.*" %>
<% List<MediaFile> mediaFileList = (List<MediaFile>) argument; %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<!-- include the required JavaScript file -->
</head>

<body>
<div align="center">
<table width="80%">
<%

int maxItembyRow = 2;
int index = 0;

for (Iterator<MediaFile> iterator=mediaFileList.iterator();iterator.hasNext();) {%>
<tr>
<%
for(int j=0;j<maxItembyRow;j++){
MediaFile element = iterator.next();
%>
<td>
<a href="<%=element.getName()%>" id="player<%=index%>"><%=element.getName()%>
</a>

<%=element%>

</td>
<%
index++;
}%>
</tr>
<%
}
%>
</table>
</div>
</body>
</html>

That will generate the java class : ca.sebastiendionne.gallery.jet.GalleryHtmlJET

and you use it like that :


public void generate(){

GalleryHtmlJET galleryJET = new GalleryHtmlJET();

String html = galleryJET.generate(mediaFileList); // the argument is the list

System.out.println(html);
}

The method generate() is simpler and smaller than Velocity, but in other hands… The formatting is more tricky with JSP syntax. Try for fun to look at a html page generated with scriptlet. It’s will works, but there will be lot of blank lines and it won’t have a nice indentation. That is important when you want to generate java class. You don’t want to pass a formatter after the generating job.

I had used JET few months ago for my application IbatisGen. I think that it took more time to get the indentation right that coding the rest of the application.

JET have some limitations like the one argument, but that JET2 fixed that.

Eclipse JET2

JET2 differs than JET1 in different ways. JET1 can be used outside Eclipse, but not JET2.

JET2 can be easily use in Eclipse if you have a xml file as input, but if you don’t have a fixed input like this demo. It’s more complicated.
You will have to create a Eclipse Plugin that will be able to handle dynamic input.

So, if you don’t want to create a Eclipse Plugin, stop here, take JET or Velocity.

I won’t cover how to create the JET2 Plugin, you can find a good sample here http://www.eclipse.org/articles/Article-JET2/jet_tutorial2.html, but I’ll show you how to use a xml input file.

The JET2 templates can you JSP and JSLT syntax like.

sample.xml


<app class="Car">
<property name="model" type="String" initial="Hybrid" />
<property name="horsepower" type="int" initial="140" />
<property name="spareTires" type="boolean" initial="true" />
</app>

The main template (like the java class that contains the main() )

main.jet


<%@taglib prefix="ws" id="org.eclipse.jet.workspaceTags" %>
<c:if test="isVariableDefined('org.eclipse.jet.resource.project.name')">
<ws:file template="templates/testCar.jet" path="{$org.eclipse.jet.resource.project.name}/dump2.xml"/>
</c:if>

testCar.jet (the template that will generate the code from sample.xml) (We are creating a getter/setter class)


<%@taglib prefix="ws" id="org.eclipse.jet.workspaceTags" %>
class <c:get select="/app/@class" /> {
<c:iterate select="/app/property" var="p" >
private <c:get select="$p/@type" /> <c:get select="$p/@name" />;
</c:iterate>

public <c:get select="/app/@class" />() {
<c:iterate select="/app/property" var="p" >
this.<c:get select="$p/@name" /> = <c:choose select="$p/@type" >
<c:when test="'String'">"<c:get select="$p/@initial" />"</c:when>
<c:otherwise><c:get select="$p/@initial" /></c:otherwise>
</c:choose>
;
</c:iterate>
}

<c:iterate select="/app/property" var="p" >
public void set<c:get select="camelCase($p/@name)" />(<c:get select="$p/@type" /> <c:get select="$p/@name" />) {
System.out.println("In set<c:get select="camelCase($p/@name)" />()");
this.<c:get select="$p/@name" /> = <c:get select="$p/@name" />;
}

public <c:get select="$p/@type" /> get<c:get select="camelCase($p/@name)" />() {
System.out.println("In get<c:get select="camelCase($p/@name)" />()");
return <c:get select="$p/@name" />;
}

</c:iterate>
}

To run all that you need to “Run as … JET Transformation” in Eclipse.

I won’t go into details, but here what the generate() method should look like if you want to handle a dynamic input.


public void generate(){

GalleryHtmlJET galleryJET = new GalleryHtmlJET();

JET2Context context = new JET2Context(null);
context.setVariable("list", mediaFileList);

JET2Writer out = new BodyContentWriter();

context.setTagFactory(new TagFactoryImpl(context));

... the line for the Plugin
galleryJET.generate(context, out);
... end of the Plugin stuff
System.out.println(out);

}

It’s look really like Apache Velocity at this point.

If I had to choose between them, I don’t know if I would choose Velocity or JET. Both of them could work in a plugin (Eclipse or Netbean), support Ant task.

What do you think ? Do you know some framework that you want to share with us ?
You can download the source code here : Velocity/JET and JET2.

Categories: Java Tools, Web Tags: , , ,

Tools for debugging html/css/javascript

May 24, 2010 Leave a comment

There are so many browsers and version of theses browsers that I became harder to create HTML that will run on all the possibles combinations.

You need the appropriate tools to help you to debug. There are few application and plugins you need to try :

- Firebug for Firefox (https://addons.mozilla.org/fr/firefox/addon/1843) : to debug everything : html, css, javascript, ajax …

- Markup Validation Service (http://validator.w3.org/) : to validate your (x)html page.

- Internet Explorer Developer Toolbar (http://www.microsoft.com/downloads/details.aspx?FamilyID=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en) :

Microsoft Firebug alternative : to debug html, css …

- Install multiple versions of IE on your PC (http://tredosoft.com/Multiple_IE) : Install more than one version of IE on your PC.

- CSS Formatter and Optimiser (http://floele.flyspray.org/csstidy//css_optimiser.php?lang=en) : a nice CSS formatter and optimiser.

-I also recommend trying IETester (http://www.my-debugbar.com/wiki/IETester/HomePag) which allows you to open browser tabs with individual IE engines.

I like this even a little bit better than MultipleIE,

which is a very cool package but caused me some problems while IETester just ran out of the box.

Theses are the tools that I’m using to debug the main page of Glassfish. Even with that.. it’s hard :)

Categories: Java Tools, Web

Maven Test Coverage : Cobertura and Surefire working

May 24, 2010 Leave a comment

I wanted to add Cobertura to Grizzly project within the pom file for Maven, but I got errors at first. I follow the procedure describe on Cobertura website,

but it was lacking of a complete example. Cobertura will instrument your classes and you need to run tests to get a test coverage.

You need to pass the path of these instrumented classes to the plugin that will run the tests(in the same pattern for ant and junit).

For my project I’m using Surefire. I created a file pom2.xml for Grizzly.

Put this file in the root of the project and call it like that : mvn -f pom2.xml cobertura:cobertura

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.sun.grizzly</groupId>
<artifactId>grizzly-project</artifactId>
<version>1.9.0-SNAPSHOT</version>
<relativePath>pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.sun.grizzly</groupId>
<artifactId>grizzly-framework</artifactId>
<version>${grizzly-version}</version>
<name>grizzly-framework</name>
<url>https://grizzly.dev.java.net</url>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemProperties>
<property>
<name>net.sourceforge.cobertura.datafile</name>
<value>target/cobertura/cobertura.ser</value>
</property>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</reporting>
</project>

I put explicit version of the plugins. You can remove that to use the latest version.

Categories: Java Tools Tags: , ,

Read web.xml with one line of code

May 24, 2010 Leave a comment

I needed to parse a web.xml for a sample for Grizzly and I wanted to find a way to have something that I can reuse later. You don’t have to do it by hand. There are tools out there to do it for you.

One of them is XMLBeans from Apache group and more popular is JAXB. For JDK 1.4 ,I used XMLBeans and if you have JDK6 JAXB will reduce the dependencies and will be more smaller. I’ll show you how to use theses two API.

XMLBEANS

What I like about this tool is that I can generate Java classes from a xsd within seconds using Ant.

I want to show you how to obtain a Class that will contains a web.xml loaded with only one line of code :)

Let’s start by downloading XMLBeans. I’ll skip to the folder structure I’ll use for this demo.

lib/ : Where you put the XMLBeans libraries
schemas/ : Where you put the xsd
build.xml

Download build.xml from here.

I use the schemas from Glassfish sources : glassfish/appserv-commons/schemas

You don’t have to copy all the files. Copy just the main schemas and Ant will download the missing schemas.

For my demo I used theses files :

schemas/j2ee_1_4.xsd
schemas/jsp_2_0.xsd
schemas/web-app_2_4.xsd

you just have to launch the ant task with this command :

ant -autoproxy

that will generate a jar file and the java source for theses schemas.

Now.. How do we load a web.xml within our Java application ?

#1 – Include the jar file : j2ee_schemas-xmlbeans.jar into your project
#2 – Create the root class of your schema and load the web.xml

WebAppDocument webAppDocument = WebAppDocument.Factory.parse(webxmlFile);

After that .. It’s up to you, webAppDocument contains all the config from web.xml.

JAXB

You will need the librairies for the compilation, but after that if you use JDK6, you can remove them, because JAXB is include in JDK6.

#1 – To generate the schemas, you use ant.
#2 – Include the jar file : j2ee_schemas-jaxb.jar into your project
#3 – Create the root class of your schema and load the web.xml

JAXBContext jc = JAXBContext.newInstance(“ca.sebastiendionne.jaxb.xsd”);

// create an Unmarshaller
Unmarshaller u = jc.createUnmarshaller();

JAXBElement root = (JAXBElement)u.unmarshal( new FileInputStream(“./web.xml”) );

WebAppType webAppType = (WebAppType)root.getValue();

It’s take a little more line of code, but it’s not complicated.

I put the source project (xmlbeans + jabx) here.

Categories: Java Tools, Web Tags: , , ,

Apache + Glassfish + Subversion + Joomla

May 24, 2010 Leave a comment

I’ll explain in this article how to setup Apache and the configuration of Apache to setup a web server. I’ll setup Apache with Tomcat, Glassfish, Hudson, Subversion, PHP and Joomla. It’s a quick guide how to setup everything, you could have to change some settings to reflect your configuration.

Take a look of the applications that will be installed

  • Apache
  • Php
  • PhpMyAdmin
  • MySQL
  • Glassfish
  • Tomcat
  • Subversion
  • Hudson
  • Joomla

First, We will have to download the applications. (Only download what you need).

Download applications

Apache

To simplify the installation and configuration process, I’ll use an “all in one” setup : xampp. You can download it here.

Tomcat

If you need Tomcat 6.0.14 , you can download the addon for xampp here , or download it from Jakarta here.

If you want Tomcat or Glassfish you will need a JDK. You can use the latest JDK 6 here or try JDK 7 here.

Glassfish

You can download binaries of Glassfish from here or the latest version from svn. (If you want to do this step, you will need Maven 2.0.7 here). There is a really good procedure from Sun here for building from the sources.

Hudson

You can download it here.

Subversion

Subversion server can be download from here. We will need an addon for Apache, that can be download here.

Joomla

To download Joomla go here.

Installation and configuration

Apache

When you use the installer from xampp, it’s very easy to install. Just follow the wizard. When the installation is done, you need to change the default security settings. Follow this guide.

You could have to modify httpd.conf if you install the others applications. I’ll explain it in the appropriate application’s configuration.

Tomcat

Once you have installed Tomcat, you need to configure Apache to redirect the Url to Tomcat. You need to activate the module mod_jk in httpd.conf of Apache. (If you used the Tomcat module for xampp, it will be already activated).

Add this line at the end of httpd.conf :

Include conf/extra/mod_jk.conf

and create the file if is not there and put this in the file.

<IfModule !mod_jk.c>
LoadModule jk_module modules/mod_jk.so
</IfModule>

<IfModule mod_jk.c>
JkWorkersFile “C:/www/tomcat/conf/workers.properties”
JkLogFile “C:/www/tomcat/logs/mod_jk.log”
JkLogLevel info
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# Alias /examples “C:/www/tomcat/webapps/examples”

#<Directory “C:/www/tomcat/webapps/examples”>
# Options All
# </Directory>

# here it’s the url that will be forwarded to tomcat
JkMount /*.jsp ajp13
JkMount /examples/* ajp13

</IfModule>

Please take a look at the line :

JkWorkersFile “C:/www/tomcat/conf/workers.properties”

This line is the configuration for the module in Tomcat. You configure the port, load balancing… (Tomcat have a complete documentation with example here). Tomcat have a “auto config” if you want to keep it simple.

here a sample

worker.ajp13.port=8009
worker.ajp13.host=localhost
worker.ajp13.type=ajp13

Subversion

I recommend that you start by reading this good guide.

You will have to edit the httpd.conf of Apache.

Add theses lines at the end : (don’t forget the replace settings that represent your setup)

# Subversion
LoadModule dav_svn_module modules/mod_dav_svn.so
LoadModule authz_svn_module modules/mod_authz_svn.so

<Location /svnrepository>
DAV svn
SVNPath “c:/www/Subversion/repository”
#SVNParentPath “c:/www/Subversion/repository”
#SVNIndexXSLT “c:/www/Subversion/repository/svnindex.xsl”
SVNAutoversioning on
</Location>

I suggest to install a Subversion client, it will be easier to configure and create repositories. I use TortoiseSvn and Eclipse (SVN plugin).

Joomla

To install Joomla, it’s really simple. Unzip the installation file into the document root of Apache (if you don’t know, check the for the line : DocumentRoot in httpd.conf).

After that, start a browser and enter this URL (need to reflect your configuration) :

http://localhost:80/joomla/

you will be forwared to the Joomla Setup. Just follow the wizard, and when your setup is completed, you will have to delete the folder …/Joomla/installation

Glassfish

To install Glassfish, you have multiples options. I’ll recommend the easiest way for your first time. Install the Glassfish with the Installer, just follow the wizard. Don’t forget.. You need the JDK for that.. not the JRE!

If you prefer bulding Glassfish from the sources, you can follow this excellent guide.

You can configure Glassfish in Apache using mod_jk (like Tomcat) or use mod_proxy.

If you use mod_jk, you won’t use the full connectivity power of Glassfish, but it will works. I’ll explain how to configure both of them. Just for your information, I prefer the mod_proxy config.

Mod_jk setup

Please read the config for Tomcat in this article and go to this post from Jean-Francois Arcand here.

This procedure works for Glassfish 2.1. At this moment, it doesn’t work for the latest version of Glassfish. There is a open bug for that.

And your need to log into the Glassfish console admin. Go into the section : Application Server, JVM Setting. Add this line :

-Dcom.sun.enterprise.web.connector.enableJK=8009

Mod_proxy setup

Open httpd.conf of Apache and add theses lines at the end :

LoadModule proxy_html_module modules/mod_proxy_html.so
Include conf/proxy_html.conf

ProxyPreserveHost on
RewriteEngine on

# example of web application installed on Glassfish
#RewriteRule ^/hudson$ /hudson/ [R,L]
#RewriteRule ^/hudson/(.*) http://localhost:8888/hudson/$1 [P,L]

you can get the file : conf/proxy_html.conf

ADMIN GUI

It’s possible that you don’t have the admin gui console bundle with your installation. You will need to install it. You can let Glassfish auto-install it for you (Recommended), or install it yourself. Right now there is a bug on the build that I’m testing, so I have to install it myself. I’ll describe the both ways.

Auto-install

Enter the URL : http://localhost:8080 (it the port you choose). You should get a welcome page : Your Application Server is now running. Click on the link : To manage the server, click here. You will be redirect to : http://localhost:8080/admin

it the console is not install, you will be able to install it from there, just follow the steps. Like I said, I’m not able to install it from there, so is you are in the same situation.. go to the next step.

Manually

Download the admin.war from Glassfish site. You can have the latest promoted test build here : http://download.java.net/glassfish/v3/admingui/

Once you have downloaded the war..

copy it in the folder glassfish/bin

open a command line : asadmin deploy -p 8080 admingui-v3-prelude-b20.war

that will install it and it will be accessible with this link : http://localhost:8080/admingui-v3-prelude-b20/

Hudson

To install Hudson into Glassfish it’s really easy. Log into the Glassfish admin console or by command line.

You can deploy the war with the command line, like the Glassfish admin gui installation or use GF admin to deploy it. I prefer the Gui. Open Glassfish admin and click on Deploy war application. Click on browse and followed by OK. That it. The application will start automaticaly. You will be able to access it by : http://localhost:8080/hudson

PS. There is a bug in the admin gui. If your port is not 8080, when you click on the “launch” link for an application, it won’t use your custom port. It will open it using the port 8080, that you will have th edit the URL to reflect your port. That should be fixed in V3.

Follow

Get every new post delivered to your Inbox.