Posts Tagged ‘java’

Glassfish 4.0 : “Hello world” application with Maven 3

The following steps will allow you to develop and deploy a first demo web-app with Glassfish Server 4.
1) To install Glassfish 4.0 follow the steps at
For example, you can get the zip version and extract into: C:\glassfish4.

2) If you´re working on a Windows Desktop Rename glassfish4/glassfish/bin asadmin to *.s to prevent the following Maven error:
Unable to start domain "domain1". IOException: Cannot run program"C:\glassfishv3\glassfish\bin\asadmin": CreateProcess error=193, %1 is not a valid Win32-Application

In this way The system will run asadmin.bat, instead of calling the Linux script (provided with no file extension by Glassfish).

3) On Eclipse install Glassfish plugin ( to manage the server graphically. Otherwise you would not be able to installing with the command File>New>Other>Server> etc.
Starting Glassfish for the first time, you will have a user called “admin” with no password. You can manage Glassfish with Admin-Console available at: http://localhost:4848/ or even with asadmin CLI console (under C:\glassfish4\glassfish\bin).

4) To deploy your application using Maven, create the settings.xml file under the .m2 folder (for example, under Windows at the location: C:\Users\username\.m2), providing the glassfish profile credentials: they will automatically imported in the pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="" 

5) Create a new Maven project with the maven archetype “maven-archetype-webapp” template. As a default you can already find the index.jsp HelloWorld page.

6) Add the following plugins to the pom.xml:


					<!-- <webXml>src\main\webapp\WEB-INF\web.xml</webXml> -->



7) Launch the maven command:
clean package glassfish:deploy

You may find errors related to the Dynamic Web Module in the Eclipse project, even if the maven gives you “BUILD SUCCESS”. For now it´s ok.

With the given pom.xml the application will be deployed into:

You can see it up and running at: http://localhost:8080/Glassfish_HelloWorld/

You can manage the applications, for example editing the Content Root folder, directly in the administration console.

Demo Code available at:

JAXB part 8: generate classes from DTD with maven

After using JAXB with XSD schema, I have finally discovered that it´s MUCH better to make it with files and jaxd binding files.

Supposing you want to generate the classes for a web-app xml file, in the Maven pom.xml you need to add something like:

		<!-- if you want to put DTD somewhere else <schemaDirectory>src/main/jaxb</schemaDirectory> -->

In the specified schema directory there must be both the .dtd and the .jaxb binding files.
To specify a package for the generated classes, in the jaxb file like:

<?xml version="1.0" ?>
     <xml-java-binding-schema xmlns:xjc=""
         <options package="deploy.service.webapp" />

You can find a full demo of a web-app xml schema classes generation at sourceforge: JAXB DTD maven demo

Interface as reference data type in Java

So far, I hadn´t understood that interfaces can be used as data types in java. I discovered it while learning depency injection.
An interface in java is a valid referenca data type. If you want to use an interface as reference variabile, make sure your class implements it!

Here is the interface for any liquid container:

public interface LiquidContainer {

void fill(int ml);
void empty();
void wash();
void drink();


The class Glass implements the developed interfaced:

import static java.lang.System.out;

public class Glass implements LiquidContainer{

