Facebook Java Api(ENG)__

Facebook Java Api Example
G.Morreale

Introduction:

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 http://developers.facebook.com/get_started.php


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:http://wiki.developers.facebook.com/index.php/Client_Libraries

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


I prefer the last one.
So go to http://code.google.com/p/facebook-java-api/ and download facebook-java-api-2.0.4.bin.zip (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:http://wiki.developers.facebook.com/index.php/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
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try
        {
            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);
        uids.add(uid);
        //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>");
            ret.append("</br>");
        }
        return ret.toString();
    }

Conclusion 
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:
http://www.theliveweb.net/blog/2007/10/31/facebook-authentication-using-java/ 






Glassfish Cluster: LoadBalancer with Apache (ENG)

Glassfish Cluster: LoadBalancer with Apache
G.Morreale

Introduction:
(valid for glassfish v2ur2)

The loadbalancer task is to distribute the traffic between different nodes in the cluster.

The load balancing between the various nodes in the cluster can be achieved in several ways:
LVS, mod_jk, plugins for Glassfish, Apache Rewrite Rule using dedicated equipment etc. etc.
The objective is to examine the different nodes in a particular algorithm in order to load the various nodes in accordance with the requirements of the system.

In subsequent steps, reference is made to configure a LoadBalancer, using the Glassfish plugin and apache webserver.

Using the solution plug-in you can take the following advantages:

- Integration with application servers
- Ability to configure loadbalancing from admin console:

-  Integrated Health Checking System, the module determines if a request is not able to respond in order to eliminate from balancing load.

- Configuring the algorithm of load distribution, with the possibility to load a user-defined one.

- Automatic balancing module, the plugin allows you to automatically or manually export the configuration file for the module so as to make it current, even in real-time, on the structure of the cluster (eg. Addition or deletion of nodes) .

Abstract:

The communication between the Web server that acts as loadbalancer and the DAS is via SSL.
It 'necessary to enable the apache server to support SSL.

The plugin for Glassfish is considered compatible with apache 2.0.x (32 bit version)
so do not use the newer 2.2 or higher.

The steps to be performed are divided into the following macro-steps:

  • Installing and Configuring Apache with SSL support
  • Install the plugin and configure Apache to communicate with the plugin
  • Create and enable the plugin in the DAS


Installing and Configuring Apache with SSL support

The following steps refer to the Windows platform:
For Linux or Solaris, you can follow one of several guides on the web, or alternatively refer to the guidance provided by the sun

Download a version of Apache with openssl:

  • Enable the module on httpd.conf by removing the comment '#'

Ssl_module LoadModule modules / mod_ssl.so


  • Ensure the existence of the following in httpd.conf lines

<IfModule Mod_ssl.c> 
Include conf / ssl.conf 
</ IfModule>


  • Generate the certificate and the key for apache

%% ApacheDIR bin openssl.exe req-new-x509-keyout newreq.pem-out newreq.pem-days 365-config "% ApacheDIR% confopenssl 
. CNF "
(substitute the appropriate path for the file openssl.cnf used) 
Note: the generation of the certificate creates problems with the environment variable that indicates the location of openssl configuration, best to use the switch-config as shown.


WARNING: the common name applied for must correspond to the hostname used on apache. This value will then during the configuration of Glassfish plugin on the host device.


  • Opening with a text editor file newreq.pem

  • copy the portion that goes from

----- BEGIN CERTIFICATE ----- 
to 
----- END CERTIFICATE ----- 

ApacheDIR in file%% / conf / ssl.crt / server.crt 

Instead copy the portion that goes from 
----- BEGIN RSA PRIVATE KEY ----- 
to 
----- END RSA PRIVATE KEY ----- 

ApacheDIR in file%% / conf / ssl.key / server.key 


Note: If you entered a passphrase when generating the key file server.key will have a version of the cryptographic key. Apache, have shown during the opening a dialog to enter your passphrase. 
This dialog box is NOT supported on windows, so you need to remove the passphrase from the key with the following command: 

ApacheDIR%% / bin / openssl rsa-in server.key-out serverNoPhrase.key 

The serverNoPhrase.key is obtained without passaphrase. Make sure the file ssl.conf it points to that file rather than the encrypted or copy serverNoPhrase.keyin server.key and delete serverNoPhrase.key. 
.

  • Start Apache in SSL mode. In windows the command is as follows:
apache-D SSL

  • Test the operation of apache with ssl not forgetting the browser to use https.

WARNING: There may be conflict in the door between Glassfish and apache. 
Reading the log (error.log in apache) or (in Glassfish server.log) to identify the conflict and act accordingly.



Install the plugin and configure Apache to communicate with the plugin

  • Download the plugin from the following link:

SOLARISX86 http://download.java.net/javaee5/external/SunOS_X86/aslb/jars/aslb-9.1-MS4-b1.jar 
SOLARIS http://download.java.net/javaee5/external/SunOS/aslb/jars/aslb-9.1-MS4-b1.jar 
WINDOWS http://download.java.net/javaee5/external/WINNT/aslb/jars/aslb-9.1-MS4-b1.jar 
LINUX http://download.java.net/javaee5/external/Linux/aslb/jars/aslb-9.1-MS4-b1.jar 

Note: http://download.java.net/javaee5/external/ surf to search for any newer versions and other platforms 

In this configuration has been used "aslb-9.1-MS4-b7.jar"

  • Unpack the file. Jar using the command jar-xvf nomefile.jar or using an archiver like WinRar.
  • Zip files obtained (SUNWaslb.zip and SUNWaspx.zip) should be unpacked in the folder lib / lbplugin server
then create the folder "lbplugin" on% GLASSFISH_HOME / lib / and unpack the contents of two files inside. zip 

Note: in linux assign permissions with the command: chmod-R 755 <GLASSFISH_HOME> / lib / lbplugin / lib 

  • Copy the file mod_balancer.dll in <GLASSFISH_HOME> / lib/lbplugin/lib/webserver-plugin/windows/apache2 /
within the modules directory of Apache. 

  • Create and copy within ApacheDir%% / modules / resource files. <GLASSFISH_HOME> In res / lib/lbplugin/lib/webserver-plugin/windows/apache2 /

  • Create and copy within ApacheDir%% / modules / errorpages files in <GLASSFISH_HOME> / lib/lbplugin/lib/webserver-plugin/windows/apache2/errorpages

  • Create and copy within ApacheDir%% / sec_db_files files. <GLASSFISH_HOME> In db / lib/lbplugin/lib/webserver-plugin/windows/apache2 /

  • Copy within ApacheDir%% / conf file loadbalancer.xml.example in <GLASSFISH_HOME> / lib / lbplugin / lib / install / templates / loadbalancer.xml.example
and rename loadbalancer.xml

  • Restart Apache in SSL mode



Create and enable the plugin in the DAS

E 'advisable at this stage of the setup of the open console can read in real time the contents of file error log (for Glassfish server.log and error.log for apache, also in the case of the cluster light not only on the server. log of the domain but also the hub and various forums)

You need to login the Admin console of the DAS, positioned on HTTP Load Balancers and click New to create a new reference to the load balancer.

  • Choose a name for the load balancer, for example apacheLB
  • How Device Host, the host of the same apache configuration in ssl.conf, typed in the same common name when creating the file newreq.pem (certificate + key)
  • How Devce Admin Port, the port number of apache ssl (default is 443)
  • Select the correct target in a way that the points on the cluster loadbalancer
  • The Apply Changes Automatically checkbox can be selected if you want to automatically notify the module to apache balancing with respect to changes in structure of the cluster (eg, adding or deleting nodes instance)
  • After saving the test configuration apacheLB selecting and clicking on Test Connection

Note: In the Export section of the LoadBalancer exists the possibility to export the configuration files necessary to loadbalancer.xml form of balancing apache or edit by clicking on "Apply Changes Now".
About the automatic generation of xml files to the directory of apache on linux you must correctly set the different permissions.

Make sure that the instances in the cluster have enabled load balancing (Click on "Enable Load Balancing" as per image)

The Plug In is configured.

Installing an application on the cluster and check if your browser meets one of the nodes by calling

http://apache_hostname/path_applicazione_cluster

Note: The configuration has been implemented using SSL for communication between the DAS and apache, the load balancing is the case using the normal http protocol.

Possible Problems

Trying to make repeated requests to the loadbalancer you may experience the following errors (see error.log for apache)

[warn] lb.runtime: RNTM2024: Daemon http://MOBISERVER:38081 is unhealthy. 
[warn] lb.runtime: RNTM2030: Daemon Monitor: http://MOBISERVER:38081: could be because daemon is down 
[warn] lb.runtime: RNTM2025: Daemon http://mobipc:38080 is healthy. 
[warn] lb.runtime: RNTM2025: Daemon http://mobipc:38080 is healthy. 
[warn] lb.runtime: RNTM2025: Daemon http://mobipc:38080 is healthy. 
[warn] lb.healthchecker: HLCK3003: Listener: http://MOBISERVER:38081 is still detected to be unhealthy in cluster: cluster 
[warn] lb.healthchecker: HLCK3003: Listener: http://MOBISERVER:38081 is still detected to be unhealthy in cluster: cluster 
[warn] lb.healthchecker: HLCK3003: Listener: http://MOBISERVER:38081 is still detected to be unhealthy in cluster: cluster 
[warn] lb.healthchecker: HLCK3003: Listener: http://mobipc:38080 is still detected to be unhealthy in cluster: cluster 
[warn] lb.healthchecker: HLCK3003: Listener: http://mobipc:38080 is still detected to be unhealthy in cluster: cluster

If instances of the cluster are running in the state and if I answer calls directly on their ip: port means you may be some problem nell'httpd. Conf, it is necessary to check that the virtual host name and server have the correct number name.

In addition, the Apache error.log file is updated by module mod_balancer, and then provide the appropriate automatic rotation of log files or to set a different log level.

Reference Link:


Conclusion:
The article was translated from the italian version i'm wrote before.
I translate it with google translate service and after a fast review and some correction I think that it is a bad english too(I'm sorry).
The article that I wrote directly in english are a little bit better.
however I hope it is helpful.
If you want to correct any sentences please contact me through a comment, don't hesitate!

Clustering and EJB Timer (ENG)

Glassfish Cluster and EJB Timer
G.Morreale

clicca qui per la versione in italiano
Introduction:

One of EJB features is "Timer Service".
It allows you to activate timer for specified periods of time or after certain dates.


This service relies on a embedded Glassfish database.
Go into the console between the connection pool (see JDBC resources) you can see is the connection pool __TimerPool "used by the resource __TimerPool.

This resource is available by default for the target server, then the cluster is not even aware of a db that supports the timer service.

Furthermore, the embedded database is not sufficient as instances of the cluster can not access the db and then know the status of management of the timer service.

Having to deploy on Glassfish cluster that uses an EJB timer service should set up an external db can support transactions and ensure that only one instance to handle the timeout without replicating the events more than necessary.

Steps to configure:

To configure the cluster so that it supports the EJB Timer Service is necessary to follow the following steps

- Create a db (eg TIMER_DB)

- Create in a table using sql scripts that are within $ GLASSFISH_HOME / lib / install / databases
The script mysql is not present you can copy it from here:

CREATE TABLE EJB__TIMER__TBL (
CREATIONTIMERAW bigint NOT NULL,
`` BLOB BLOB,
TIMERID VARCHAR (255) NOT NULL,
CONTAINERID bigint NOT NULL,
OWNERID VARCHAR (255) NOT NULL,
STATE INTEGER NOT NULL,
PKHASHCODE INTEGER NOT NULL,
INTERVALDURATION bigint NOT NULL,
INITIALEXPIRATIONRAW bigint NOT NULL,
LASTEXPIRATIONRAW bigint NOT NULL,
PK_EJB__TIMER__TBL CONSTRAINT PRIMARY KEY (TIMERID)
);

Note: The table name must be uppercase

- Make in "Resource-> Connection Pools" a connection pool that can communicates with the db created.

- Create a resource pointing to the jdbc connection pool you just created.
The resource must be created as the target cluster, to ensure that you can create the resource by clicking on
"Cluster-> name cluster-> Resources-> New-> JDBC Resources"

- Go on the configuration of the cluster (The default is called cluster-config)
select EJB container,
click EJB Timer Service
set in the Timer Datasource jdbc resource name created in previous step.

- Restart the cluster.

Driver XA and Possible problems

To make a good setup needs to be created, as I suggested earlier, a resource jdbc appropriate for the timer.
This choice, however, can create problems when the application that makes use of the timer service simultaneously access a resource jdbc different (for example through hibernate you log on to the connection pool of the db).

In this case the same bean needs to access two resources at once and ensure the ACID properties.
To do this you need a JDBC driver XA-capable

This driver obviously needs to be available in the classpath, eg copying it into the / lib of the domain (default domain1).
(Note: when you update a library, you must restart the application server)

In the case of mysql, the J connector (currently version 5.1.6) is XA compliant.

Besides having a driver with such characteristics is necessary to set the connection pool so that these features are used.
Then in the connection pool should be created as set Resource Type "java.sql.XADataSource" in the field instead DataSourceClassName must set the correct value based on the DBMS used

In the case of this class is mysql
com.mysql.jdbc.jdbc2.optional.MysqlXADataSource


Unfortunately, when the connector J creates problems due to bug:http://bugs.mysql.com/bug.php?id=35489

Consequently when you restart the timer (For example, when you restart an instance of the cluster) will otter the following exception:

INFO: Exception thrown from bean; nested exception is: java.lang.IllegalArgumentException: null source jav ... 

Caused by: java.lang.IllegalArgumentException: null source 
at java.util.EventObject. <init> (EventObject.java: 38) 
at javax.sql.StatementEvent. <init> (StatementEvent.java: 39) 
at 
com.mysql.jdbc.jdbc2.optional.JDBC4PreparedStatementWrapper.close (JDBC4PreparedStatementWr 
apper.java: 70) 
at com.caucho.sql.UserStatement.close (UserStatement.java: 127) 
at com.caucho.sql.UserPreparedStatement.close (UserPreparedStatement.java: 450) 
at org.hibernate.jdbc.AbstractBatcher.closePreparedStatement (AbstractBatcher.java: 534) 

caused by the bug in question.

In order to resolve the issue, pending a new release you can use a nightly build of the connector j providing for the bug fix.
(Note: When you reinstall a library jar in Glassfish must restart).

I settled with that of September 20.


Conclusion

The article was translated from the italian version i'm wrote before.
I translate it with google translate service and after a fast review and some correction I think that it is a bad english too(I'm sorry).
The other article that I wrote directly in english are a little bit better.
however I hope it is helpful.
If you want to correct any sentences please contact me through a comment, don't hesitate!



Setup Glassfish Cluster (ENG)

Glassfish Cluster
G.Morreale
Introduction:

A cluster usually consists of a machine that acts as an administrator and a set of nodes that perform the work of the applications installed on them.
The objective of a cluster is usually to improve the system scalability and high availability .

The machine acting as an administrator in Glassfish clustering is called DAS (Domain Administrator Server).

Each node is made up of 2 elements:

1) Node Agent: It manages the life cycle of the application to which it is associated.
2) Application: Application server ..

The applications are installed on the DAS and are automatically propagated in nodes.

Cluster Support

Support cluster must be installed only on the DAS machine.



The Glassfish can be installed directly with the active cluster support or you can activate after a standard installation.

  • To enable support during installation use the following command:% libantbinant-f setup-cluster.xml instead of% libantbinant-f setup.xml

  • To enable the support afterwards (see picture above):
    • - Open the admin console
    • - Select from the common task: Enable Cluster Support
    • - Click Ok


Now it is prepared in this way the machine will be the DAS.

Cluster setup with a node

Suppose you want to create a cluster minimal (no sense in real situations):

A single machine is the DAS and also it is the node(later we add the second node).

In The  DAS machine, which have enabled cluster support will create the first node.

Note: The nodes can be created only from the command line. From the panel you can add a node but it is just a placeholder .. or a predisposition to create real

Creating Node Agent

From the command line type:

asadmin create-node-agent nodoDAS

nodoDAS is the name that was chosen for the node agent on DAS machine.
This command creates a node agent on DAS machine.

After you create must be started with the following command:

asadmin start-node-agent nodoDAS

Cluster Creation

Panel will now proceed with the creation of the cluster.

Clusters go on and click the button to create a new cluster.

About configuring the cluster that will leave the options on "Configuration" is unchanged will create a configuration
default-config, the system will call the copy "cluster-config". From this moment you can configure differently as regards the cluster different from that which concerns the application stand-alone acting on the different configurations.

Instance creation

Once the cluster is carried by adding the first instance and associating the nodoDAS.
You call this instance istanzaDAS.
In order to proceed with the creation, click the cluster you just created (it is located inside the item Clusters, in the previous image there is already called a cluster), then click on the Instances tab and then click New.
Enter the name and associate it instanzaDAS to NodeAgent nodoDAS after click on ok.

We have just created an instance associated with the node created by default at each stop and start the node corresponding similar operation The application is created.

State of Cluster

