Posts Tagged ‘Java’

Deploying BIRT Report Engine API with Stripes Framework

June 23rd, 2008

A long time has passed since my previous BIRT example – Deploying BIRT Report Engine API with Apache Struts.
Now that I preferably use Stripes Framework over Apache Struts, I’ve decided to port my last example to this framework.

BIRT WebReport Example

Even though BIRT now supports HTML, Paginated HTML, PDF, Excel, Word, PowerPoint, and PostScript formats, images and charts are not embedded in Excel output. Tribix XLS Emitter 2.5.2 supports this and was used to generate Excel reports.

I’ve tried to follow some good practices that I think are important to use in a production application:

  • There is a significant cost associated with creating an engine instance, due primarily to the cost of loading extensions. Therefore, each application should create just one ReportEngine instance and use it to run multiple reports. In this example the engine is started in the context listener and the same instance is always used.
  • All texts in the report should be loaded from the resources so the application can be fully localizable and fully internationalized.
  • You should use a JDBC data set to preview your report with BIRT designer but you must swap the data set in runtime to use data from your business logic.
  • You should use predefined styles instead of custom styles as much as you can.
  • Not a good practice but often a requirement, hide the master page when generating a HTML report, and change the visibility of elements so they are visible only to specified outputs.

» Read more: Deploying BIRT Report Engine API with Stripes Framework

Stripes framework and EJB3

January 21st, 2008

Inspired by the Spring with Stripes integration I made a new one named EJB3 with Stripes.

This extension allows you to inject your EJB beans into your Action beans.

Please fell free to use it, and to visit the Stripes and EJB3 project at Google Code.

J2EE cache filter

January 2nd, 2008

In my current web project I was having some performance issues, I needed a tool that allowed me to do some testing so I can see what’s wrong and what I can do better so my application perform faster.

My search lead me to High Performance Web Sites and YSlow, a very good talk by Steve Souders the Chief Performance Yahoo! at Yahoo!

YSlow is an easy-for-use plugin that allows you to inspect any web page just clicking a button.

YSlow analyzes web pages and tells you why they’re slow based on the rules for high performance web sites. YSlow is a Firefox add-on integrated with the popular Firebug web development tool. YSlow gives you:

  • Performance report card
  • HTTP/HTML summary
  • List of components in the page
  • Tools including JSLint

A good way to reduce the number of Http Connections required to load a web page is to store images and other resources in the browser cache.

Expires is a HTTP header that allows you to define when a resource (image, css, javascript, …) will need to be reloaded. It is a String representation of a Date in the format EEE, dd MMM yyyy HH:mm:ss z.
Cache-Control response headers give Web publishers more control over their content and address the limitations of Expires.

To correctly produce these headers I implemented a Java cache filter.
Using the cache filter is very simple. Grab it here and configure your web.xml, here’s an example:

<filter>
    <filter-name>imagesCache</filter-name>
    <filter-class>com.samaxes.filter.CacheFilter</filter-class>
    <init-param>
        <param-name>privacy</param-name>
        <param-value>public</param-value>
    </init-param>
    <init-param>
        <param-name>expirationTime</param-name>
        <param-value>2592000</param-value><!-- 30 days -->
    </init-param>
</filter>

<filter>
    <filter-name>cssCache</filter-name>
    <filter-class>com.samaxes.filter.CacheFilter</filter-class>
    <init-param>
        <param-name>privacy</param-name>
        <param-value>public</param-value>
    </init-param>
    <init-param>
        <param-name>expirationTime</param-name>
        <param-value>604800</param-value><!-- 7 days -->
    </init-param>
</filter>

<filter>
    <filter-name>javascriptCache</filter-name>
    <filter-class>com.samaxes.filter.CacheFilter</filter-class>
    <init-param>
        <param-name>privacy</param-name>
        <param-value>private</param-value>
    </init-param>
    <init-param>
        <param-name>expirationTime</param-name>
        <param-value>172801</param-value><!-- 48 hours + 1 second -->
    </init-param>
</filter>

<filter-mapping>
    <filter-name>imagesCache</filter-name>
    <url-pattern>*.png</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>imagesCache</filter-name>
    <url-pattern>*.jpg</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>imagesCache</filter-name>
    <url-pattern>*.gif</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>cssCache</filter-name>
    <url-pattern>*.css</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>javascriptCache</filter-name>
    <url-pattern>*.js</url-pattern>
