dinsdag 24 november 2009

Devoxx 2009

I skipped 2008 so I can't compare with that. This year was a lot about annotations and how they make xml files redundant. In JSF 2.0 for instance the faces-config.xml is optional. Also EJBs are much easier to define and it can even be done in a single class from now on (jee6).

I'm pretty sure you can find more about this conference online.

maandag 23 november 2009

JSF: translation of messages in managed bean

In JSF managed beans you can add messages to the context for use in views. For instance when an error occurs you can add a message to be displayed to the user. This is how:

FacesContext.getCurrentInstance().addMessage(null,
    new FacesMessage("message"));

The null is an identifier you can provide in order to identify an element of the view. I don't want that kind of information in my managed bean so I left this out. But that isn't the problem. My problem is that the message wasn't translated this way. So I figured out how to get to the resourcebundle configured in the faces-context definition:

ApplicationFactory factory = 
    (ApplicationFactory) FactoryFinder
    .getFactory(FactoryFinder.APPLICATION_FACTORY);
Application application = factory..getApplication();
ResouceBundle bundle = ResourceBundle.getBundle(
    application.getMessageBundle());

vrijdag 20 november 2009

outputText renders date wrong?

outputText is rendering dates wrong! I created a simple testcase with some dates. The 2 lines per date should print exactly the same date because only difference is that that I'm using the outputText tag or not. Like this:

<u>test java.util.Date</u>
<p>this is the date without outputText tag: #{helloBean.currentDate}</p>
<p>this is the date wit outputText tag: <h:outputText value="#{helloBean.currentDate}" /></p>

It's always the line without outputText tag that is printing just fine. Problem only occured when fetching a date from database. Like DB2 and HSQLDB.

test simple util.Date
this is the date without outputText tag: Fri Nov 20 13:40:17 CET 2009
this is the date wit outputText tag: 20-nov-2009

test with db2
this is the date without outputText tag: 2009-06-23
this is the date wit outputText tag: 22-jun-2009

test sql.date
this is the date without outputText tag: 2009-11-20
this is the date wit outputText tag: 20-nov-2009

test other db (hsqldb) date
this is the date without outputText tag: 2009-11-20
this is the date wit outputText tag: 19-nov-2009

Code used in bean:
public Date getHSQLDBDate() throws Exception {
  Date date = null;
  Class.forName("org.hsqldb.jdbcDriver");
  Connection connection = DriverManager.getConnection(
    "jdbc:hsqldb:mem:test", "sa", "");
  try {
   Statement statement = connection.createStatement();
   try {
    try {
     statement.execute("drop table test");
    } catch (Exception e) {
     // ignore
    }
    statement.execute("create table test (adate date)");
    PreparedStatement pstat = connection
      .prepareStatement("insert into test(adate) values(?)");
    pstat.setDate(1, new java.sql.Date(Calendar.getInstance()
      .getTime().getTime()));
    pstat.execute();
    ResultSet set = statement
      .executeQuery("select adate from test");
    try {
     if (set.next()) {
      date = set.getDate("adate");
     }
    } finally {
     set.close();
     pstat.close();
    }
   } finally {
    statement.close();
   }
  } finally {
   connection.close();
  }

  return date;
 }

donderdag 12 november 2009

richfaces calendar tag fails when nested in paragraph tag

When nesting the richfaces calendar tag in a paragraph tag (<p>) it doesn't work anymore. For example this code:
<p>#{bundle.availabilityDate} <rich:calendar id="validUntilDate"
     required="true"
     value="#{glossaryVersionController.glossaryVersion.availabilityDate}" /></p>

resulted in the popup not showing and this javascript error on rendering the xhtml page:
Fout: obj is null
Bronbestand: http://server:port/application/a4j/g/3_3_1.GAorg/richfaces/renderkit/html/scripts/calendar.js.xhtml
Regel: 97

When this richfaces calendar tag is used outside a paragraph tag all works well.

woensdag 28 oktober 2009

Increase Heap Space size for maven on windows

When you get a Heap Space error when building with maven you can increase this heap space by setting MAVEN_OPTS.

On windows this is done by creating a mavenrc_pre.bat file in your %HOME% directory with this content:
set MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m

Similar there is a mavenrc_post.bat for everything you want to be executed after the build.

is org.richfaces.model.selection.ClientSelection causing PermGen OutOfMemoryError

