Archive

Archive for the ‘Java’ Category

About some of the new features of Java 8 …

March 30th, 2013 No comments

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.

Categories: .Net, ASP.NET, C#, Java Tags:

[GWT] How to print a widget or a page

January 30th, 2013 No comments

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

Categories: GWT, Java Tags:

[JPA 2] Criteria API and MetaModel

September 12th, 2012 No comments

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 :
Read more…

Categories: Criteria, Java, Java EE, JPA, JPQL Tags:

My presentation of GWT 2.4

June 6th, 2012 No comments

I have recently done a presentation of GWT 2.4
It is now available on slideshare.net :

I might work on it again later. To make it a bit nicer.

Categories: Architecture, Eclipse, GWT, Java, Maven, MVP Tags:

Read a properties file external to a webapp

April 9th, 2012 No comments

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

February 18th, 2012 No comments

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

Categories: Eclipse, Java, Maven Tags:

Coding my first Android application

January 1st, 2012 No comments

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 :
Read more…

Categories: Android, Eclipse, Java Tags:

Java puzzlers

May 29th, 2011 No comments

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);
    }
}

Read more…

Categories: Java Tags:

[Tutorial] Create a Maven project and import it with m2Eclipse

February 19th, 2011 No comments

In this video tutorial, I show how to create a Maven project under DOS. Then how to import it to Eclipse with m2Eclipse.
Read more…

Categories: Eclipse, Java, Java EE, Maven, Tutorials Tags:

[Tutorial] WSDL to Java with Apache CXF and soapUI

February 1st, 2011 No comments

The WSDL2java command generates JAX-WS compliant Java code for the services that are defined in the WSDL document.
This is known as the Top-Down approach (contract first, based on an existing WSDL file).
Read more…

Categories: Apache CXF, Java, Tutorials, Web Services Tags:

My book on EJB 3 is now on sale

July 3rd, 2010 No comments

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

April 14th, 2010 No comments

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.

Read more…

Categories: Java, Scala Tags:

DAO design pattern in a session bean ?

March 28th, 2010 No comments

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.

bools or ints ?

December 20th, 2009 No comments

Comic272

Categories: Java Tags:

Escaping quotes in Java

September 11th, 2008 No comments

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

Categories: Java Tags:

Object-oriented Programming in Java

July 6th, 2008 No comments

A good free book about Object-oriented Programming in Java !

Get it here :

http://computing.southern.edu/halterman/OOPJ/index.html

Categories: Java Tags: