Java Hello World

Java Hello World
G.Morreale

Introduzione:

The simplest programming language example!

//define a class HelloWorld
public class HelloWorld 
{ 
    //define a public static method in the class that make an entry point for the application.
    //It takes an array of String parameter
    public static void main(String[] args) 
    { 
        //Use the base System api to print a "Hello World" string in the standard output.
        System.out.println("Hello World"); 
    } 
}

Conclusion:

In a simple Java Hello World example come into play various topics:

  • the class notion
  • the public modifiers
  • the static method modifiers
  • Array type
  • String type
  • a static method call (System.out.println(String a))

So, You have to start with an object oriented programming tutorial within java tutorial in order to start programming in java.

Maintaining state in Java Webservice(JAX-WS)

Maintaining state in Java Webservice(JAX-WS)


Introduction

This little article start point is the need of get the current session from a flash swf.
I try to explain: The web application has a login form and after the user is authenticated a session is created and mantained, so the need is to access to this value into the session from flash that calls a webservice in the same service.

recapitulate.

Server side: JSP, Servlet etc. for user login.
Server side: Webservice for reporting stuff.

Client side: html form for login
Client side: flash swf (created with flex) for reporting gui. it access the webservice to obtaining reporting data and draw it. when the webservice is called the session data created in login step is required.


The Webservice

The webservice is created like in the previouse article.
But in order to get the current session a MessageContext is required.
So declare it by the @Resouce annotation, and get the HttpSession from it!

@WebService()
public class testWS {

    @Resource
    private WebServiceContext context;
    /**
     * Web service operation
     */
    @WebMethod(operationName = "sayHello")
    public String sayHello(@WebParam(name = "name")
    String name)
    {
        String ret = "";
        MessageContext mc = context.getMessageContext();
        HttpSession session = ((HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST)).getSession(false);
        if (session == null)
        {ret =  "hello: NO SESSION";}
        else
        {
            Enumeration en = session.getAttributeNames();
            while (en.hasMoreElements())
            {
                String key = (String) en.nextElement();
                ret += key + " " + session.getAttribute(key) + "\r\n";
            }
        }
        return ret;

    }

}

That's all.
The client side you can see in the previous article


Conclusion

For a complete discussion about session mantaining

Flex AS3 call a Java Webservice

Flex AS3 call a Java Webservice


Introduction

Webservice is a standard in soa architecture.
Flex is a leading tecnology for client side so let's see how actionscript 3(the flex programming language) can call a java(jax-ws) webservice.


Starting Point

The main step are:

  1. Make a WebProject with a Webservice
  2. Make a MXML in flex side and code the call

The webservice:

Two click with netbeans header and you can obtain this code:

package webservice;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService()
public class testWS 
{
    @WebMethod(operationName = "sayHello")
    public String sayHello(@WebParam(name = "name")
    String name)
    {        
        return "hello " + name;
    }

}

The Action Script Side inside mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" click="useWebService()">

<mx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.soap.WebService;
public function useWebService():void
{
var ws:WebService = new WebService();
 
ws.addEventListener(ResultEvent.RESULT,onResult);
ws.addEventListener(FaultEvent.FAULT,onFault);  
 
ws.loadWSDL("http://yourserver/ws/testWSService?wsdl");
ws.sayHello("pippo");
}
private function onResult(event:ResultEvent):void
{
 trace("result " + event.result);
}
private function onFault(fault:FaultEvent):void
{
 trace("fault " + fault);
}
]]>
</mx:Script>
</mx:Application>

To see the result debug the flex application and see at console only after deploy the webservice.

Conclusion


This is the runtime version.

Java and BlazeDS by Example

The interaction between Java and Flash
(part 3 - BlazeDS)


BlazeDS - Introduction

Let's see how to make a simple example in order to get in communication a java server side(with blazeDS) and action script 3 client side inside Flash CS3 (No Flex!!)


Example
Server Side:

Download the BlazeDS binary distribuition

