Android First Example: Hello World

Android First Example: Hello World


Android is a software stack for mobile devices that includes an operating system, middleware and key applications. 

The Android SDK contains API necessary to begin developing applications on the Android platform using the Java programming language.
In this article I point out the steps for making the hello world example and running it in the emulator.

The Steps:

In order to write the example follow these steps

  • The Android SDK

    • Extract it into your hard drive directory

  • Java Code

    • Make a new java project
    • set in the project class path android.jar (you can find it in sdk zip file)
    • make a new java class into
    • copy this source code in

//package name must be composed of at least two java identifiers

import android.os.Bundle;
import android.widget.TextView;

    public class Hello extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        //Make a new text view passing Activity object
        TextView tv = new TextView(this);
        //Set a text into view
        tv.setText("Hello World");
        //set the view into activity view container

    • compile code

  • Build and install The apps

    • In tools sdk directory you can find activitycreator.bat, launch it by passing the complete package name and class name:
activitycreator -o c:\android

    • The script prepare the android application putting it into c:\android directory

    • Now you need ant tools in order to build the android application
Download it from:

    • Go in c:\android directory
    • Launch: "ant -f build.xml" command
(note: if you go in "Unable to locate tools.jar" error you must set correctly jdk classpath.)
you'll be left with a file named Hello-debug.apk under the 'bin' directory

    • Go again in tools sdk directory.
Now you can use adb command in order to install the apk file into android emulator

    • First launch the emulator (if you don't adb command fails)
(note: in order to launch emulator you must execute the emulator.exe command in sdk tools directory.)

    • Then launch the follow command: adb install c:\android\bin\hello-debug.apk

  • Run The example

    • Close the emulator
    • Re-launch the emulator

    • Click on the arrow in the bottom of the screen so you open the application list, now you can 

    • find hello application.. click on it to see the hello word string..


It is only a small example introducing android development.
The next step is to go deep into

Please leave a feedback in the comment to this post.

Java and OpenOffice BASE db through HSQLDB jdbc

Java and OpenOffice BASE db


A Base document can create an HSQLDB database that is stored inside of the Base document.
OOo documents are stored as zip files and Base documents are no exception.

So HSQLDB is the internal engine of OpenOffice db

In this article we see how can interact by java source code with OpenOffice base db using the hsqldb jdbc driver.

The Steps:

In order to write the example follow these steps

  • Prepare ODB database with openoffice 

    • Create a new office base database(i.e. mydb.odb).
    • Create a new table(i.e. User) into base database.
    • Make the coloumns inside the table(ID,firstname,lastname)
    • Populate it with some rows

  • Prepare HSQLDB extracting it from ODB

    • Rename the mydb.odb file in, extract "database" directory from it, so you can find these files:
      • backup
      • data
      • properities
      • script
    • Copy the files into c:\mydbdir\ location
    • rename all the files by putting the same prefix before the file name, example:
      • mydb.backup
      • mydb.properities
      • mydb.script

            The prefix and filename are separated by dot. These files is the HSQLDB.


We are ready for source code!

The Source Code

import java.text.ParseException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main

     * @param args the command line arguments
    public static void main(String[] args) throws ParseException
            String db_file_name_prefix = "c:\\mydbdir\\mydb";
            Connection con = null;
            // Load the HSQL Database Engine JDBC driver
            // hsqldb.jar should be in the class path or made part of the current jar

            // connect to the database.   This will load the db files and start the
            // database if it is not alread running.
            // db_file_name_prefix is used to open or create files that hold the state
            // of the db.
            // It can contain directory names relative to the
            // current working directory
            con = DriverManager.getConnection("jdbc:hsqldb:file:" + db_file_name_prefix, // filenames
                    "sa", // username
                    "");  // password

            Statement statement = con.createStatement();
            //look at " for table name
            ResultSet rs = statement.executeQuery("SELECT * FROM \"User\"");

            //print the result set
            while (
                System.out.print("ID: " + rs.getString("ID"));
                System.out.print(" first name: " + rs.getString("firstname"));
                System.out.println(" last name: " + rs.getString("lastname"));


        } catch (SQLException ex)
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex)
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);


The odb is a zip file, so the beginning steps is uncomfortable because you must rename the odb in zip, rename, work on it and then recompress all in order to edit the odb again with openoffice.
In order to avoid this incovenient way it is possible to make the beginning steps automatically by using package:

Please leave a feedback in the comment to this post.

Search and Find a JAR

Search and Find a JAR

clicca qui per la versione in italiano

Sometimes when you download library, or simply classes the  provided package is not inclusive of all necessary dependencies. 
Therefore the need for this and in other cases, find jar containing a given class. 

The solution:

I found a good online service that can resolve the problem of finding, given the name of a class, the name of the jar file that contains this class in it. 

The service is available from the site 

It then helps to solve the exceptions: 

  • NoClassDefFoundError
  • ClassNotFoundException


For example, by typing the name of the class XMLSerializer 

You get the following output: 

[CLASS] XmlSerializer
[CLASS] org.xmlpull.v1. XmlSerializer
[CLASS] org.kxml2.wap.Wb xmlSerializer
[CLASS] net.sf.json.xml. XMLSerializer
[CLASS] com.idoox.util.xml. XMLSerializer
[CLASS] oracle.xml.binxml.Bin XMLSerializer
[CLASS] XmlSerializer
[CLASS] org.vraptor.remote.xml. XMLSerializer

In this case, not finding a jar containing the class XMLSerializer, the system proposes the complete package name of classes similar to INPUT typed. 

If you click on XmlSerializer or type it as input, since, to name a complete package and the correct output proposes the names of the JARs that contain the specific class: 

Containing JAR 


A short article to link a simple but sometimes very useful website. 
If you want to point out interesting services and leave a comment to this post. 

Facebook Java Api(ENG)

Facebook Java Api Example


This article explain the facebook java api through an example.
First you need a facebook account, and you have to enable "Developer" application.

Then you must configure you account and make a new application configuration in order to obtain 
"api key" and "secret key".
This can be accomplished by reading

The Server

You need a java web server (tomcat, glassfish, jboss etc.) available by the web.
Localhost server isn't ok to facebook integration purpose.

Facebook Java Api

If you want to interact with facebook platform a client library can be very useful.
Client library are available in different languages:

There isn't a officiale Java api but you can choose alternative unofficial ones:

I prefer the last one.
So go to and download (or later).
When you download it, extract the jar into a directory and get it available in you facebook example application classpath.

Facebook server make available user data, photos, groups infos etc by rest api:

The Facebook Client Project

Make a new Web project, and make a new empty servlet.
The servlet url-pattern configured in web.xml must be the same indicated in facebook application configuration.

The Source Code

public class index extends HttpServlet

    //facebook give it!
    String apiKey = "your api key";
    String secretKey = "your secret key";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
        PrintWriter out = response.getWriter();
            out.println("<h2>User information</h2>");

            //facebook login mechanism give you by http parameter the session key
            //needed for client api request.
            String sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());

            //initialize a facebook xml client (you can choose different client version: xml, jaxb or json)
            //the init is done by apiKey, secretKey and session key previosly requested
            FacebookXmlRestClient client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);

            //This code line obtain the user logged id
            Long uid = client.users_getLoggedInUser();

            //print user info.
            out.println(printUserInfo(uid, client, sessionKey));


private String printUserInfo(Long uid, FacebookXmlRestClient client, String sessionKey) throws FacebookException
        StringBuffer ret = new StringBuffer();
        //init array parameter
        ArrayList<Long> uids = new ArrayList<Long>(1);
        //init field parameter - we choose all profile infos.
        List<ProfileField> fields = Arrays.asList(ProfileField.values());
        //init the client in order to make the xml request
        client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);
        //get the xml document containing the infos
        Document userInfoDoc = client.users_getInfo(uids, fields);
        //for each info append it to returned string buffer
        for (ProfileField pfield : fields)
            ret.append(pfield.fieldName()).append(" <b>").append(userInfoDoc.getElementsByTagName(pfield.fieldName()).            item(0).getTextContent()).append("</b>");
        return ret.toString();

In this simple manner you can print all logged facebook user info into facebook application. In order to make a cleary client authentication by using java servlet filter you can read this: 

TrovaTv Samsung and facebook


MDB(Message Driven Bean)(ENG)

MDB - Introduction on Message Driven Bean through an Example

clicca qui per la versione italiana

MDB (Message Driven Bean) is a special type of bean that can perform certain acts in relation to the receipt of a JMS message.
It therefore does not respond to requests for a client but does the connection with "receiving a message."

Receiving a second domain chosen either on a topic or a tail.

The MDB is nothing but a JMS client operating currently received on a queue.

The Example

Suppose you want to create a MDB can process the web requests arriving on a given url(a servlet).
The MDB collect data on the object HttpServletRequest in order to keep a log file.

So any access to the MDB opens the file, and writes in the information: IP address of the client, user-agent, etc timestamp of the request.

But why have carried out such operations all'MDB? The JMS asynchronous system does not block the execution of the servlet pending operations (opening, writing files etc.) Log (useless to the user).

Initialize projects

In order to implement the project to create an application form with EAR WEB and EJB module.
The WEB module include the producer of messages EJB put the consumer: the MDB.

Elements from the example

As in any application will JMS 3 key elements:

  • provider of messages
  • client that produces messages
  • client that consumes messages

Comments about our 3 element list

  • provider messages - Queue to create the server resources in a position to collect the messages produced.
  • client that produces messages - Servlet (or rather a filter) that sends the message
  • client that consumes messages - MDB that processes the message by storing some data on file.

Configuring the JMS Provider 

I state that the provider, or rather its configuration, idepend on application servers used in this case it is used Glassfish V2.

Open the administration panel. For example, on localhost: 4848.
On Resources -> JMS Resources -> Connection Factories
You can create a new connection factory:

insert the JNDI name, or the value that allows you to find resource in the container, set as a kind of resource QueueConnectionFactory because we want to use in a specific queue and leave all other options.

Glassfish creates a pool of connections to the queue so as to maximize the reuse of open connections to the factory in the same way that optimizes for example jdbc to a db.

Likewise, you can create a Destination:

Choosing as usual the JNDI name, the name of the physical destination and type of destination that, in this case is a queue.

Client that produces messages

The message will be produced in relation to access to a given url, we will use


So we must create and test a servlet filter to test the servlet, in the web of course (war).

The filters intercept request so permits to edit request and the response of a given url pattern to forward the servlet or jsp or call or one or more other filters. They provide the ability to create units of code across multiple riusabile url (servlet or jsp) and create real chains filters (structuring development in a kind of plugins)

About the servlet build a trivial hello world servlet:

package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 * @author PeppeM
public class test2 extends HttpServlet {
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {            
            out.println("<title>Servlet test2</title>");  
            out.println("<h1>ESEMPIO MDB - WEB TRACKING</h1>");
        } finally { 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);

    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);

    * Returns a short description of the servlet.
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>


Prepare an object DTO (Data Transfer Object) 

Able to encapsulate the data that will serve the consumer client! 
This subject should be put in the EJB project and not in the WEB. 

import java.util.Date;
import javax.servlet.http.HttpServletRequest;

public class RequestDTO implements Serializable{
    String user_agent;
    private String remote_addr;
    private String query_string;
    private String method;
    private Date date;

    public String getMethod()
        return method;

    public void setMethod(String method)
        this.method = method;

    public String getQuery_string()
        return query_string;

    public void setQuery_string(String query_string)
        this.query_string = query_string;

    public String getRemote_addr()
        return remote_addr;

    public void setRemote_addr(String remote_addr)
        this.remote_addr = remote_addr;

    public String getUser_agent()
        return user_agent;

