Flex AS3 Webservice Proxy and Object Binding

Flex AS3 Webservice Proxy and Object Binding


Introduction

In the previous article we see how a flex as3 can call webservice simply by using the Webservice class.
Let's see about webservice resultformat and data binding.

The Webservice Client Result Format in AS3

The webservice client result format can be "Object, xml, or e4x".

  • The Object(default resultFormat) return data in form of ObjectProxy. ObjectProxy contains different datatypes like ArrayCollection etc. You would have to handle and parse this result obtaining the data you expect.
  • XML format returns the data as an array of XMLNodes.
  • E4X format gives an XMLList. 



But like jax-ws java client maked with netbeans wizard I wish to search about automatic data binding.

It shows how make the proxy objects by using the wsdl.
This is done by flex builder ide.

Import Webservice into flex builder

The following link show the detailed steps

I write only some notes about this.
First of all, Import webservice inside flex builder project:

Data Menu -> Import Webservice and so on.

Then in order to call the webservice use the

NameService class.
Where Name is the name of webservice.

var ws:NameService = new NameService();

The autogenerate procedure make also one listener for each operation inside the webservice.
So add the listener and make the proper function called by the listener

ws.addOperation1EventListener(onResultOperation1);

the onResultOperation1 definition is like this:

private function onResultOperation1(res:Operation1ResultEvent):void
{
   var value:Operation1ReturnType = res.result._return;
}

The Operation1ResultEvent and Operation1ReturnType is created by flexbuilder during the webservice import.
Note that Operation1ReturnType is the real return type used also in the webservice (server side).
So in this function you obtain directly the returnType Object.

Ok, for calling the webservice, first assign the request variable.

//inside costructor possible parameter to be pass to the webservice //operation
var param:Operation1_request = new Operation1_request(); 
ws.Operation1_request_var = param;

call it

ws.Opearation1_send();


Conclusion

In this way more coding works is done automatic by the ide.

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/ 






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

Blog Archive

Translate the blog