The BlazeDS binary distribuition is a war, so it is a web application.
Decompress it in a directory.
Make a new java webproject and update the web-inf directory in the empty project with the files contained in decompressed war into web-inf.

Try to deploy it into the server and be sure that it is deployed correctly.

Note:
I'm take the example step by reading - RPC service example

Now in the project make the class EchoService like the example in the link:

package remoting; 

public class EchoService 
    public String echo(String text) 
    { return "Server says: I received '" + text + "' from you"; } 

If you build the project, then you see that inside WEB-INF/classes/remoting there is the EchoService.class file!

Now you have to define a destination and reference one or more channels for data transport.
So make EchoService.class the remoting destination by editing WEB-INF/flex/remoting-config.xml and adding the following code:

<destination id="echoServiceDestination" channels="my-amf">
<properties> 
<source>remoting.EchoService</source> 
</properties> 
</destination>

With the latest xml you reference my-amf channel, but it isn't setup yet.
So add the following code to WEB-INF/flex/services-config.xml

<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel"> 
<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/> 
<properties> 
<polling-enabled>false</polling-enabled>
</properties> 
</channel-definition>


This code specifes also that client uses a non-pooling AMFChannel.
Note that you must replace server.name, server.port, context.root with the correct values


Client Side:

Make An ActionScript file and inside the actions put this source code:

import flash.net.NetConnection;
import flash.net.Responder;

//replace with you server ip or servername
var url:String = "http://89.96.213.148/blazeDS/messagebroker/amf";
var nc:NetConnection;
var responder:Responder;                   
     
nc = new NetConnection();
nc.connect(url);
nc.call("echoServiceDestination.echo", new Responder( onResult, onError ), "TEST!");

function onResult( text:String ):void 
{
     trace("Result: " + text);
}
                    
function onError( error:* ):void 
{
        trace("CALL ERROR:");               
        for(var i:String in error)
        trace(i + " :: " + error[i]);
}

Conclusion:

BlazeDS seems to be a powerful solution, this example show only a simple RPC example.

Make GUI with Flash and code by Flex!

Flex and Flash CS3: How they works together


Introduction

In some previous article, I'd searched for a java ee to flash communications framework.
Webservice as3 library disappears in the third version of action script after as2.
Xml parsing and unmarshalling is too coding expensive.
AMF works but by java side I can only with OpenAMF that supports the old AMF0 version.

When I'm search for this solution I'm reading about different technologies and library and It seems that adobe flex is more powerful when you must code more by client side.

As a matter of fact Flex supports Webservice, BlazeDS tutorials talks about Flex, and many forums post talks about the flexibilty of flex.

So I think that Adobe wants to move the coding capabilities of SWF from Flash CS Actionscript to other frameworks that works too with ActionScripts but is equipped with a powerful compiler tool and library. So the developers team and Webdesigner team can works respectively with differents development software.

I'm starting to study how the web designer can go on in working with his flexible tool: flash cs3 and the developers team can integrate the graphic designer's project in flex in order to control it in a more flexible way.

Starting Point

The main step are:

  1. Make a simple flash project (FLA) with some movieclip
  2. Export it as flex component (SWC)
  3. Import it into flex builder and manage the imported movieclip.


The Flash Side:

Create a new "Flash File (ActionScript 3.0)"
Draw a rectangle and convert it into MovieClip, call it MainMovieClip.
Draw a rectangle inside MainMovieClip
Press F8, convert it into MovieClip, rename it MyMovieClip
Call the MyMovieClip instance into MainMovieClip into "myMovieClip_1"
Save All.


Export it as flex component(SWC)

In order to export the MainMovieClip you have to download the Adobe Flex Component Kit
Inside the downloaded zip you can find a simple mxp, a flash cs3 extension installable by a simple double-click.

Install it and restart Flash CS3.

Reopen the Flash File created in the first step.
Select MainMovieClip
Commands Menu-> Make Flex Component -> confirm the 24fps conversion.

