Delete a file from a project generated through a custom maven archetype if a condition is met

With the help of Groovy, we can delete a file from a generated project if it meets a condition (for instance if a maven property equals a certain value).

Here is the procedure :
1) Create the archetype. To do that, type the following command from the root of a Maven project :
mvn archetype:create-from-project
result ==> [INFO] Archetype project created in E:\eclipse\workspace\celinio\target\generated-sources\archetype

The archetype project is here :
/celinio/target/generated-sources/archetype

Copy-paste this folder structure into another folder in the workspace and import it as an existing maven project.
By default, I have decided that this archetype will generate a project which contains a file /src/main/resources/META-INF/configuration.xml. This is the file that I do not want to include if the maven property configurable is set to no.

2) Add the following required property to /celinioArchetype/src/main/resources/META-INF/maven/archetype-metadata.xml

  <requiredProperties>
    <requiredProperty key="configurable">
      <defaultValue>yes</defaultValue>
    </requiredProperty>
  </requiredProperties>

Also add this property to /celinioArchetype/src/test/resources/projects/basic/archetype.properties :
configurable=yes

3) Add the following groovy script archetype-post-generate.groovy under the folder /celinioArchetype/src/main/resources/META-INF/
It will be executed upon creating a project from this archetype.
https://maven.apache.org/archetype/maven-archetype-plugin/advanced-usage.html

/**
* CF : This script will be executed upon creating a project from this archetype.
* https://maven.apache.org/archetype/maven-archetype-plugin/advanced-usage.html
* It will delete a folder called configuration.xml if the value for the "configurable" property
* is set to true.
*/

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

println "artifactId: " + artifactId
println "request: " + request
println "archetypeArtifactId: " + request.getArchetypeArtifactId()
println "archetypeGroupId: " + request.getArchetypeGroupId()
println "archetypeVersion: " + request.getArchetypeVersion()
println "archetypeName: " + request.getArchetypeName()
println "artifactId: " + request.getArtifactId()
println "groupId: " + request.getGroupId()
println "version: " + request.getVersion()

Path projectPath = Paths.get(request.outputDirectory, request.artifactId)
Properties properties = request.properties
String configurableProperty = properties.get("configurable")
println "configurableProperty : " + configurableProperty

if (!configurableProperty.equals("yes")) {
   println "Deleting the configuration.xml file"
   
   Path configPath = projectPath.resolve("src/main/resources/META-INF")   
   String configurationFile = "configuration.xml";    
   Path cxfConfigPath = configPath.resolve(configurationFile)
   println "cxfConfigPath " + cxfConfigPath  
   Files.deleteIfExists cxfConfigPath
}

To test it in eclipse, you will need to create a project from a run configuration as the groovy script is not executed if you go through the wizard (File > New Maven Project > select archetype etc)
See this link for details :
https://bugs.eclipse.org/bugs/show_bug.cgi?id=514993

I have created a repository on github to host the code for this basic maven archetype :
https://github.com/longbeach/mavenArchetypeGroovy

I added two run configuration files which will help testing it.

Add UML diagrams to the JavaDoc

It is possible to add UML diagrams to the JavaDoc generated during the build phase.

The first thing to do is to install Graphviz which is an open source graph visualization software.
After installation, add the bin folder (D:\Graphviz\bin for instance) to the PATH environment variable.
Then configure the pom.xml :

<build>
		<plugins>
			<plugin>
				<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-javadoc-plugin</artifactid>
<version>3.0.1</version>
<configuration>
<doclet>org.umlgraph.doclet.UmlGraphDoc</doclet>
<docletartifact>
<groupid>org.umlgraph</groupid>
<artifactid>umlgraph</artifactid>
<version>5.6.6</version>
</docletartifact>
<additionalparam>-views -all</additionalparam>
<doclint>none</doclint>
<usestandarddocletoptions>true</usestandarddocletoptions>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
			</plugin>
		</plugins>
	</build>