    public void setUser_agent(String user_agent)
        this.user_agent = user_agent;
    public RequestDTO(HttpServletRequest request)
        user_agent = request.getHeader("user-agent");
        remote_addr = request.getRemoteAddr();
        query_string = request.getQueryString();
        method = request.getMethod();
        date = new Date();

    public String toString()
        return date + " " + this.remote_addr + " " +  this.getMethod() + " " +  this.getUser_agent() + " " +  this.query_string + "\r\n";

It is a simply object that extracts the necessary data and makes them available through the methods accessories. 
Note: The object must be Serializable! 

Also noteworthy is the override of the toString method to copy the value of all fields in a string DTO. 

The filter should instead look into the production of messages.

Create a new filter, using the wizard of NetBeans.
Still using the NetBeans wizard can automatically generate the code for the connection factory and the tail set up earlier.
In that case, click the right mouse button on the code of the filter and select

Enterprise Resources -> Send JMS Message

Setting the correct values in how to create resources referencing application server.

Or you can write by hand the following methods:

 private Message createJMSMessageFormyDestination(Session session, Object messageData) throws JMSException
        ObjectMessage m = session.createObjectMessage((Serializable)messageData);                
        return m;

    private void sendJMSMessageToMyDestination(Object messageData) throws NamingException, JMSException
        Context c = new InitialContext();
        ConnectionFactory cf = (ConnectionFactory) c.lookup("java:comp/env/myQueueFactory");
        Connection conn = null;
        Session s = null;
            conn = cf.createConnection();
            s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
            Destination destination = (Destination) c.lookup("java:comp/env/myDestination");
            MessageProducer mp = s.createProducer(destination);
            mp.send(createJMSMessageFormyDestination(s, messageData));
        } finally
            if (s != null)
            if (conn != null)

automatically generated by NetBeans. 

To sum up the code to send the message you perform the following steps:

  1. Lookup resource ConnectionFactory
  2. creation of the connection
  3. creation of the session
  4. Lookup of destination
  5. Creation of client producer
  6. Sending message
  7. Closing session and connection

Then in the main method of filtering doFilter(ServletRequest request, ServletResponse response,                FilterChain chain)

you can call the method of sending the message

sendJMSMessageToMyDestination(new RequestDTO(request));

The content of the message will be the object of type HttpServletRequest request.
This object contains all the useful information log on to writing required on MDB.

Test production of messages 

Before you generate the client can consume messages produced by the filter, you should check if it works as a production, and launch the project and EAR call servlet test on which the filter is mapped. 

You may experience the following problem: 