	public void fill(int ml) {
		out.println("Glass filled with "+ml+"!");

	public void empty() {
		out.println("Your glass is now empty.");

	public void wash() {
		out.println("the glass has been washed.");

	public void drink() {
		out.println("you have drunk from a Glass.");

Mug is another class implementing the interface:

import static java.lang.System.out;

public class Mug implements LiquidContainer {

	public void fill(int ml) {
		out.println("Mug filled with "+ml+"!");

	public void empty() {
		out.println("Your Mug is now empty");

	public void wash() {
		out.println("Your mug has been washed.");

	public void drink() {
        out.println("You have drunk from a mug.");

Then we can define two classes: Superman and Batman mugs extending Mug, without specifying what they implement:

import static java.lang.System.out;

public class SupermanMug extends Mug{

	LiquidContainer liquidContainer;

	public void fill(int ml) {
		out.println("Superman Mug filled with "+ml+"!");

	public void empty() {
		out.println("superman Mug is now empty.");

	public void wash() {
		out.println("Superman Mug has been washed.");

	public void drink() {
		out.println("you have drunk from a Superman Mug!");

And finally a Breakfast class:

public class Breakfast {

LiquidContainer lc;

	static void drinkFromObject(LiquidContainer lc){

	public static void main(String args[]){

		SupermanMug sm=new SupermanMug();
		BatmanMug bm=new BatmanMug();
		Glass glass=new Glass();
		Mug mug=new Mug();


The “drinkFromObject” methods work for any liquid container objects, no matter what the class inheritance is, because it takes an interface (LiquidContainer) as reference data type parameter. The resulte is:

you have drunk from a Glass.
You have drunk from a mug.
you have drunk from a Superman Mug!
you have drunk from a Batman Mug!

Subtle, isn´t it?

Liferay search container pagination problem when passing form parameter SOLVED

Hello, guys!
I’ve been struggling for a couple of days trying to make my seach container pagination works.
When you clicking on the next page and you need to use a form parameter value submitted to get the rows, you need to store it in the portlet preferences, otherwise you lose it in the page “refresh”.

I haven’t found a solution on the web so far, so I’m posting my code snippets… that WORKS lol:
but I’m using portlet preferences … check it out!

[b]action method in the controller:[/b]

		public void searchVolume(ActionRequest request, ActionResponse response)
			throws IOException, PortletException, PortalException,
			SystemException, NoSuchVolumeException {

		String volumeIdentifier = request.getParameter("volumeId");
		long volumeId = (long) Integer.parseInt(volumeIdentifier);
		long idVol = 0;

		boolean found = false;
		boolean emptyList = false;

		List volume = new ArrayList();
		volume = VolumeLocalServiceUtil.getAllVolumes();
		List caseArchive = new ArrayList();
		caseArchive = CaseArchiveLocalServiceUtil

		if (caseArchive.size() == 0) {
			emptyList = true;

		for (Volume itemVolume : volume) {
			if (itemVolume.getVolumeId() == volumeId)
				found = true;

		if (found && emptyList) {
			SessionMessages.add(request, "no-cases-found");
		} else if (found && !emptyList) {
			Volume vol = DBUtil.getVolumefromRequest(request);
			idVol = vol.getVolumeId();

			if (idVol == 1) {
				System.out.println("Volume id iniziale: " + volumeId);
				SessionErrors.add(request, "error-volume");
			} else if (SearchValidator.volumeNotNull(idVol) && !(idVol == 1))

				System.out.println("Volume id action : " + vol.getVolumeId());

				response.setRenderParameter("volId", volumeIdentifier);
				System.out.println("search volume clicked");

				PortletPreferences prefs = request.getPreferences();
				String volumeIdent = request.getParameter("volumeId");
				if (volumeIdent != null) {
					prefs.setValue("volumeIdPref", volumeIdent);;


				SessionMessages.add(request, "search-volume");

		} else
			SessionErrors.add(request, "error-volume");

		response.setRenderParameter("jspPage", viewDatabaseJSP);


[b]JSP page[/b]:



	List volumes = VolumeLocalServiceUtil.getAllVolumes();
	List cases = CaseArchiveLocalServiceUtil.getAllCases();
	Long volumeIdentifier = 1L;

	Collections.sort(volumes, new Comparator() {
		public int compare(Volume o1, Volume o2) {
			Volume p1 = (Volume) o1;
			Volume p2 = (Volume) o2;
			return p1.getVolumeName().compareToIgnoreCase(

	PortletURL portletURL = renderResponse.createRenderURL();

	portletURL.setParameter("jspPage", "/html/admin/viewDatabase.jsp");

	int selected = 0;
	String volSel = null;

	PortletPreferences prefs = renderRequest.getPreferences();
	String volumeId = (String) prefs.getValue("volumeIdPref", "1");


		 1) {
						volumeIdentifier = (long) Integer.parseInt(volumeId);


					List tempResults = DBUtil

					results = ListUtil.subList(tempResults,

					total = tempResults.size();

					pageContext.setAttribute("results", results);
					pageContext.setAttribute("total", total);

					System.out.println("Cur PRINT:" + searchContainer.getCur());

					href="" name='view Case' />

 <a href="<%=cancelURL%>">← Back to Menu</a>

In the example above, volumeId is the form action parameter (passed by the select option), while volumeIdPref is the portlet preferences parameter, which keeps the value while consulting the pages.
In the action method, that is invoked when submitting the form value, i’ve set a response parameter called volId which is used in the jsp to set the variable value when invoking the search-container result page “1”. The render parameter is null when visiting the other pages, but it can be retrieved by the portlet preferences value.

I hope this helps. Let me know if you have questions or suggestions.

Recursive Beer Ballad

Even though I’ve been into Java since 2007, I had never found out how recursion can be powerful when you have to print several lines of code…

So now I’ve just made a funny little programs with a recursive method.

Separating the cases by a switch, this funny Beer Ballad plays even better!

Check it out!



public class Beer {

public static void balladCounter(int n) {
case 0:  System.out.println("No bottles of beer on the wall, no bottles of beer, ya’ can’t take one down, ya’    can’t pass it around, ’cause there are no more bottles of beer on the wall! \n"); break;
case 1:  System.out.println("1 bottle of beer on the wall, 1 bottle of beer,  ya’ take one down, ya’ pass it around, and now there are no more bottles of beer on the wall! \n");
balladCounter(n-1);   break;
case 2:    System.out.println("2 bottles of beer on the wall, 2 bottles of beer,  ya’ take one down, ya’ pass it around, and now just 1 bottle of beer on the wall! \n");
balladCounter(n-1);     break;
default:     // if n>2
System.out.println(n+" bottles of beer on the wall, "+n+" bottles of beer, ya’ take one down, ya’ pass it around, "+(n-1)+" bottles of beer on the wall. \n");
balladCounter(n-1);    break;

public static void main(String[] args) {
int m = 0;   //input from console
String inputString = null;
BufferedReader bufferedReader = null;
System.out.println("How many beers do you want to sing about?");
bufferedReader = new BufferedReader(new InputStreamReader(;

try { inputString = bufferedReader.readLine();

m = Integer.parseInt(inputString);

System.out.println("\n THE BALLAD OF THE BEER \n");
balladCounter(m); }
catch (IOException e) { e.printStackTrace();}