Making a summary on what has been achieved so far, we have a machine that acts as a DAS which is the main controlling nodeAgent one instance (instanceDAS).


Adding Second Node

To give meaning to the cluster will add a second node.

Note: You do not need the media cluster on the second machine.

The steps needed to achieve this objective are:

1) create a node agent

use the command asadmin on the machine where we want to create the second node: 

asadmin create-node-agent - host macchinaDAS nodo1 

command is equivalent to the one used to create nodoDAS but this time you must add the parameters to indicate the function of creation 
(create-node-agent) of the node that the agent machine where resides the DAS is not localhost (default value) but it is another machine.
The command used is assumed that the machine on which you installed the DAS has the hostname macchinaDAS. 

NOTE: E 'advisable to use a hostname rather than the ip, the JMX API can create some problems. 
Do not forget about linux to edit the file / etc / hosts / hostname with the choice. 

NOTE: When prompted admin admin user name and password when creating the node, enter the credentials for the login to DAS. 

The node has been created called nodo1. 

2) start the node

run from the console of the machine with the command nodo1 

asadmin start-node-agent nodo1 

in order to start the new node agent. 


3) create the istanza1 on the machine with nodo1

This can be done by hand panel. 
Going on the cluster and adding as done previously for instanzaDAS a new instance associating the node agent nodo1. 

the application created the call istanza1 

4) start istanza1

Click on the cluster, click istanza1, click on "start instance". 


Now we have two machines

DAS machine with the DAS, an instance (istanzaDAS), the main node Agent (nodeAgentDAS).
1 car with an instance (instanza1), the corresponding node Agent nodo1.

Start the Cluster

Feasible operation panel of DAS.

Click on the cluster and on the "Start Cluster".

The Cluster Test

To test the cluster, you can use a sample application provided with the same Glassfish.
Ear file should reside in the folder samples / quickstart / clusterjsp.

Effettauare deploy the panel by paying attention to the target on which you install the application.
We must remove the target server and instead add the target cluster.

Select the Availability flag if the application makes use of sessions and these sessions must be replicated in different nodes in the cluster.

If all went well, the application should be installed on both machines.
To check this in your browser, type the following url:

http://localhost:38080/clusterjsp

DAS is the machine that the machine 1.

NOTE: As you can see the URL of the cluster instances listen on port 38080 and not 8080. 8080 is about listening to standalone application server that despite the cluster is still running. Obviously not necessary if you can stop it and use only those instances configured in the cluster.

Conlcusion:
The article was translated from the italian version i'm wrote before.
I translate it with google translate service and after a fast review and some correction I think that it is a bad english too(I'm sorry).
The article that I wrote directly in english are a little bit better.
however I hope it is helpful.
If you want to correct any sentences please contact me through a comment, don't hesitate!



Link:



Android First Example: Hello World

Android First Example: Hello World
G.Morreale

Introduction:

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 Hello.java
    • copy this source code in Hello.java:

//package name must be composed of at least two java identifiers
package my.android;

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

    public class Hello extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(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
        setContentView(tv);
    }
}

    • compile Hello.java 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 my.android.Hello

    • 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: http://ant.apache.org/bindownload.cgi

    • 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..


Conclusion 

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
G.Morreale

Introduction:

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 mydb.zip, 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.data
      • mydb.properities
      • mydb.script

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


  • Prepare HSQLDB JDBC API


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
    {
        try
        {            
            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
            Class.forName("org.hsqldb.jdbcDriver");

            // 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 (rs.next())
            {
                System.out.print("ID: " + rs.getString("ID"));
                System.out.print(" first name: " + rs.getString("firstname"));
                System.out.println(" last name: " + rs.getString("lastname"));
            }

            statement.close();
            con.close();

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


Conclusion 

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 java.util.zip package:

Please leave a feedback in the comment to this post.

Search and Find a JAR

Search and Find a JAR
G.Morreale

clicca qui per la versione in italiano
Introduction:

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 www.findjar.com 

It then helps to solve the exceptions: 

  • NoClassDefFoundError
  • ClassNotFoundException

Example 

For example, by typing the name of the class XMLSerializer 

You get the following output: 

[CLASS] org.kxml2.io.K 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] org.apache.ws.jaxme.JM 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 org.kxml2.io.K 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 
files:
kxml2.jar 
kxml2-2.1.8.jar


Conclusion 

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.