Well, in the output windows you can read, if all is right, Component "MainMovieClip" is ready to be used in Flex.
And a UIMovieClip appears in library window.

note:
In this way the MainMovieClip is converted erediting the mx.flash.UIMovieClip instead of flash.display.MovieClip

Just to make a clear package definition, go to MainMovieClip properities, and change the Class from MainMovieClip in my.test.MainMovieClip

Now by right click again in MainMovieClip export it as swc.

Import the SWC inside Flex and use it

first of all make a new flex project
Add a simple button

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Button x="10" y="10" label="Button"/>
</mx:Application>

Go in the project properities ->  Flex Build Path -> Library Path -> Add SWC ... 
and add the swc exported before.

Now add a as3 script code inside mxml file:

<mx:Script>
<![CDATA[

    import my.test.MainMovieClip;
    
    var mmc:MainMovieClip
    
    function MainMovieClipShow():void
    {    
      this.addChild(mmc);  
    }
]]>
</mx:Script>

and add a click event to button:

<mx:Button x="10" y="10" label="Button" click="MainMovieClipShow()"/>

If all is right you see a web page, where by clicking in the button the MainMovieClip appear in the screen.

Conclusion

This simple example show how you can split a project between gui and model.

Java and AMF by AS3 in Flash

The interaction between Java and Flash
(part 2 - OpenAMF)

OpenAMF


Download the jar and add the library in the web project.

Make a simple servlet and inside "processRequest" put this instruction

AMFDeserializer amfDeserializer = new AMFDeserializer(new DataInputStream(request.getInputStream()));

System.out.println("bodies String " + amfDeserializer.getAMFMessage().getBodiesString());

See at server.log and you understand that library works, so go deep inside in deserialization

Go to see other details in AMFMessage:

Iterator iterator = amfMessage.getBodies();
                AMFBody body = null;

                while (iterator.hasNext())
                {
                    System.out.println("---------------");
                    body = (AMFBody) iterator.next();
                    System.out.println("type description " +     
                    body.getObjectTypeDescription(body.getType()));
                    System.out.println("response " + body.getResponse());
                    System.out.println("service method name " +     
                                        body.getServiceMethodName());
                    System.out.println("service name " + body.getServiceName());
                    System.out.println("target " + body.getTarget());
                    System.out.println("value " + body.getValue());
                    System.out.println("----------------");
                }
It works also!!wonderful
But Now I want to send an array thru action script:

so in the call funcion I pass an array

var oneArray:Array = new Array("a", "b", "c");
nc.call("func_name",res,"a_array");

But I obtain the following error:

java.io.IOException: Unknown/unsupported object type UNKNOWN: 0x10001
        at org.openamf.io.AMFDeserializer.readData(AMFDeserializer.java:350)
        at org.openamf.io.AMFDeserializer.readArray(AMFDeserializer.java:226)
        at org.openamf.io.AMFDeserializer.readData(AMFDeserializer.java:335)
        at org.openamf.io.AMFDeserializer.readBodies(AMFDeserializer.java:144)

After some hours I found the problem.
I try to change in as3 client code the AMF encoding:

nc.objectEncoding = ObjectEncoding.AMF0;

And I discover that OpenAMF supports only the AMF0 encoding.
I see also at latest update in sourceforge: 
the date time is 2006 year. It seems and old solution and not maintained.

Switch to see in part3 other solution!

Java, Flash, ActionScript and AMF

The interaction between Java and Flash
(part 1)

Introduction:

I'm writing some notes about the java and flash interaction.
I wish to achieve in the communication between a java web technology and flash client side tecnology

Client Side:

Flex and Flash.
Flex is more powerful with business logic, Flash is the best choose for designers.
See at wikipedia for a little introduction.

Websites using the Adobe Flash Player platform or Flex is programmable by ActionScript language.
Actually the latest version is the 3.0

AMF(Action Message Format) is a binary format for data serialization and remote method invocation. It is for better perfomance, it compress the size of data transferred and it is more powerful than parsing XML data. Basically AMF is the native choose if you want to comunicate with actionscript.


AMF, SOAP, XML??

About performance benchmarks are very bright, as you see in this link AMF 3 is the best.
But the webservice is a standard for a scalable architecture. you write a service with soap specification and the you can reuse it in different client technology.
So what about interaction with AS3 and Webservice?

Action Script 3 and Webservice

In the Action Script 2.0 there is a component that allow to consume a webservice.
In Action Script 3.0 it disappears, because now it belong to flex sdk.
So, in order to consume a webservice you need to use a thirdy part component.

I try two thirdy part component, 

and

But I obtain several error in calling a simple java jax ws "hello world" webservice.
So I think that this component can't handle well the jax ws wsdl and webservice without any further modification.

So, If you want to use webservice you must see Flex within its webservice managed component.
Now I leave this way.

Action Script 3 and AMF

AMF is the easiest way to get communication between flash and the web server.
Data is compressed and is in binary format.

I found an actionscript client code in order to see what data is sent thru amf:

var nc:NetConnection=new NetConnection();

nc.connect("http://localhost/amf/test1");

var res:Responder=new Responder(onResult,onError);

nc.call("func_name",res,"a_parameter");

function onResult(e:Object):void
{
 trace(e);
}

function onError(e:Object):void
{
 trace("Error");
}


Then I make a simple java servlet in order to see what headers, parameters and body stream is sent.

The content type arrived is application/x-amf
And in the body stream I see the string func_name, a_parameter and other chars, so I think that is the right moment to search for a java amf library for body deserialization.

There are many solutions for AMF in java side:


OpenAMF is a Java port of AMFPHP, it does a small subset of BlazeDS, i.e. Flash Remoting. 

BlazeDS  has a proxy service to proxy HTTP calls, it has an extensive messaging infrastructure with various server push flavors (polling, long-polling, streaming) to build messaging applications, it has JMS capabilities and many different features.

Red5 is a video/audio streaming oriented solution and more close to the Adobe's Flash Media Server. It does  also Flash remoting and remote shared objects which provide limited data connectivity. (BlazeDS does not have video/audio streaming.)


Cinnamon has a full support for AMF4, it works with or without flex, it support spring beans and plain java classes as services, has also an automatic source generation for AS3 service interfaces. Basically is a remoting framework connecting as3 clients with java ee server applications.

Pimento is a framework for integrating data management into RIA. It integrates Java apps, Hibernate, spring with flex,flash and air clients.

Granite DS is an open source framework for integrating Java EE with Flex and AMF3 serialization. It provides interoperability with popular framework service like EJB3, Spring, Google Guice, POJO service etc.