In a previous post I got into the PermGen OutOfMemoryError, what it causes and how to fix it. The reason I got into this material is that I'm running into it myself with a richfaces application.

I'm also commenting on this issue about this problem. There you can see I was able to reproduce the problem with a simple application. Next step is to try fix it :D

woensdag 21 oktober 2009

java.lang.OutOfMemoryError: PermGen space on glassfish

Workaround

I get this PermGen space OutOfMemoryException sometimes when I do a lot of deployments on the Sun Java System Application Server 9.1_02 (build b04-fcs). The first hit when googling this error was this thread with a suggestion to increase memory heap size. But not only for the complete heap with the -Xmx argument because the PermGen space is only a fixed part of that memory, used for classloading. You can increment that specific part with the following arguments:

-Xmx=512m
-XX:MaxPermSize=256m
-XX:PermSize=256m

Understanding the problem

Even better is to find out where it leaks. But before we can do so we need to understand the problem.
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.

This is a comprehensive explanation of the cause:
To summarize, a new instance of custom Classloader is created by Application Server whenever a new application (.ear, .jar, .war) is deployed to the server, and this Classloader is used to load all the classes and resources contained in this application. Benefit in this approach is that, this way applications are self-contained and isolated from each other, and there are no conflicts between different applications. When an application is undeployed from server, its associated Classloader is also unloaded, and it is subject to garbage-collection by JVM.

As described in Frank's blog, there are situations in which Classloaders cannot be garbage-collected because of dangling references to them thru most unexpected places, and this will cause memory-leak in the PermGen space (a special section of heap). To find the cause of this problem, I used JDK 6.0's jmap and jhat utility to generate memory dump and analyze memory dump, respectively.

Fixing the problem

First of all we need to trigger the problem. That is by deploying your application and undeploying it again and then look for classes still loaded that shouldn't. When you find these classes you can track back for strong references from classes from another classloader. There are several tools for that. The easiest (as explained on the blog of Frank Kieviet) is to get the memory dump using jmap. For that we need to know the PID of the process, using jps:
jps
will return a list of PIDs and one of them is of your application server:
C:\Program Files\Java\jdk1.6.0_11\bin>jps
1000 jar
2204 Jps
2356 CLIMain
1796 org.eclipse.equinox.launcher_1.0.1.R33x_v20080118.jar
1824 PELaunch
For Glassfish it is called PELaunch. For other containers I have no idea.

Using that PID we can get a memory dump using jmap (included in JDK 6):
jmap -dump:format=b,file=leak 1824
Where 1824 is the PID of the container you're running and leak is the file where you want the dump be written to.

Then you can run jhat (included in JDK 6) to browse that dump:
jhat -J-Xmx512m leak
leak is the same file you've written the memory dump to. This will start a server you can reach by directing your browser to http://localhost:7000. 7000 is the default port. Now you can browse the classes and find those that are leaking. A goog idea is to look into the exclude weak refs links. Even better is to use the modified code of Edward Chou you can find on his blog. Then you can also list a hierarchy of classloaders with Show ClassLoader Hierarchy (added) and an extra link is added to show only strong links from classes in a different classloader: Exclude weak refs, filter enabled (added)

I now found a more visual approach at http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/17/the-unknown-generation-perm/. It's an eclipse plugin that visualises the heap dump created with jmap (give the file a .hprof extension so it's recognized by this tool).

Resources

Check the following resources if you want to get into this problem:
http://blogs.sun.com/edwardchou/
http://blogs.sun.com/fkieviet/entry/classloader_leaks_the_dreaded_java
http://blogs.sun.com/fkieviet/entry/how_to_fix_the_dreaded
http://mediacast.sun.com/users/Frank.Kieviet/media/JavaOne07-BOF9982-PermGen.pdf
http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/memleaks.html
http://blog.emptyway.com/2007/04/02/finding-memory-leaks-in-java-apps/

dinsdag 20 oktober 2009

format code in blog post using html, css and js

I have several code samples on this blog and I needed a way to display these with some kind of code highlighting. First queries returned me some blogs that only formatted the <pre> or <code> tag with css:
pre {
  background:#efefef;
  border:1px solid #A6B0BF;
  font-size:120%;
  line-height:100%;
  overflow:auto;
  padding:10px;
  color:#000000;
}
pre:hover {
  border:1px solid #efefef;
}
code {
  font-size:120%;
  text-align:left;
  margin:0;padding:0;
  color: #000000;
}
.clear { 
  clear:both;
  overflow:hidden;
}
And next I only needed to find a way to highlight code... Google has a code prettify project for that. It uses css as well but also javascripting. Read the instructions here. You need to add a reference in the header to the script and stylesheet like this:
<link href="prettify.css" type="text/css" 
  rel="stylesheet" />