</filter-mapping>

Note: YSlow far future Expires header magical number is 172801 seconds (48 hours + 1 second).

Classloader leaks and PermGen space

October 2nd, 2007

After googling a bit for error “java.lang.OutOfMemoryError: PermGen space” I found many sites talking about that problem. Some tried passing command line arguments to the JVM or changing the size of the PermGen space, others end up recommending using a VM from BEA or IBM, all without success.

But after a closer look at their comments I ended up at Frank Kieviet blog.
Frank explains what really is a PermGen error

The problem in a nutshell

Application servers such as Glassfish allow you to write an application (.ear, .war, etc) and deploy this application with other applications on this application server. Should you feel the need to make a change to your application, you can simply make the change in your source code, compile the source, and redeploy the application without affecting the other still running applications in the application server: you don’t need to restart the application server. This mechanism works fine on Glassfish and other application servers (e.g. Java CAPS Integration Server).

The way that this works is that each application is loaded using its own Classloader. Simply put, a Classloader is a special class that loads .class files from jar files. When you undeploy the application, the Classloader is discarded and it and all the classes that it loaded, should be garbage collected sooner or later.

Somehow, something may hold on to the Classloader however, and prevent it from being garbage collected. And that’s what’s causing the java.lang.OutOfMemoryError: PermGen space exception.

PermGen space

What is PermGen space anyways? The memory in the Virtual Machine is divided into a number of regions. One of these regions is PermGen. It’s an area of memory that is used to (among other things) load class files. The size of this memory region is fixed, i.e. it does not change when the VM is running. You can specify the size of this region with a commandline switch: -XX:MaxPermSize. The default is 64 Mb on the Sun VMs.

If there’s a problem with garbage collecting classes and if you keep loading new classes, the VM will run out of space in that memory region, even if there’s plenty of memory available on the heap. Setting the -Xmx parameter will not help: this parameter only specifies the size of the total heap and does not affect the size of the PermGen region.

… and how to use new profiling tools in Java 6 to fix Classloader leaks.
Resuming, the steps are:

  1. start your application server
  2. deploy and run your application
  3. undeploy the application that is leaking (just the application not the server)
  4. trigger a memory dump jmap -dump:format=b,file=leak <PID>
  5. run jhat (with modification, Java SE SDK 6.0 update 1 has the updated code) jhat -J-Xmx512m leak
  6. go to jhat report http://localhost:7000/ (http://localhost:7000/oql/ if you need the OQL (Object Query Language))
  7. find a leaked class (any class of your application since you shouldn’t see any objects of the classes that you deployed)
  8. locate the Classloader
  9. find the “Reference chains from root set”
  10. inspect the chains, locate the accidental reference, and fix the code

Some try even to go further on finding Orphaned Classloaders others try to nicely present the leaking classes in a form of a HTML table histogram.

These tools can really help, use them!

Resources

Code conventions and programming style

October 1st, 2007

Coding conventions are rules that computer programmers follow to ensure that their source code is easy to read and maintain.

Why is that important?

Sun Microsystems provides the following rationale for the Java Programming Language:

Code conventions are important to programmers for a number of reasons:

  • 80% of the lifetime cost of a piece of software goes to maintenance.
  • Hardly any software is maintained for its whole life by the original author.
  • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
  • If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.

Crossbow Software has gather a set of code conventions and programming style documents, take a look at their Coding Style Standards download page.

Maven 2 Cobertura Plugin

June 24th, 2007

The Maven 2 Cobertura Plugin web site lacks information to successfully generate Cobertura reports. Worse, some of the usage examples are incorrect and don’t work.

The most common problem when generating Cobertura reports is when the generated report shows 100% test coverage while in reality many of the classes don’t even have tests.