Here i chose to add the maven-javadoc-plugin to the build maven phase. In the configuration of the plugin, i added the UmlGraphDoc doclet.
UMLGraph allows the declarative specification and drawing of UML class and sequence diagrams.

Run mvn install and then check the generated JavaDoc under the folder target/site/apidocs/
Here is a sample :

The code of this project is available on my github repository :
https://github.com/longbeach/eclipseumlgraph

Modularity and plug-ability features in Servlet 3.0 specification with Tomcat 9

Modularity and plug-ability features in Servlet 3.0 specification is also called web fragments. The JSR 315 (Java Servlet 3.0 specification) is already 9 years old. The final release dates back to december 10, 2009.
https://jcp.org/en/jsr/detail?id=315
Web fragments are one of the main features of this JSR.
A web fragment is an XML file named web-fragment.xml and located inside the META-INF folder of a jar library.
The root element of this file must be :

<web-fragment>

Web fragments are XML files that will have part of the configurations of a web.xml file.

Here is a short and quick demonstration of it. First, create a web app project with the help of the maven-archetype-webapp archetype.

Here is the content of the web.xml of this first project :

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

Now create a second project with the help of the maven-archetype-quickstart archetype. Add a resources folder under src/main and then create a META-INF folder under that resources folder. Finally add a new file called web-fragment.xml to that META-INF folder with the following content :

<?xml version="1.0" encoding="UTF-8"?>
<web-fragment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd"
              id="WebAppFragment_ID" version="3.0">
    <name>authentication-fragment</name>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Client</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>client</role-name>
        </auth-constraint>
    </security-constraint>

    <security-role>
        <role-name>client</role-name>
    </security-role>

    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>Client</realm-name>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/login-error.jsp</form-error-page>
        </form-login-config>
    </login-config>

    <error-page>
        <error-code>404</error-code>
        <location>/home.jsp</location>
    </error-page>

</web-fragment>

Add this second project as a dependency in the first project :

...
	<dependency>
			<groupId>com.celinio</groupId>
			<artifactId>secondproject</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
...

Now if we deploy the artefact mainproject.war to a web server such as Tomcat for instance, the following web.xml will be produced :

15-Dec-2018 18:42:12.960 INFO [main] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [E:\devJava\apache-tomcat-9.0.13\webapps\mainproject.war]
15-Dec-2018 18:42:13.194 INFO [main] org.apache.catalina.startup.ContextConfig.webConfig web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>  <display-name>Archetype Created Web Application</display-name>




  <servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
      <param-name>listings</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>0</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
      <param-name>fork</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>xpoweredBy</param-name>
      <param-value>false</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
  </servlet>

...
<security-constraint>
    <web-resource-collection>
      <web-resource-name>Client</web-resource-name>
      <url-pattern>%2F*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>client</role-name>
    </auth-constraint>
    <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
  </security-constraint>

  <login-config>
    <auth-method>FORM</auth-method>
    <realm-name>Client</realm-name>
    <form-login-config>
      <form-login-page>/login.jsp</form-login-page>
      <form-error-page>/login-error.jsp</form-error-page>
    </form-login-config>
  </login-config>

  <security-role>
    <role-name>client</role-name>
  </security-role>



</web-app>
With Tomcat 9, to view the content of the generated web.xml, it is necessary to add the logEffectiveWebXml attribute to the context tag in the context.xml file located under the conf folder and set it to true :
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for each web application -->
<Context  logEffectiveWebXml="true">

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>
During the deployment, the web server scans and treats the various web fragments that it might find. It will concatenate all the fragments to the main web.xml file. This is a simple demonstration. You might be wondering what might happen if there is more than one web fragment file and more precisely in which order will they be added to the generated web.xml. Well, to deal with that, the absolute-ordering tag was added :
<web-app>
...
<absolute-ordering>
   <name>MyFirstFragment</name>
   <name>MySecondFragment</name>
</absolute-ordering>
...
</web-app>

Finally, the web fragments can also contain ordering themselves with the use of the ordering tag :
<web-fragment>
<name>MyFirstFragment</name>
...
<ordering>
   <before>
   		<name>MySecondFragment</name>
   </before>