<script type="text/javascript" 
  src="prettify.js"></script>
And then add the prettyPrint() function to the onload event of the body tag like this:
<body onload="prettyPrint();">

nullpointer for param inside commandlink

The problem started when I added this param to a commandlink like in the code below:
<h:commandLink 
  value="#{item.elementCombinedCode}" 
  action="#{elementFormController.prepareElementAction}">
<f:param name="elementNbr" 
  value="#{item.elementId}" />
</h:commandLink>
With Glassfish version 9.1_01 (build b09d-fcs) I then got this error:
java.lang.NullPointerException
at com.sun.faces.renderkit.RenderKitUtils.getCommandLinkOnClickScript(RenderKitUtils.java:934)
at com.sun.faces.renderkit.html_basic.CommandLinkRenderer.getOnClickScript(CommandLinkRenderer.java:295)
at com.sun.faces.renderkit.html_basic.CommandLinkRenderer.renderAsActive(CommandLinkRenderer.java:357)
at com.sun.faces.renderkit.html_basic.CommandLinkRenderer.encodeBegin(CommandLinkRenderer.java:165)
...
After some investigation I got to this issue stating that you would get this error when the given param value is null. Good news is that it's solved in following versions of glassfish. I quote:

The following will blow up:
<h:commandLink value="Go!">
    <f:param name="test" value="#{null}"/>
</h:commandLink>
The reason is that, while HtmlBasicRenderer.getParamList(UIComponent)
acknowledges that the parameter value may be null, and thus creates a
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.Param instance with a null
value if the parameter's value was null, the code in
RenderKitUtils.getCommandLinkOnClickScript dereferences the param.value property
without checking whether it is null:
for (Param param : params) {         
            sb.append(',');
            sb.append(param.name.replace("'", "\\\'"));
            sb.append(',');
            sb.append(param.value.replace("'", "\\\'"));            
        }          
Resulting in an NPE.

donderdag 15 oktober 2009

using JTrac as issue tracking system

We wanted some simple tracking system. Some out of the box and easy to use application. Because I have experience working with Trac this was my first choice. But on my current project we lack a Python installation so setup would require setting up a python environment first... Something similar in Java would be easier... and that would be JTrac indeed :D.

JTrac also has support for custom fields and a custom ticket workflow. Are very similar to Trac but in java an distributed as a war that we could deploy on our already running glassfish servers.

Until now we have only found one problem with version 2.1.0. Some tickets showed duplicate identities. It is already described in this topic so solution was fairly simple. And as it seems a new version have fixed this problem for ever.

I quote the solution:
I'm pretty confident this will be addressed in the next version, some work went into re-doing how the next sequence number is generated. You can check the SVN commit logs if you need more details.

Thanks all who posted information. It all helps. An update I received over e-mail from Maurizio (who reported the problem on restart) is at least in that scenario - the problem is fixed.

New installations of JTrac will also enforce a unique constraint at the database level - for the combination of 2 columns on the "items" table. Existing users can easily do this on their existing databases.

The columns on the "items" table are "space_id" and "sequence_number"

For HSQLDB and MySQL you can add a constraint as follows:
alter table items add constraint con_items_space_seq unique (space_id, sequence_num);
This command will of course fail if the table still contains duplicates. To find duplicates, you can run this query:
select a.id from items a, items b where a.space_id = b.space_id and a.sequence_num = b.sequence_num and a.id > b.id;
You can select more columns in the above query to get more info as to which rows are duplicated. But the above query can be easily used as a subquery to delete the duplicate records. To take care of referential integrity, you have to delete the history table entries first:
delete from history where item_id in (
select a.id from items a, items b where a.space_id = b.space_id and a.sequence_num = b.sequence_num and a.id > b.id
);
and then:
delete from items where id in (
select a.id from items a, items b where a.space_id = b.space_id and a.sequence_num = b.sequence_num and a.id > b.id
);
And now you can add the unique constraint.

dinsdag 15 september 2009