The following example shows how to configure the reports so that it would reflect real test coverage and then check if the specified packages achieved the wanted test coverage:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>cobertura-maven-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <check>
                    <haltOnFailure>false</haltOnFailure>
                    <regexes>
                        <regex>
                            <pattern>com.samaxes.business.*</pattern>
                            <branchRate>90</branchRate>
                            <lineRate>90</lineRate>
                        </regex>
                        <regex>
                            <pattern>com.samaxes.persistence.*</pattern>
                            <branchRate>90</branchRate>
                            <lineRate>90</lineRate>
                        </regex>
                    </regexes>
                </check>
                <instrumentation>
                    <includes>
                        <include>com/samaxes/**/*.class</include>
                    </includes>
                </instrumentation>
            </configuration>
            <executions>
                <execution>
                    <id>clean</id>
                    <phase>pre-site</phase>
                    <goals>
                        <goal>clean</goal>
                    </goals>
                </execution>
                <execution>
                    <id>instrument</id>
                    <phase>site</phase>
                    <goals>
                        <goal>instrument</goal>
                        <goal>cobertura</goal>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
<reporting>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>cobertura-maven-plugin</artifactId>
        </plugin>
    </plugins>
</reporting>

JBoss – Stacking Login Modules

May 27th, 2007

Sometimes no single login module is enough to meet our needs. Imagine the case of using an external LDAP server to provide the user authentication and a database server to provide the user authorization. A user would be in one repository or the other, and login should succeed if the user is found in either repository.

JBoss allows you to specify multiple login modules for a single security domain. But simple module stacking doesn’t resolve the problem on its own. For that, you need to use password stacking.

Password stacking allows modules to skip the actual authentication and to provide supplemental roles. The modules require the password-stacking option to useFirstPass for this to work.

<application-policy name="myRealm">
  <authentication>
    <login-module code="org.jboss.security.auth.spi.LdapLoginModule" flag="optional">
      <module-option name="password-stacking">useFirstPass</module-option>
      <module-option name="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</module-option>
      <module-option name="java.naming.provider.url">ldap://LDAP_SERVER:LDAP_PORT/</module-option>
      <module-option name="java.naming.security.authentication">simple</module-option>
      <module-option name="principalDNPrefix">MY_DOMAIN\</module-option>
    </login-module>
    <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
      <module-option name="password-stacking">useFirstPass</module-option>
      <module-option name="dsJndiName">java:myDS</module-option>
      <module-option name="principalsQuery">SELECT passwd FROM user WHERE login = ?</module-option>
      <module-option name="rolesQuery">SELECT role, 'Roles' FROM user_roles r, user u WHERE u.userid = r.userid AND u.login = ?</module-option>
    </login-module>
  </authentication>
</application-policy>

The option principals query is optional; it’s a fallback in the case the authentication fails in the LDAP server. Notice that the LDAP configuration omits the roles query option set so the authorization is only provided by the database server module.

Where does .NET beat Java?

May 9th, 2007

Werner Schuster posted at InfoQ an article entitled “Microsoft Surpasses Java’s Dynamic Language Support” trying to show where .NET is doing better than Java.

Some of the highlights are:

  • Microsoft CLR (Common Language Runtime), LINQ and the support for multiple languages
  • DLR (Dynamic Language Runtime)
  • .NET modularization and versioning

Secure JSP Taglibs

February 4th, 2007

I’ve just created the project Secure JSP Taglibs at Google Code Project Hosting with the ambition to fill some gaps in the security of the presentation layer in a Java web application.

For now it doesn’t do too much, more features will be added in the future.
This Taglib allows you to evaluate the nested body content of the tag to test if the user has the specified roles.
This is equivalent to the isUserInRole() method, but you can evaluate multiple roles (comma separated) at the same time.

Examples:

<secure:one roles="role1toevaluate, role2toevaluate">
    Show this content if the user has one of the specified roles.
</secure:one>
<secure:all roles="role1toevaluate, role2toevaluate">
    Show this content if the user has all the specified roles.
</secure:all>
<secure:none roles="role1toevaluate, role2toevaluate">
    Show this content if the user has none of the specified roles.
</secure:none>

Feel free to use it, it’s licensed under Apache License 2.0 and can be found at http://code.google.com/p/secure-taglib/.

Comparison between Stripes and JSF

January 8th, 2007

Reading the TheServerSide.COM news I’ve found a comparison’s article between Stripes and JSF frameworks.

I can’t agree more with the author Gregg Bolinger when he says Since I stumbled on Stripes, I’ve found it to be the best all around framework for my purposes.

Read it at “Stripes and JSF: A Brief Comparison“.