</ordering>
...
</web-app>

The code of this small demonstration is on my github account :
https://github.com/longbeach/webfragments.git


Variable which is “effectively final” in Java 8

Java 8 has an interesting feature that I learnt recently.
A variable can become “effectively final”.
Very useful.
For instance, the following class would not compile in Java 1.7.
It would return the following error :
“Cannot refer to the non-final local variable myVocabulary defined in an enclosing scope”.
It would require to add the modifier FINAL to the myVocabulary variable.
In Java 8, there is no need to make it final but make sure you do not change the value once assigned.

package com.celinio.training.threads;

import java.util.Hashtable;

public class MainApplication {
	public static void main(String[] args) {
         // No need to declare this variable FINAL
		Hashtable<String, Integer> myVocabulary = new Hashtable<String, Integer>();

		Thread t = new Thread() {
			public void run() {
				try {
					Thread.sleep(2000);
					myVocabulary.put("Hello", 1);
					myVocabulary.put("Bye", 2);
                   // Compilation error in Java 8
                   // myVocabulary = new Hashtable<String, Integer>();
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}
}

Assigning a new value to the myVocabulary variable (line 28) would produce an error at compilation time :
“Local variable myVocabulary defined in an enclosing scope must be final or effectively final”

How is the cyclomatic complexity of an algorithm calculated ?

When checking the issues detected by Sonar, i noticed a few issues related to cyclomatic complexity.
The usual message is clear :

The Cyclomatic Complexity of this method “checkSomething” is 22 which is greater than 12 authorized.

Indeed, the method checkSomething has way too many if conditions :

private static SomeDto checkSomething(AnotherDto anotherDto, String reference)
{
SomeDto someDto = new SomeDto();

// condition 1
if (!someDto.getA())
    return new SomeDto("bla1", "blabla");

// condition 2
if (someDto.getName2() == null || checkSurName(anotherDto.getName()))
    return new SomeDto("bla2", "blabla");

// condition 3
if (someDto.getName3() == null || checkSurName(anotherDto.getName()))
    return new SomeDto("bla3", "blabla");

// condition 4
if (someDto.getName4() == null && checkSurName(anotherDto.getName()))
    return new SomeDto("bla4", "blabla");

// condition 5
if (someDto.getName5() == null || checkSurName(anotherDto.getName()))
    return new SomeDto("bla5", "blabla");

// condition 6
if (someDto.getName6() == null && checkSurName(anotherDto.getName()))
    return new SomeDto("bla6", "blabla");

// condition 7
if (someDto.getName7() == null && checkSurName(anotherDto.getName()))
    return new SomeDto("bla7", "blabla");

// condition 8
if (someDto.getName8() == null && checkSurName(anotherDto.getName()))
    return new SomeDto("bla8", "blabla");

// condition 9
if (someDto.getName9() == null && checkSurName(anotherDto.getName()))
    return new SomeDto("bla9", "blabla");

// condition 10
if (someDto.getName10() == null && checkSurName(anotherDto.getName()))
    return new SomeDto("bla10", "blabla");

// condition 11
if (someDto.getName11() == null && checkSurName(anotherDto.getName()))
    return new SomeDto("bla11", "blabla");

return someDto;
}

Question : how is the cyclomatic complexity of an algorithm calculated ?
Cyclomatic complexity is the number of independent paths through the program.
A program can be seen as a connected graph.
The formula is the following :
v(g) = e – n + 2P
where
e = number of edges
n = number of nodes
P = the number of exit points (usually only 1)

An edge connects 2 nodes. It represents non-branching and branching links between nodes.
Nodes are decisions points which may be conditional statements like if, if … else, switch, while, etc.
This metric was developed by Thomas J. McCabe in 1976.

Well, after further investigation and according to this link (checkstyle tool), I have concluded that the McCabe formula is not really applied to calculate the cyclomatic complexity in a Java program.

The complexity is equal to the number of decision points + 1 Decision points: if, while , do, for, ?:, catch , switch, case statements, and operators && and || in the body of target.

So if I apply this rule to the previous sample code :


private static SomeDto checkSomething(AnotherDto anotherDto, String reference)  // 1
{
SomeDto someDto = new SomeDto();

// condition 1
if (!someDto.getA())                                 // 2
return new SomeDto("bla1", "blabla");

// condition 2
if (someDto.getName2() == null || checkSurName(anotherDto.getName()))  // 4
return new SomeDto("bla2", "blabla");

// condition 3
if (someDto.getName3() == null || checkSurName(anotherDto.getName()))  // 6
return new SomeDto("bla3", "blabla");

// condition 4
if (someDto.getName4() == null && checkSurName(anotherDto.getName()))  // 8
return new SomeDto("bla4", "blabla");

// condition 5
if (someDto.getName5() == null || checkSurName(anotherDto.getName()))  // 10
return new SomeDto("bla5", "blabla");

// condition 6
if (someDto.getName6() == null && checkSurName(anotherDto.getName())) // 12
return new SomeDto("bla6", "blabla");

// condition 7
if (someDto.getName7() == null && checkSurName(anotherDto.getName()))  // 14
return new SomeDto("bla7", "blabla");

// condition 8
if (someDto.getName8() == null && checkSurName(anotherDto.getName()))  // 16
return new SomeDto("bla8", "blabla");

// condition 9
if (someDto.getName9() == null && checkSurName(anotherDto.getName()))  // 18
return new SomeDto("bla9", "blabla");

// condition 10
if (someDto.getName10() == null && checkSurName(anotherDto.getName())) // 20
return new SomeDto("bla10", "blabla");

// condition 11
if (someDto.getName11() == null && checkSurName(anotherDto.getName())) // 22
return new SomeDto("bla11", "blabla");

return someDto;
} 

Anyways, the result number of 22 makes sense.
This method has an awful number of successive if conditions and something should be done about it to improve its maintainability. If we would apply strictly the McCabe formula, the result would be strange. At least according to this plugin for Eclipse : Eclipse Control Flow Graph Generator
The flow chart generated is the following :

And the McCabe result would be 1 !

About some of the new features of Java 8 …

Just want to signal something that a lot of Java developers seem not to be aware of :
a few of the upcoming features of the JDK 8 have been available in C# for some time now.

.NET / C# Java
Lambda expressions (closures) .NET 3.5 - C# 3 - 2007 JDK 8 - 2013
Virtual extension methods .NET 3.5 - C# 3 - 2007 JDK 8 - 2013
... ... ...

C# was inspired by Java and C++ and now it kind of feels like Java 8 is catching up with C# !
But it is a good thing when the languages influence each other.
That is the case with C# and Java but that is also the case with Windows Forms / WPF + XAML and JavaFX 2 / GWT or ASP.NET MVC and Java MVC-based frameworks, etc.

That is another good reason to be open to both worlds.

[GWT] How to print a widget or a page

To print a widget or an entire page with GWT, you can use JSNI and the JavaScript print function.

A good practice is to put all the content you want to print inside a DIV tag, for instance :

<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:p1="urn:import:com.mycompany.gwtproject.client.common.ui.composite">
	<ui:style>
		/* Add CSS here. See the GWT docs on UI Binder for more details */
		.important {
			font-weight: bold;
		}
	</ui:style>
...
<div id="printAll">
	<g:Label text="Some title" styleName="pageTitle" />		
	<div style="height:30px"></div>
		<p1:DetailAgency ui:field="detailAgency " />
	<div style="height:30px"></div>
		<p1:DetailCountry ui:field="detailCountry" />
	<div style="height:15px"></div>
</div>
<div style="float:left;margin-right:20px">
		<g:Button text="Print" ui:field="printBtn" />
</div>

An id is assigned to that DIV tag (line 10) and a button is added to the page. It calls the Java print method from the Print class:


import com.mycompany.gwtproject.client.service.print.Print;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
...

public class MyViewImpl extends Composite implements MyView {
...
@UiField
Button printBtn;

@UiHandler("printBtn")
void onPrintBtnClick(ClickEvent event) {
	Element element = DOM.getElementById("printAll");
	Print.it(element);
}

This class Print.java contains several methods it that help you print the window, a widget, etc. In the end, they call the JavaScript print() function :

...
public static native void printFrame() /*-{
        var frame = $doc.getElementById('__printingFrame');
        frame = frame.contentWindow;
        frame.focus();
        frame.print();
    }-*/;
...

You can apply CSS to the printed page. If you work with uiBinder and want to print a widget that has no id defined in the XML template, you can assign one in the corresponding Java class :

...
<g:VerticalPanel ui:field="myDetails">
	<p1:DetailAgency ui:field="detailAgency " />
	<p1:DetailCountry ui:field="detailCountry " />
</g:VerticalPanel>
...

import com.mycompany.gwtproject.client.service.print.Print;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
...

public class MyView2Impl extends Composite implements MyView2 {

@UiField
VerticalPanel myDetails;

@UiHandler("printBtn")
void onPrintBtnClick(ClickEvent event) {
	printBtn.getElement().setId("details");
	Element element = DOM.getElementById("details");
	Print.it(element);
}

This will fire the print window :
Print

Links :
http://code.google.com/p/gwt-print-it/source/browse/trunk/src/br/com/freller/tool/client/Print.java

[JPA 2] Criteria API and MetaModel

I want to mention the Criteria API, a very cool API which in my opinion is not used as much as it should be. The developers who implement the specification (JSR 317: Java Persistence 2.0) do an impressive work. Thanks to them we have an API that makes it possible to write type safe queries in an object oriented way.
Usually Java developers write queries using JPQL or they write native queries. The fact is that the API Criteria has a (small) learning curve : you have to explore the API and study some basic queries examples before writing your own queries. The first time you use it, it does not seem as intuitive as JPQL.

The Criteria API is particularly convenient when writing queries which do not have a static where clause. For instance in the case of a web page where the user can make a research based on optional criterias. Then the generated query is not always the same.

The Criteria API has its advantages and its disadvantages : it produces typesafe queries that can be checked at compile time but on the other hand queries can be a bit hard to read (apparently unlike QueryDSL or EasyCriteria).
Another advantage is that it can help to avoid SQL injection since the user input is validated or escaped by the JDBC driver (which is not the case with native queries).

To create typesafe queries, one uses the canonical metamodel class associated to an entity (an idea originally proposed by Gavin King, as far as i know). A possible definition of a metamodel class could be that one : it is a class that provides meta information about a managed entity. By default, it has the same name as the entity plus an underscore. For instance if an entity is called Employee then the metamodel class is called Employee_. It is annotated with the annotation javax.persistence.StaticMetamodel.
Fortunately you do not have to write them, you can generate them using an annotation processor, through Eclipse or a Maven plugin for instance.
I chose to generate the metamodel classes with the help of the Hibernate Metamodel Generator (an annotation processor) and the maven-processor-plugin maven plugin, at each build so that they are updated whenever the entities are modified. It is a good way to keep the metamodel classes up to date.

<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<version>2.0.5</version>
<dependencies>
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for typesafe criteria queries -->
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-jpamodelgen</artifactId>
    <version>1.2.0.Final</version>
  </dependency>
</dependencies>
<executions>
  <execution>
    <id>process</id>
    <goals>
      <goal>process</goal>
    </goals>
    <phase>generate-sources</phase>
    <configuration>
      <outputDirectory>${project.basedir}/src/main/.metamodel/</outputDirectory>
      <processors>
        <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
      </processors>
    </configuration>
  </execution>
</executions>
</plugin>

<!--  add sources (classes generated inside the .metamodel folder) to the build -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
<executions>
  <execution>
    <id>add-source</id>
    <phase>generate-sources</phase>
    <goals>
      <goal>add-source</goal>
    </goals>
    <configuration>
      <sources>
        <source>${basedir}/src/main/.metamodel</source>
      </sources>
    </configuration>
  </execution>
</executions>
</plugin>

And here is the kind of dynamic query one can create :
Continue reading

Read a properties file external to a webapp

Externalizing part of the configuration of a webapp in a .properties file that is located outside of that webapp (outside the WAR, the EAR …) is a frequent requirement and I initially thought that the PropertyPlaceholderConfigurer class, provided by the Spring framework and which is an implementation of the BeanFactoryPostProcessor interface, would help me to get the values of the properties defined in that external file.
The properties are pulled into the application context definition file.
The typical sample code used to achieve this is the following :


<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations">
      <list>
          <value>file:d:/temp/toto/myFile.properties</value>  
      </list>
     </property
</bean>

<bean id="smtpserverurl" class="com.vendor.SomeSmtpServer">  
    <property name="URL" value="${smtpserver.url}"/>  
</bean>  

or :

<context:property-placeholder location="file:d:/temp/toto/myFile.properties" />

<bean id="smtpserverurl" class="com.vendor.SomeSmtpServer">  
    <property name="URL" value="${smtpserver.url}"/>  
</bean>  

And the properties file :


smtpserver.url=smtp.gmail.com

It is a good solution as long as you do not need dynamic reloading of the properties, i.e. without the need for restarting the application whenever the properties values are changed.
So I find out that in that case the Apache Commons Configuration is a good alternative because it supports dynamic reloading of the properties.
And it is as easy to use as this :


package com.celinio.readprops;
import java.io.File;
import java.util.Iterator;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;

/**
 * This class reads properties that are stored in a file outside the webapp
 * @author Celinio Fernandes
 *
 */
public class ReadExternalPropertiesUtil {
		
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ReadExternalPropertiesUtil.class);

	private static final String PROPERTIES_FILE = "config.properties";
	private static final String ENV_VAR = "PROPERTIES_APP";
	public static String propertiesFolder;
	public static PropertiesConfiguration propertiesConfig  = null;
...

FileChangedReloadingStrategy strategy  = null;
strategy  = new FileChangedReloadingStrategy();
strategy.setRefreshDelay(reloadInterval);
propertiesConfig.setReloadingStrategy(strategy);
propertiesConfig.setDelimiterParsingDisabled(true);

...

Line 23 : the path is given as an environment variable.

It works great. The only problem that I met was when I tested the reload interval (the delay period before the configuration file’s last modification date is checked again, to avoid permanent disc access on successive property lookups), it did not work : if i set the reload interval to 30 seconds for instance and if i modify the properties several times during that delay period, the new property values are still displayed. I would have expected to get the old values again, until the delay period expired.
The source code for this sample webapp is available at http://code.google.com/p/celinio/source/browse/#svn%2Ftrunk%2Fpropreloadable

M2E problem : Plugin execution not covered by lifecycle configuration

I am adding to the blogosphere of development-related blogs another post about the “Plugin execution not covered by lifecycle configuration” error.

The M2E Plugin 1.0.0 is integrated into Eclipse Indigo (3.7). Apparently, M2E connectors, which are a bridge between Maven and Eclipse, require to provide a connector for every plugin that is used in the build.
And if no connector is available, M2E shows the following annoying errors in the Eclipse problems view :

Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-antrun-plugin:1.7:run (execution: run, phase: validate)

Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-resources-plugin:2.5:resources (execution: default-resources, phase: process-resources)

Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-resources-plugin:2.5:testResources (execution: default-testResources, phase: process-test-resources)

Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:properties-maven-plugin:1.0-alpha-2:read-project-properties (execution: default, phase: initialize)

Plugin execution not covered by lifecycle configuration: org.apache.cxf:cxf-codegen-plugin:2.2:wsdl2java (execution: generate-sources, phase: generate-sources)

Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:hibernate3-maven-plugin:3.0-SNAPSHOT:hbm2ddl (execution: default, phase: compile)

Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-ear-plugin:2.6:generate-application-xml

To avoid these errors, it is necessary to modify the pom.xml file so that M2E will not complain about it.

These are the extra lines that I added in my parent pom.xml :

	<build>
<pluginManagement>
	<plugins>
	<!--The configuration of this plugin is used to store the Eclipse M2E settings
                  only. It has no influence on the Maven build itself. -->
	<plugin>
		      <groupId>org.eclipse.m2e</groupId>
		      <artifactId>lifecycle-mapping</artifactId>
		      <version>1.0.0</version>
		      <configuration>
		        <lifecycleMappingMetadata>
		          <pluginExecutions>
		            <pluginExecution>
		              <pluginExecutionFilter>
		                <groupId>org.apache.maven.plugins</groupId>
		                <artifactId>maven-antrun-plugin</artifactId>
		                <versionRange> [1.7,)</versionRange>
		                <goals>
		                       <!-- plugin goals-->
		                  <goal>run</goal>
		                </goals>
		              </pluginExecutionFilter>
		              <action>
		             	 <!-- M2E should ignore the plugin-->
		                <ignore />
		              </action>
		            </pluginExecution>
		            <pluginExecution>
		              <pluginExecutionFilter>
		                <groupId>org.apache.maven.plugins</groupId>
		                <artifactId>maven-resources-plugin</artifactId>
		                <versionRange> [2.5,)</versionRange>
		                <goals>
		                       <!-- plugin goals-->
		                  <goal>resources</goal>
		                  <goal> testResources </goal>
		                </goals>
		              </pluginExecutionFilter>
		              <action>
		             	 <!-- M2E should ignore the plugin-->
		                <ignore />
		              </action>
		            </pluginExecution>
		            <pluginExecution>
		              <pluginExecutionFilter>
		                <groupId>org.codehaus.mojo</groupId>
		                <artifactId>properties-maven-plugin</artifactId>
		                <versionRange> [1.0-alpha-2,)</versionRange>
		                <goals>
		                       <!-- plugin goals-->
		                  <goal>read-project-properties</goal>
		                </goals>
		              </pluginExecutionFilter>
		              <action>
		             	 <!-- M2E should ignore the plugin-->
		                <ignore />
		              </action>
		            </pluginExecution>
		            <pluginExecution>
		              <pluginExecutionFilter>
		                <groupId>org.apache.cxf</groupId>
		                <artifactId>cxf-codegen-plugin</artifactId>
		                <versionRange> [2.2,)</versionRange>
		                <goals>
		                       <!-- plugin goals-->
		                  <goal>wsdl2java</goal>
		                </goals>
		              </pluginExecutionFilter>
		              <action>
		             	 <!-- M2E should ignore the plugin-->
		                <ignore />
		              </action>
		            </pluginExecution>
		            <pluginExecution>
		              <pluginExecutionFilter>
		                <groupId>org.codehaus.mojo</groupId>
		                <artifactId>hibernate3-maven-plugin</artifactId>
		                <versionRange> [3.0-SNAPSHOT,)</versionRange>
		                <goals>
		                       <!-- plugin goals-->
		                  <goal>hbm2ddl</goal>
		                </goals>
		              </pluginExecutionFilter>
		              <action>
		             	 <!-- M2E should ignore the plugin-->
		                <ignore />
		              </action>
		            </pluginExecution>
		                  <pluginExecution>
		              <pluginExecutionFilter>
		                <groupId>org.apache.maven.plugins</groupId>
		                <artifactId>maven-ear-plugin</artifactId>
		                <versionRange> [2.6,)</versionRange>
		                <goals>
		                       <!-- plugin goals-->
		                  <goal>generate-application-xml</goal>
		                </goals>
		              </pluginExecutionFilter>
		              <action>
		             	 <!-- M2E should ignore the plugin-->
		                <ignore />
		              </action>
		            </pluginExecution>
		          </pluginExecutions>
		        </lifecycleMappingMetadata>
		      </configuration>
  	</plugin>
...
  </plugins>
      </pluginManagement>
</build>

Links :
http://wiki.eclipse.org/M2E_plugin_execution_not_covered
http://objectledge.org/confluence/display/TOOLS/M2E+Connectors

Coding my first Android application

I finally got the time to develop my first small Android application.
Technical environment :
– Eclipse Indigo
– Android SDK 2.3.3 (Gingerbread)
– An Android phone with Android SDK 2.3.4

I tried to go a little bit further than the traditional “Hello World” sample.
The application, called TeamManagement, is still a simple one : type in a name of a project member and it will display what his role is and when he arrived in the project. That’s it. I explored some nice features : relative layout, autocompletion, popup, menu at the bottom, show/remove image etc.

Main

The project inside Eclipse has the following structure :

The file /MyProject/res/values/strings.xml is where the name of the application is set.

<string name="app_name">TeamManagement 1.0</string>

I chose to organize the layout programatically, instead of declaratively (main.xml) and created a single activity called MyProjectActivity :
Continue reading

Java puzzlers

This week I attended the very first and very well organized conference What’s Next ? in Paris and one of the speakers was Neil Gafter, co-author of the book “Java™ Puzzlers: Traps, Pitfalls, and Corner Cases” (2005).
He shared with us 2 or 3 puzzlers which I will share here too :
Question 1) What will the following program print ?

import java.util.Random;

public class Rhymes {
    private static Random rnd = new Random();

    public static void main(String[] args) {
        StringBuffer word = null;
        switch(rnd.nextInt(2)) {
            case 1: word = new StringBuffer('P');
            case 2: word = new StringBuffer('G');
            default: word = new StringBuffer('M');
        }
        word.append('a');
        word.append('i');
        word.append('n');
        System.out.println(word);
    }
}

Continue reading

My book on EJB 3 is now on sale

I received an email from the editor informing me that the book is now printed and will be available in bookstores next week (from July 5th, 2010).

It is already available for sale on Amazon and ENI.

An online version is also available.

Here is the cover of the book :

SO3EJB_max

First glance at Scala

Today I took a first glance at Scala at the Paris JUG monthly meeting. Scala is a programming language which runs on the Java Virtual Machine.
I have not compiled a single line of code in Scala yet but I saw enough code to get a decent idea of it.
When you think Scala, think about the functional programming paradigme. A function can be a value.
The first speaker, Sader Drobi, showed us a few examples of code to illustrate the advantages of passing a function as a parameter.

Continue reading

DAO design pattern in a session bean ?

I have recently been challenged by a colleague with a .Net background about the way I sometimes use session beans in web applications. Indeed, I like to implement DAOs as session beans.
Some people argue that it’s best not to directly implement CRUD methods in session beans.
The main reason being that they prefer to add another level of separation. For instance :

Session bean client
!
Session bean
!
business object helper class
!
DAO
!
ORM (Hibernate)
!
Database

A good example of this approach is the old implementation (EJB 2.0) of the The Java Pet Store by Sun. (API : http://java.sun.com/blueprints/code/jps131/src/).
My opinion is that this level of separation is not always necessary. And I believe using session beans as DAOs makes even more sense now that in EJB 3.x we have the Java Persistence API (entitymanager)  which already provides generic
database access methods (persist(), merge(), etc) :

Session bean client
!
Session bean DAO (JPA)
!
Entity bean
(JPA)
!
Database

Adam Bien explains it well in this post.

Escaping quotes in Java

Here is a simple tip to replace a quote with a backslash and a quote :
‘ ==> \’

public static String echappeApostrophe(String s) {
String temp;
temp = s.replaceAll(“‘”,”\\\\'”);
return temp;
}

I needed 4 backslashes

To better understand what is happening here, i printed out a few values :

String a = “\'”;
String b = “\\'”;
String c = “\\\'”;
String d = “\\\\'”;

System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);

output :

\’
\’
\\’

This is useful if for instance you need to pass, from a Java program, a string with a quote inside as a parameter to a dynamically generated
JavaScript function.

Else you get a Javascript error because the quote is not escaped.

More info here :

http://java.developpez.com/faq/java/?page=langage_chaine#LANGAGE_STRING_antislash