EJB injection failed on glassfish with myfaces

I got nullpointers for all EJB injected dao's :o. In fact a colleague of me already blogged the solution. It's a small world after all :D.

I was trying to get @EJB dependency to work on my JSF managed beans. MyFaces Tomahawk on a Glassfish v2 app server. I kept getting NullPointerExceptions because the injection didn't happen...

Turns out it was failing to inject the ejb implementations because my webapp was trying to use the MyFaces jsf implementation next to the sun RI implementation shipped with Glassfish.

So, make sure not both the RI implementation (provided by glassfish), and myFaces implementation are active!

I prevented the myFaces implementation from loading by commenting the StartupServletContextListener in WEB-INF/web.xml (2.5 headers):
view plainprint?

1. <!--  
2. <listener>  
3. <listener-class>  
4. org.apache.myfaces.webapp.StartupServletContextListener  
5. </listener-class>  
6. </listener>  
7. -->

vrijdag 24 april 2009

JSF CommandLink and CommandButton fails inside table

The problem is some commandButtons simply don't work at all. The action is never executed. I tested with a debugger and there is not even a call to the given action method :o. Overlooking spelling mistakes makes no sense because JSF would warn me for non existing methods. I found the solution in this topic: JSF and "THE TRAP!" - CommandLinks and DataTables on theserverside.com.

And I quote from http://typo.ars-subtilior.com/articles/2007/02/07/jsf-datatable-and-commandlink

The reason for this behaviour is that the DataTable modifies the id of the CommandLink during renderering, but the CommandLink does not know that it was rendererd with a different id. During the decoding of the request which was triggered by clicking the CommandLink, the ComandLinkRenderer looks at a hidden form parameter. If the value of that form parameter equals the id of the CommandLink, an action is queued. If not, nothing is done.

Since the DataTable changes the ids, the value of the hidden form parameter does not match the id of the CommandLink.


Some solutions:

- change request scope of bean to session scope in faces-config.xml (only workaround)
- adding preserveDataModel="true" to dataTable tag (didn't help for me!)
- using tomhawaks saveState tag (didn't try this)
- override commandLinkRenderer

Also check this thread: http://forums.sun.com/thread.jspa?threadID=5116147

Java Black Belt

The Community Edition is a free training platform with mostly java related content.

Users can take exams for which they get knowledgepoints. According to the amount of knowledgepoints they get a belt (ref. judo).


Yellow belt : 0 Knowledge points needed


Orange belt : 18 Knowledge points needed


Green belt : 30 Knowledge points needed


Blue belt : 45 Knowledge points needed


Brown belt : 60 Knowledge points needed


Black belt : 80 Knowledge points needed

Some exams are free. Other exams you can only take in return of some contribution points. These points can be collected by creating and reviewing questions and exams. This way the content is built.

For those wondering: I have a personal account where I got up to the brown belt (black wasn't available at that point) and a corporate account where I'm stuck at some other color. It just doesn't make sense to take those tests again. And the accounts couldn't be merged. Too bad.

donderdag 9 april 2009

(NL) Europese ICT deals worden kleiner en korter

outsourcing / Nieuws
07-04-2009 11:38 | Door Diederik Toet | Gerelateerde bedrijven: Forrester Research | Er zijn nog geen reacties op dit artikel | Permalink
Europese ICT-deals worden kleiner en korter
Budget geld planning

Europese uitbestedingsopdrachten hebben tegenwoordig een kortere looptijd en een lagere contractwaarde dan voorheen. Dat becijferen analisten van Forrester. "Het toont dat klanten heel specifieke keuzes maken bij de beslissing welke individuele ict-onderdelen ze willen uitbesteden."

In 2008 is een duidelijke afname zichtbaar van de gemiddelde waarde van nieuwe ict-uitbestedingsprojecten. Bovendien lopen de contracten ook korter dan in 2007. Dat concluderen analisten van Forrester. Zij onderzochten zeventien grote Europese ict-dienstverleners en de contracten die zij afsloten. Het Forrester-rapport heet EMEA IT Outsourcing Deals: 2008 Review.

Klantorganisaties zijn duidelijk op zoek naar kleinere contracten, zegt analist Pascal Matzke van Forrester. In 2008 heeft 43 procent van de afgesloten deals een waarde die ligt tussen de tien en twintig miljoen euro. "Het toont dat klanten heel specifieke keuzes maken bij de beslissing welke individuele ict-onderdelen ze willen uitbesteden. Daarmee keren zij de trend uit 2007. Toen slonk het aandeel opdrachten met een waarde tussen tien en twintig miljoen euro", licht Matzke toe. Er waren volgens hem geen deals van boven de miljard euro en slechts weinig van meer dan een half miljard.
Logisch
Forrester uitbestedingsdeals 2008

Bron: EMEA IT Outsourcing Deals 2008 Review (Forrester Research)
Bron: EMEA IT Outsourcing Deals 2008 Review (Forrester Research)

Een andere bevinding uit het onderzoek is dat organisaties gemiddeld korter lopende uitbestedingsopdrachten tekenen met dienstverleners. De analist vindt dat logisch, gezien de onzekere economische situatie. In 2008 hadden bijna acht op de tien uitbestedingscontracten een looptijd van vijf jaar of korter. Vier van de tien betrof zelfs een opdracht voor korter dan vier jaar. Matzke ziet een duidelijke toename van het aantal kortlopende uitbestedingscontracten ten opzichte van 2007. In dat jaar was slechts veertien procent afgesloten voor minder dan drie jaar.

51 procent van de uitbestedingsopdrachten van de publieke sector betreft deals met een waarde van minder dan twintig miljoen euro.
bron: http://www.computable.nl/artikel/ict_topics/outsourcing/2920177/1276946/europese-ictdeals-worden-kleiner-en-korter.html

(NL) Er is meer verlof dan je denkt \o/

Verlof: lusthof of doolhof
11 soorten verlof - welke past bij jou?

Dat je recht hebt op minstens 20 dagen jaarlijkse vakantie, weet elke werknemer wel. Maar welke andere vormen van verlof zijn er nog?

Samen met Kathy Bergen, Juridisch adviseur bij Groep S, proberen we je door het verlof-doolhof te loodsen.

* Adoptieverlof

* Palliatief verlof

* Verlof om dwingende redenen

* Moederschapsverlof

* Ouderschapsverlof

* Tijdkrediet

* Betaald educatief verlof

* Vaderschapsverlof

* Zorgverlof

* Pleegzorgverlof

* Klein verlet


> Overheid wil bepaalde vormen verlof uitbreiden

vrijdag 20 februari 2009

more java reading

check this link, is a list of java resources. Funny how they mention themselves... recursivity all over :D.

http://www.ibm.com/developerworks/java/library/j-javaresources.html


The list of Web sites (with URLs):

* java.sun.com
This is the place from which the JDK originates and is often the first site that Java developers go to download a copy of the JDK and documentation. But beyond that, it is also a good source for information on the entire Java platform, including a very rich section on the JVM itself (Hotspot), which describes the internals of the JVM to a surprising depth.

* java.net
The Java.NET site is a smorgasbord of open-source projects, documentation, blogs, wikis, news, and other community resources. It's a motherlode of information on Java technology, possibly too much. For all that though, cruising through the list of projects can lead to some real gems such as the FEST-Swing project, which aims to create a "fluent interface" for building Swing applications, making them vastly simpler to create unit tests around.

* InfoQ
Created by Floyd Marinescu, founding editor-in-chief of The ServerSide, InfoQ differs from many of the other resources listed here in that it is explicitly technology-neutral, covering not only Java code but also .NET and Ruby and offering great coverage of agile approaches and insights. Though the commenting community on InfoQ isn't as large or as diverse as that of TheServerSide, the discussion is usually more tame and less hostile.

* TheServerSide
Often called "the the Slashdot of Java," TheServerSide was the first place that enterprise Java topics were openly questioned, hotly debated, and aggressively pursued. Some of the earliest thoughts around lightweight containers (as typified by Spring) occurred here and many of the individuals now considered to be "thought leaders" in the Java community emerged here. Although more recently the debates have sometimes taken on the character of shrill shouting matches, TSS will always be the original home of much of what turned into the Java ecosystem we now live within; as such, it will always be a source of information, historical if nothing else.

* DZone
DZone began life as a resource for Java developers, but more recently has begun to branch out into the other technology sectors, including .NET and Ruby, as well as several other topical "zones" of coverage. As such, while it's possible for the Java developer to focus entirely on just the Java zone, some cross-pollination does occur and it's the wise developer who will take advantage of that.

* IBM® developerWorks
If you're reading this article, then you've already found dW. In the interest of full disclosure, I must note that I have contributed articles other than this one to this site, but I can say with integrity that dW stands as a great resource for articles and material on Java coding and the JVM. In particular, be sure to check out Java theory and practice, a long-running series by Brian Goetz, which includes a three-part description of the JVM garbage collector that introduces the core concepts of GC in a surprisingly approachable way.

* JavaWorld
After a long hiatus, JavaWorld has returned to its youthful glory with a revamped look, high-quality technical content, and a handy topic taxonomy for quickly finding the types of articles you seek. Don't miss the extensive archives, which date back to its inception and include articles by some of the Java community's most notable contributors.

* Artima
Created by Bill Venners, Artima has evolved into a huge collection of articles, blogs, and interviews, not all of it entirely focused on Java development, and has some of the biggest names in the Java space writing there. (Check out Bill Joy's disbelief over the complexity of the Java language after Java 5 was released and the example he uses to justify his worries — Enum<> — as a classic example.) Well worth

fast & simple jsf mockups with hibernate

I'm working on a prototype for several administration pages and needed a quick mockup for testing. So I quickly set up a HSQLDB in memory and used hibernate annotations to map my model to it. Here are some code snippets to check how to configure hibernate to work in the jsf context:

you'll need a filter to instantiate hibernate:
package fi.tavutaito.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
*
* SessionFilter initializes EntityManagerFactory and serves each request
* with an EntityManager.
*
* @author markus
*
*/
public class EntityManagerFilter implements Filter {
/** Logger */
protected Logger log = Logger.getLogger(EntityManagerFilter.class.getName());

private EntityManagerFactory entityManagerFactory;

/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig config) throws ServletException {
Map configOverrides = new HashMap();
// this enables to see hibernate generated SQL in the server log
configOverrides.put("hibernate.show_sql","true");
entityManagerFactory = Persistence.createEntityManagerFactory("database", configOverrides);
}

/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {

EntityManager em = entityManagerFactory.createEntityManager();
request.setAttribute("entitymanager", em);
EntityTransaction tx = null;
try {
// begin the transaction
tx = em.getTransaction();
tx.begin();

// continue processing to JSF
chain.doFilter(request, response);

// after returning from JSF commit the transaction
tx.commit();

} catch (RuntimeException e) {
// if something fails, log the error and rollback
log.log(Level.SEVERE, "",e);
tx.rollback();
} finally {
// always close the entitymanager
em.close();
}
}

/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
entityManagerFactory = null;
}

} 

and this filter needs to be configured in the web.xml like this:
<!-- Entity Manager Filter declaration -->
<filter>
<filter-name>EntityManagerFilter</filter-name>
<filter-class>fi.tavutaito.filter.EntityManagerFilter</filter-class>
</filter>

<!-- Filter is setup on all requests than end with jsf suffix -->
<filter-mapping>
<filter-name>EntityManagerFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>

Now don't forget to configure you're persistence.xml. I'm used to putting it into the META-INF folder but it wasn't found so I got exceptions like:
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named database
Not sure yet why but I think it has something to do with the way I run it using jetyy. Will get back to this post when I have a solution.

If all goes well you can access the EntityManager through the FacesContext like this:
(EntityManager)
((HttpServletRequest)FacesContext
.getCurrentInstance()
.getExternalContext()
.getRequest()
)
.getAttribute("entitymanager");
Also check the resources of this post for some utilities.

I'm managing dependencies using maven and running all this code using the maven jetty plugin ;-).

external links:
* a tutorial on jsf + hibernate + facelets
* an example of HSQLDB hibernate config properties

dinsdag 27 januari 2009

(NL) De helft van de boodschap is lichaamstaal

Een boodschap bestaat voor 55% uit lichaamstaal, voor 38% uit
intonatie en voor 7% uit woorden. Door te schaven aan uw lichaamstaal
kunt u dus een betere communicator worden.

Het enige waaraan u moet denken wanneer u spreekt is: "Ik weet waar ik
over praat". U zult dat vanzelf ook uitstralen.

- Hoofd en schouders rechtop houden. Niet ineengedoken staan. Zo wint
u twee centimeter.
- Handen beter in de achterzakken dan vooraan in de zakken of gekruist.
- Benen evenwijdig stevig op de grond plaatsten.
- Met de handen uw woorden benadrukken.
- Hart en voeten naar de gesprekpartners toe draaien.
- Kijk naar de ogen van uw gesprekspartner. Wanneer u naar de kleur
van de ogen kijkt, geeft u de indruk nog aandachtiger te luisteren.
- Maak een kleine aanraking om vertrouwen te creëren.
- Wanneer u wilt glimlachen, zeg "Great". Dat voelt goed, en veertig
van de tachtig gezichtsspieren bewegen. Veel beter dan "Cheese".
- Spiegel uw houding aan die van de mensen om u heen. Dat schept vertrouwen.

Deze aanbevelingen voelen in het begin misschien onnatuurlijk aan,
maar dat gevoel slijt. Als u deze tips zelf even vergeet, laat u eraan
herinneren.

Dit zijn enkele lessen uit het seminarie charismacoaching van Frank
Segers, Glenn De Cliént en Bé De Meyer. Drie Bizz-lezers hebben dit
nieuw seminarie uitgetest. Hun oordeel leest u in de Bizz van deze
maand.

vrijdag 23 januari 2009

JSF controllers and bean dependencies

I'm refreshing my JSF knowledge since I've been working with spring mvc instead for a while. In fact a lot is similar to spring or can be done using a similar approach.

JavaBean: Interconnection between front- and backend are the javabeans. These you should know, having a no args ctor, properties with accessors (getters and setters), binding of these properties in frontend, ...

public class JavaBean {

private String myProperty;

public JavaBean() {};

public void setMyProperty(String property) {
this.myProperty = property;
}

public String getMyProperty() {
return this.myProperty;
}
}


Using javabeans as controllers: In JSF javabeans can be configured using the faces-config.xml (or any custom named xml configuration file when it's pointed correctly). The properties can be easily set by providing setters and getters in the javabean class and databinding in the JSF page. You can use these managed beans as controllers by just creating some extra methods and the commandButton or commandLink jsf-component bound to these methods.

<!-- ... -->

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
template="/WEB-INF/template/default.xhtml">

<!-- ... -->

<!-- example of property binding with a checkbox -->
<h:selectBooleanCheckbox title="#{file.selected}"
value="#{file.selected}">

<!-- example of method binding with commandButton -->
<h:commandButton id="refresh" action="#{StatsController.refresh}"
value="#{bundle.refresh}"></h:commandButton>

<!-- ... -->


Bean dependencies: Service and other dependencies between beans can also be configured in this xml. Therefore create managed beans with no scope and then reference these in the actual javabean.
<!-- an example of a service -->
<managed-bean>
<description>fileservice</description>
<managed-bean-name>FileService</managed-bean-name>
<managed-bean-class>
group.project.services.FileServiceImpl
</managed-bean-class>
<managed-bean-scope>none</managed-bean-scope>
</managed-bean>

<!-- and this service being referenced in another bean -->
<managed-bean>
<description>
The controller for the list of files, select and process
</description>
<managed-bean-name>FilesController</managed-bean-name>
<managed-bean-class>
group.project.web.FilesController
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>service</property-name>
<value>#{FileService}</value>
</managed-property>
</managed-bean>

Error green UML eclipse plugin 3.3

First of all, if you have a recent version of eclipse then install/update the green UML plugin using the following update site from within Help > Software Update s > Find and Install:

http://www.cse.buffalo.edu/faculty/alphonce/green/

I'm using eclipse 3.3.2 so I had to go for GEF 3.3 and Green 3.0. When dropping the plugin in the plugins folder (GEF I installed using the update sites) I had the options in the eclipse menu added to create UML diagrams.

Only when trying to view a generated Green UML file, extension .grn I got an error from eclipse:

Problems occurred when invoking code from plug-in: "org.eclipse.jface".


You can view the error log by going to the plug-in development perspective where at the bottom there is a tab Error Log (next to Tasks). I found:

java.lang.NoClassDefFoundError: com/ibm/icu/text/Bidi


Google gave me 2 threads on this problem: http://fusesource.com/forums/thread.jspa?messageID=1275 and http://www.eclipsezone.com/eclipse/forums/m92238620.html.

Solution was to update the com.ibm.icu_3.6.1.v20070906.jar in the plugins directory with a more recent version, like: com.ibm.icu_3.8.1.v20080530.jar. You can find this update at http://download.eclipse.org/tools/orbit/downloads/drops/R20080807152315/.