How to manage incoming call with OpenNetCf TAPI (Windows Mobile C

How to manage incoming call with OpenNetCf TAPI (Windows Mobile C#)
G.Morreale

Introduction

If you want to manage an incoming call you can use the windows mobile status api.
By this managed api you can get the status of many system properties: http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.status.systemproperty.aspx

But if you more than get the status by using an event handler, you must use the tapi mobile version, like the previous article I find more useful the opennetcf tapi wrapper: http://tapi.codeplex.com

Now I try to describe the way for get a call instance of an incoming call.

The example

Make a smart device c# project with a Form.

The first step like make a call as we see in the previous article is to initialize the tapi api.

        public Form1()
        {
            InitializeComponent();
            this.InitializeTelephony();
        }

        private void InitializeTelephony()
        {

            m_telephony = new Telephony();

            //Initialize the telephony class
            m_telephony.Initialize();

            //Get the cellular line with Monitor and Owner privileges
            m_line = m_telephony.CellularLine(MediaMode.InteractiveVoice, CallPrivilege.Monitor | CallPrivilege.Owner);

            //Add a new call event
            m_line.NewCall += new Line.NewCallHandler(m_line_NewCall);
        }

As you see in the code the call handler delegates the new call event to m_line_NewCall method


        /// <summary>
        /// Handles any new calls coming in/out of the phone the 
        /// </summary>
        /// <param name="call"></param>
        void m_line_NewCall(Call call)
        {
            lineSetCallPrivilege(call.Handle, CallPrivilege.Owner);
        }

        
In order to take the right privilege on the phone line you must use this coredll method:
        
        [DllImport("coredll")]
        extern static public int lineSetCallPrivilege(IntPtr hCall, CallPrivilege dwPrivilege);

 
so for example if you want to hang up all the incoming call you have to add only this line of code

        void m_line_NewCall(Call call)
        {
            lineSetCallPrivilege(call.Handle, CallPrivilege.Owner);
            call.HangUp();
        }

Also you can add a call info handler in order to monitor the call infos, for example:


        void m_line_NewCall(Call call)
        {
            lineSetCallPrivilege(call.Handle, CallPrivilege.Owner);
            call.CallInfo += new Call.CallInfoHandler(call_CallInfo);
        }


        string m_calledNumber = null;

        void call_CallInfo(Call call, CallInfoState infoState, CallInformation info)
        {
            Debug.println(info.CalledID); //print the caller id
        }

And Don't forget to shutdown the telephony instance!

        private void Form1_Closing(object sender, CancelEventArgs e)
        {
            m_telephony.Shutdown();
        }


How to make asynchrounous call with OpenNetCf TAPI (Windows Mobil

How to make asynchronous call with OpenNetCf TAPI (Windows Mobile C#)
G.Morreale

Introduction

If you want to make a synchrounous call you can read the previous article on the blog.
But if you want to make an asynchronous call you must write the following lines of code


The example

Ok, instead of calling:

call = line.MakeCall(tbNumber.Text, 39, false);

You must use

line.BeginMakeCall(tbNumber.Text, 39, null, new AsyncCallback(OnCallMade), this);

In this way the method don't block the execution and the OnCallMade method is called when the call is made!
So, implement the callback method OnCallMade

     private void OnCallMade(IAsyncResult ar)
        {
    
  //with this line of code we can bring up the Call instance in order to hang up it or do something else
            call = line.EndMakeCall(ar);
        }


How to make a call with OpenNetCf TAPI (Windows Mobile)

How to make a call with OpenNetCf TAPI (Windows Mobile C#)
G.Morreale

Introduction

The simplest way to make a call in windows mobile is by using the following

http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.telephony.phone.talk.aspx

 

that is the WindowsMobile Managed Telephony api.


Microsoft.WindowsMobile.Telephony.Phone myPhone = new Microsoft.WindowsMobile.Telephony.Phone();

myPhone.Talk("0123456789", true);


In this simple way the default phone manager appear and the call is managed by it.

Tapi

If you want a more flexible way to manage the phone module in your windows mobile device you have to use the TAPI
The TAPI is an application interface for telephony application, and microsoft make available it also for windows mobile(http://msdn.microsoft.com/en-us/library/aa455190.aspx).


Tapi Wrapper

Ok, now if you want to simplify the interaction with the unmanaged tapi library, you must use a wrapper.
A nice wrapper that I can find is an OpenNetCf Wrapper.
You can download it and various example from http://tapi.codeplex.com/

The example

Make a new smart device project, and add OpenNETCF.Telephony.dll in the references.

You can build the source code and obtaion the dll by the zip downloaded or find it in extracting TelephonySamples.zip file(makeCall ->  bin -> Debug -> OpenNETCF.Telephony.dll)ù

Now, we insert the tapi init code in the load event of the Form1.

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenNETCF.Telephony;

namespace MakeCall2
{
    public partial class Form1 : Form
    {

        private Telephony tapi;
        private Line line;
       
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            // Open Tapi
            tapi = new Telephony();
            tapi.Initialize();      
            // Get the phone line in the specified media mode and with or not call privilege
           line = tapi.CellularLine(MediaMode.InteractiveVoice, CallPrivilege.None);
        }
    }
}
So now, add a textbox to the form for telephone number input and a button in order to permits the call.
In the click event of the call you have to add the following:

        private void btMakeCall_Click(object sender, EventArgs e)
        {
            //the tbNumber is the textbox, and 39 is the country code of the called number, the third 
            //parameter is for suppressing or not the caller id
            line.MakeCall(tbNumber.Text, 39, false);
        }

remember to shutdown the tapi instance.

     private void Form1_Closing(object sender, CancelEventArgs e)
        {
            tapi.Shutdown();
        }

Possible Issues

When using tapi.CellularLine method the line returned can be null inspite the line exist and is activable.
I debug the OpenNETCF.Telephony and the problem is on 
"if (dc.ProviderName == NativeMethods.CELLTSP_PROVIDERINFO_STRING)"

When using the .net compact framework 3.5 the dc.ProviderName string is suffixed with a different char.
Now I don't know the cause of this, but we can avoid this problem by using this matching:
"if (dc.ProviderName.contains(NativeMethods.CELLTSP_PROVIDERINFO_STRING))"







Get the row with a max value in mysql

Get the row with a max value in mysql
G.Morreale

Introduction


Problem: Find the row with the max value of a column, for example 
For each article, find the dealer or dealers with the most expensive price.

The solution is around mysql queries.

Tests Environment

Make an example db with a test table in mysql:

CREATE DATABASE `mytest`;

DROP TABLE IF EXISTS `mytest`.`shop`;
CREATE TABLE  `mytest`.`shop` (
  `article` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `dealer` varchar(45) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  PRIMARY KEY (`article`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=87158 DEFAULT CHARSET=latin1;

Insert some rows in the database (I inserted 6800 row)

INSERT INTO mytest.shop (dealer,price) values ('aaa',round(rand()*100));

the test was done on windows xp, mysql 5.1 standard installation

Solutions

  • SELECT price from shop s1 order by price desc limit 1))

It sort the prices and take the first. The best sorting cannot be done in less than O(n log n) time.

  • SELECT price FROM shop s1 WHERE price=(SELECT MAX(s2.price) FROM shop s2))

It take a linear (O(n)) time for max computation and the other linear time for price comparison with max value.

  • SELECT s1.price FROM shop s1 LEFT JOIN shop s2 ON s1.article <> s2.article and s1.price < s2.price WHERE s2.article IS NULL))

This last solution works on the basis that when s1.price is the maximum value there is no s2.price with a greater value so the s2 rows values will be null.
It seems also a linear time computation.

(I don't know about mysql internals algorithm so take my discussion  with a grain of salt)


Results

select benchmark(800000000,(select price from shop s1 order by price desc limit 1));

37.1 seconds

select benchmark(800000000,(SELECT s1.price FROM shop s1 LEFT JOIN shop s2 ON s1.article <> s2.article and s1.price < s2.price WHERE s2.article IS NULL));

37.3 seconds

select benchmark(800000000,(SELECT price FROM shop s1 WHERE price=(SELECT MAX(s2.price) FROM shop s2)));

38.45 seconds

Conclusion

From the test the fastest query seems to be the first (with the order by), but I'm not sure if it is correct.
Before the tests I was thinking that the other solutions was better.

So if anyone wish to express an opinion, he will be welcome.

Request header too large Exception

Request header too large Exception
G.Morreale


In a production system, in calling a webservice I encounter this problem:

..WEB0777: Unblocking keep-alive exception
java.lang.IllegalStateException: PWC4662: Request header is too large
at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:740)
at org.apache.coyote.http11.InternalInputBuffer.parseHeader(InternalInputBuffer.java:657)
at org.apache.coyote.http11.InternalInputBuffer.parseHeaders(InternalInputBuffer.java:543)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.parseRequest(DefaultProcessorTask.java:712)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:577)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380)
at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
|#]

I solve it, by using maxPostSize property.

In order to setup this value open admin console, go to Configuration->Http Service->Http Listener and add the property
maxPostSize.

The default value is 4096, so increment it until the exception doesn't appear anymore.

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/