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))"