javax.naming.NameNotFoundException: myQueueFactory not found
        at com.sun.enterprise.naming.TransientContext.doLookup(
        at com.sun.enterprise.naming.TransientContext.lookup(

This indicates that the value used in JNDI lookup phase is erroneous. 
In our case, for example NetBeans default considers the resources located in the path JNDI java: comp / env / resourcename, but when creating Glassfish included resources in the root, then you must make the following changes being lookup: 

ConnectionFactory cf = (ConnectionFactory) c.lookup("myQueue");

Destination destination = (Destination) c.lookup("myDestination");

Client that consumes messages - The MDB

Inside the EJB project, create an MDB. 

Once again you can use the wizard of NetBeans. 

Or hand-write the following code: 

package MDB;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;

@MessageDriven(mappedName = "myDestination", activationConfig =  {
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")

public class myMDBBean implements MessageListener {

    public myMDBBean() {

    public void onMessage(Message message) {

Through the use of dependency injection with a few notes you can instantiate the client JMS (the MDB).

@MessageDriven(mappedName = "myDestination", activationConfig =  {

        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),

        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")


  It indicates that the bean is MessageDriven and add a couple of properties to indicate the type of destination (queue or topic) and the destination itself (previously set by the system). 
  With only another step you end configuration dell'MDB it is necessary to implement the MessageListener 
public class myMDBBeanimplements MessageListener {
public void onMessage (Message msg) {
FileWriter fw = null;
ObjectMessage m = (ObjectMessage) message;//casting per estrarre la corretta tipologia di messaggio
RequestDTO requestDTO = (RequestDTO) m.getObject();//estrazione dei dati dal messaggio

//open. write and close the file
fw = new FileWriter("c:\\logmdb.txt", true); //look! the windows path.

} catch (IOException ex)
Logger.getLogger(myMDBBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (JMSException ex)
Logger.getLogger(myMDBBean.class.getName()).log(Level.SEVERE, null, ex);
} finally
} catch (IOException ex)
Logger.getLogger(myMDBBean.class.getName()).log(Level.SEVERE, null, ex);



The example is able to process data without losing time, "the servlet so that they write in a log file.
Indeed launching 'n' times the servlet will notice the inclusion of n lines in the log file.

Note: Possible Problems
If the file server.log Glassfish note of the following string

DirectConsumer: Caught Exception delivering can not be cast to com.sun.messaging.jms.ra.DirectPacket

know that this is a know issue / issues / show_bug.cgi? id = 3988
  With the technology JMS client even if the consumer is not active at the time was posted, the messages will be delivered later. 
To demonstrate this, it is possible
  • delete temporary the mdb project;
  • delete the log file "logmdb.txt"
  • build and redeploy the project on the serv
  • launch the servlet test (which will generate a message to every call).

  • remake the MDB
  • build and redeploy the project on the server

  WITHOUT launch servlet will notice that the logs were put on the line calls when the MDB 
was not completely present.

The MVC Design Pattern in Java EE (Eng Ver)

MVC - Java EE (Eng Ver)

MVC is a design pattern (a general design solution for problem solving) widely used in software design. 
MVC Stands for Model Controller View. 
MVC is achieved through 3 components: 

  • the model contains the data and provides methods for accessing them;
  • The view displays the data in the model;
  • the controller receives the commands(usually through the view) and implement them by changing the status of the other two components

This pattern ensures the division between business logic(managed by the model) and user interface (run by and view controller). 

Wanting to apply this pattern to the Java EE, you can use the following Java technologies applied to various components of the pattern. 

Model: This component can be implemented through the entity bean and session bean 
Controller: It can be implemented by the servlet. 
View: The latter through jsp and / or jsf. 

The entity bean will be an abstraction and then to represent the data, the session bean can perform operations on the entity, 
the servlet will collect input from jsp (you) to make requests to the session bean and communicate results to jsp and so on. 


You have to implement a web application that allows you to view / edit the data in a table "users" in a db. 

Table: Users 
The columns: id, name, first name 

Insert into table one data row in order to have at least one default user. 

Suppose you use a persistence provider, for example hibernate 
For this element(users table) you can create an entity bean. 
Make a session bean with entitymanager that realize the methods "edit" and "find." 

  • edit - Will carry out the update users compared to the database using the entitymanager method merge.
  • find - made an id, returns the entity bean that represents the data in the table that are in line with id indicated.
  • .. You can also implement the methods "create", "erase" to complete.

By implementing this portion of the project, it gets the "Model" 

We implement a servlet(the servlet user) that calls through resource injection, @EJB, the session bean. 
Then by invoking the servlet model and using the method find(1) you can get the equivalent entity containing the data with id = 1; 

If the servlet receives the GET or POST parameter "id", "name" and "surname" then perform the upgrade db, creating a new entity with the data passed through http parameters and calling the method of the edit session bean. 
(Note that when you leave the entity EJB components, which are used for example, web components, entering into a state-managed ..) 

The servlet in this case the controller realized. 

The servlet article in question sets the request attribute "user" setting the panel obtained from the user session bean and using a RequestDispatcher performs a forward to a jsp that takes care to show a html form that allows the reading and editing of data. 
The modification done by calling the servlet users start moving their appropriate values. 

This short article does not have the presumption to be exhaustive, as implied in various concepts and technologies .. may be the point of departure for an approach to MVC in Java EE. 

For a complete example click here