Showing posts with label RPC. Show all posts
Showing posts with label RPC. Show all posts

Oct 9, 2009

Next Generation Web Based Telecom Applications

Introduction
  • Telecom applications in today’s world are not merely limited to providing telephone connection across two locations.
  • Today’s telecom equipments make use of voice, data, and video communication mode and range from a simple telephone or mobile phones to wireless optical technologies used across in radars and satellites for scientific and military purposes.
  • However with rising demands of customers and with competitive market conditions, providing these services is coming across as a challenge.
  • So, Telecom Operators are transforming themselves into broader service oriented providers along with providing value additions to the end user. But this requires use of latest hardware and software technologies in an effective and smart way.
Use of Telecom Services

image

Need for Next Generation Architecture (NGA)
  • Telecom applications usually are tightly coupled with proprietary hardware used by Telecom Operators.
  • Due to the complexity involved in the nature of telecom applications, providing services which are readily available, secure and platform independent is a challenge.
  • With invent of new and upgraded hardware, telecom operators need to enhance their software platforms with latest technologies and architectures to support the new hardware.

So, following is one of the possible approaches:

image

Advantages of NGA

Following factors (individually or collectively) could result in the transition to NGA:

  • Low Development and Maintenance Cost
  • Improved Performance
  • Integration with latest tools and technologies
  • Robust and Fault-Tolerant systems
  • Multi Environment/Multi Platform Support
  • More secure and reliable
The SOA Architecture Pattern
  • Service-Oriented Architecture (SOA) breaks everyday business applications into individual processes and functions, called services.
  • SOA is a collection of services communicating with each other through standard interfaces and is designed to create a loosely connected architecture built up of reusable components.
  • From a developer’s point of view, SOA provides a programming model to build Web Services, which is the new buzzword in the software industry.
  • Many IT firms today are moving towards the use of Web Services in their applications for maximum benefit and SOA is one of the most popular architecture choices (e.g. British Telecom, IBM).
SOA Architecture Pattern – Key Points

image

Advantages of SOA
  • Can be run using Java and .Net platforms
  • Can be implemented using wide range of technologies like SOAP, REST, CORBA, DCOM, RPC, Web Services.
  • Support all the standard information exchange interfaces like HTTP, XML, JDBC/ODBC.
  • Supports distributed architecture style and is scalable.
  • Many open source tools available like Sun JAXWS, Apache Web Services etc., WCF (Windows Communication Foundation) by Microsoft.
  • Provides enhanced security and encryption mechanisms.
Typical Telecom Application Architecture using SOA

image

Enterprise Service Bus
  • ESB provides core infrastructure for SOA.
  • Essential in deploying and managing distributed applications.
  • Typical use in middle layer for integrating between services.
  • Ensures loose coupling and acts as a message broker.
  • Uses XML as standard communication language.
  • Includes adapters for integration with legacy applications.
SOA Middleware Layers

image

Case Study

Application Requirement – Provide Web Based Application for Call Control Management and Directory Services Management For Call Centre Supervisors

Case Study - Solution

image

Case Study - Use of Open Source Tools

image

Case Study - Handling of Real Time Data
  • Use of ‘Comet’ component from GWT Rocket framework.
  • Stream data in the response of a long-lived HTTP connection. Reference: http://code.google.com/p/rocket-gwt/wiki/Comet 
  • A Comet Servlet is loaded in Java Servlet Container (e.g. Tomcat)
  • This Servlet implements HTTP streaming of events to the browser using simple RPC mechanism through poll() method.
  • At the client side, a comet session is started with creation of hidden iFrame which connects to Comet Servlet.
  • The Servlet periodically scans a event queue for new events and pushes the serialized objects to the client (browser). The iFrame gradually continues to grow due to incoming data.
  • After every session timeout, the client can close the iFrame to reclaim memory and then attempt to reconnect automatically.
Challenges and Alternatives

Challenges with SOA:

  • Managing SOA metadata
  • No standard tools for testing
  • Providing end-to-end security
  • Still in evolving stage

Alternatives for SOA

  • Session Initiation Protocol (SIP)
  • Parlay X

Next Generation Web Based Telecom Applications

Introduction
  • Telecom applications in today’s world are not merely limited to providing telephone connection across two locations.
  • Today’s telecom equipments make use of voice, data, and video communication mode and range from a simple telephone or mobile phones to wireless optical technologies used across in radars and satellites for scientific and military purposes.
  • However with rising demands of customers and with competitive market conditions, providing these services is coming across as a challenge.
  • So, Telecom Operators are transforming themselves into broader service oriented providers along with providing value additions to the end user. But this requires use of latest hardware and software technologies in an effective and smart way.
Use of Telecom Services

image

Need for Next Generation Architecture (NGA)
  • Telecom applications usually are tightly coupled with proprietary hardware used by Telecom Operators.
  • Due to the complexity involved in the nature of telecom applications, providing services which are readily available, secure and platform independent is a challenge.
  • With invent of new and upgraded hardware, telecom operators need to enhance their software platforms with latest technologies and architectures to support the new hardware.

So, following is one of the possible approaches:

image

Advantages of NGA

Following factors (individually or collectively) could result in the transition to NGA:

  • Low Development and Maintenance Cost
  • Improved Performance
  • Integration with latest tools and technologies
  • Robust and Fault-Tolerant systems
  • Multi Environment/Multi Platform Support
  • More secure and reliable
The SOA Architecture Pattern
  • Service-Oriented Architecture (SOA) breaks everyday business applications into individual processes and functions, called services.
  • SOA is a collection of services communicating with each other through standard interfaces and is designed to create a loosely connected architecture built up of reusable components.
  • From a developer’s point of view, SOA provides a programming model to build Web Services, which is the new buzzword in the software industry.
  • Many IT firms today are moving towards the use of Web Services in their applications for maximum benefit and SOA is one of the most popular architecture choices (e.g. British Telecom, IBM).
SOA Architecture Pattern – Key Points

image

Advantages of SOA
  • Can be run using Java and .Net platforms
  • Can be implemented using wide range of technologies like SOAP, REST, CORBA, DCOM, RPC, Web Services.
  • Support all the standard information exchange interfaces like HTTP, XML, JDBC/ODBC.
  • Supports distributed architecture style and is scalable.
  • Many open source tools available like Sun JAXWS, Apache Web Services etc., WCF (Windows Communication Foundation) by Microsoft.
  • Provides enhanced security and encryption mechanisms.
Typical Telecom Application Architecture using SOA

image

Enterprise Service Bus
  • ESB provides core infrastructure for SOA.
  • Essential in deploying and managing distributed applications.
  • Typical use in middle layer for integrating between services.
  • Ensures loose coupling and acts as a message broker.
  • Uses XML as standard communication language.
  • Includes adapters for integration with legacy applications.
SOA Middleware Layers

image

Case Study

Application Requirement – Provide Web Based Application for Call Control Management and Directory Services Management For Call Centre Supervisors

Case Study - Solution

image

Case Study - Use of Open Source Tools

image

Case Study - Handling of Real Time Data
  • Use of ‘Comet’ component from GWT Rocket framework.
  • Stream data in the response of a long-lived HTTP connection. Reference: http://code.google.com/p/rocket-gwt/wiki/Comet 
  • A Comet Servlet is loaded in Java Servlet Container (e.g. Tomcat)
  • This Servlet implements HTTP streaming of events to the browser using simple RPC mechanism through poll() method.
  • At the client side, a comet session is started with creation of hidden iFrame which connects to Comet Servlet.
  • The Servlet periodically scans a event queue for new events and pushes the serialized objects to the client (browser). The iFrame gradually continues to grow due to incoming data.
  • After every session timeout, the client can close the iFrame to reclaim memory and then attempt to reconnect automatically.
Challenges and Alternatives

Challenges with SOA:

  • Managing SOA metadata
  • No standard tools for testing
  • Providing end-to-end security
  • Still in evolving stage

Alternatives for SOA

  • Session Initiation Protocol (SIP)
  • Parlay X

Sep 25, 2009

GWT Chat Application – (GWT with xmpp protocol)

emite (xmpp & gwt) – This library implements the xmpp communications protocol using the bosh technique with gwt. It also handles the xmpp Instant Messaging protocol but has a modular architecture to support any other kind of communications.

  • stable, pure java (no js), portable library
  • ready, full featured and easy to use instant messaging implementation
  • extensible architecture
  • Chat rooms support (Multi-User Chat).
  • Other XEP like: Chat State Notifications.
  • well tested (junit test, coverage support)
Features :
  • Common features support (chat, chat rooms, presence, roster)
  • Sound and visual advices when new messages arrive
  • Drag & Drop support to start a conversation and for chat room invitations
  • i18n support
  • Focused in be very usable
  • Based in extjs and gwt-ext
Screenshot

emite Chat Demo – click here
emite Chat application download

GWT Chat Application – (GWT with xmpp protocol)

emite (xmpp & gwt) – This library implements the xmpp communications protocol using the bosh technique with gwt. It also handles the xmpp Instant Messaging protocol but has a modular architecture to support any other kind of communications.

  • stable, pure java (no js), portable library
  • ready, full featured and easy to use instant messaging implementation
  • extensible architecture
  • Chat rooms support (Multi-User Chat).
  • Other XEP like: Chat State Notifications.
  • well tested (junit test, coverage support)
Features :
  • Common features support (chat, chat rooms, presence, roster)
  • Sound and visual advices when new messages arrive
  • Drag & Drop support to start a conversation and for chat room invitations
  • i18n support
  • Focused in be very usable
  • Based in extjs and gwt-ext
Screenshot

emite Chat Demo – click here
emite Chat application download

Sep 23, 2009

Google Web Toolkit and Client-Server Communications

This article is written by Miguel Mendez

Communication Infrastructure

Frame
  • Module com.google.gwt.user.User provides Frame class
  • Pass information to the server by manipulating the URL
  • Retrieve responses from the Frame's content or the server can write script tags to be executed
  • History and browser compatibility issues to consider
  • Load events are not reliable across browsers; specifically in Safari 2

FormPanel
  • Module com.google.gwt.user.User provides FormPanel class
  • Provides interoperability with servers that accept traditional HTML form encoding
  • Data is sent asynchronously
  • Any Widget that implements HasName which is part of the FormPanel will have its data sent on submit
  • Enables file uploads
FileUpload Example

final FormPanel form = new FormPanel();

form.setAction("/myFormHandler");

// FileUpload requires the POST method, and multipart MIME

// encoding.

form.setEncoding(FormPanel.ENCODING_MULTIPART);

form.setMethod(FormPanel.METHOD_POST);

// Create a FileUpload widget.

FileUpload upload = new FileUpload();

upload.setName("uploadFormElement");

form.setWidget(upload);

// Get a root panel and add the form and a button

RootPanel rootPanel = RootPanel.get();

rootPanel.add(form);

rootPanel.add(new Button("Submit", new ClickListener() {

public void onClick(Widget sender) {

form.submit();

}

}));

RequestBuilder (XHR)
  • Module com.google.gwt.http.HTTP provides RequestBuilder
  • Builder for making HTTP GETs and POSTs requests
  • Asynchronous communications only
  • Restricted by the same origin policy
  • Browsers limit the possible number of simultaneous connections so don’t go crazy firing off requests
RequestBuilder Example
public void onModuleLoad() throws RequestException {

String url = GWT.getModuleBaseURL() + "get";

RequestBuilder builder =

new RequestBuilder(RequestBuilder.GET, url);

// Create a callback object to handle the result

RequestCallback requestCallback = new RequestCallback() {

public void onError(Request request, Throwable exception) {

//…

}

public void onResponseReceived(Request request,

Response response) {

//…

}

};
// Send the request

builder.sendRequest("payload", requestCallback);

}

XML Services

XML Encoding/Decoding
  • Module com.google.gwt.xml.XML declares XML related classes
  • XMLParser parses a string containing valid XML into a new Document instance
  • Document class can be used to explore and modify the structure of the document
  • Document class will also convert the structure back into a string
  • Manipulation of XML is somewhat laborious
XMLRPC Example
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "...");

RequestCallback requestCallback = new RequestCallback() {

public void onResponseReceived(Request request,

Response response) {

// Parse xml response into a Document object

Document result = XMLParser.parse(response.getText());

// ...

}

// Error handling omitted

};

// Create Document

Document doc = XMLParser.createDocument();

// Add elements to the document as necessary…

// Send the XML request
rb.sendRequest(doc.toString(), requestCallback);

JSON Services

JSON Encoding/Decoding
  • Module com.google.gwt.json.JSON declares JSON related classes
  • JSONParser converts between strings and JSON objects
  • JSON is a fundamental data encoding that does not support cyclic structures
  • JSONP, JSONRPC are protocols built on top of the JSON encoding
  • Again, the conversion to/from JSON can be somewhat laborious
JSON Service Example
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "...");

RequestCallback requestCallback = new RequestCallback() {

public void onResponseReceived(Request request,

Response response) {

// Parse json response into a JSONValue object

JSONValue result = JSONParser.parse(response.getText());

// ...

}

// Error handling omitted

};

rb.sendRequest("{...}", requestCallback);

Efficiency Tip: JavaScriptObject Overlays

Overlays result in no runtime overhead; very efficient
/**

* Java overlay of a JavaScriptObject, whose JSON

* representation is { count: 5 }.

*/

public class MyJSO extends JavaScriptObject {

// Convert a JSON encoded string into a MyJSO instance

public static native MyJSO fromJSONString(

String jsonString) /*-{

return eval('(' + jsonString + ')');

}-*/;

// Returns the count property of this MyJSO

public native int getCount() /*-{

return this.count;

}-*/;

}

GWT RPC

GWT RPC Overview
  • Designed to move Java instances between client code (in the browser) and a Java servlet
  • Uses Serializable and IsSerializable marker interfaces
  • Interfaces define the service, a generator creates the necessary marshaling code with built-inversioning and a serialization policy file
  • Supports Java 1.5 language constructs
  • Built on top of RequestBuilder (XHR)
  • Like the rest of GWT, recompile to pick up the latest performance improvements - faster serialization code, etc.
Declaring GWT RemoteServices
// Implemented by the servlet

@RemoteServiceRelativePath("tasks")

public interface TaskRemoteService extends RemoteService {

List<Task> getTasks(int startIndex, int maxCount)

throws TaskServiceException;

}

// Implemented by generated client proxy, needs to match sync

public interface TaskRemoteServiceAsync {

void getTasks(int startIndex, int maxCount,

AsyncCallback<List<Task>> callback);

}

// TaskRemoteService servlet

public class TaskRemoteServiceImpl extends RemoteServiceServlet
implements TaskRemoteService {

public List<Task> getTasks(int startIndex, int maxCount)
throws TaskServiceException {
// Code omitted
}
}

Invoking GWT RemoteServices

// Get client proxy, annotation causes auto addressing

TaskRemoteServiceAsync service =

GWT.create(TaskRemoteService.class);

// Create a callback object to handle results
AsyncCallback<List<Task>> asyncCallback =
new AsyncCallback<List<Task>>() {
public void onFailure(Throwable caught) {
// Deal with TaskServiceException...
}

public void onSuccess(List<Task> result) {
for (Task task : result) {
// Process each task...
}
}
};

// Actually call the service
service.getTasks(0, 10, asyncCallback);

Accessing the Request Object
  • Async method signature changed to return a Request instance
  • Useful for canceling the HTTP request used by RPC
// Modified async interface
public interface TaskRemoteServiceAsync {
// Method returns the underlying HTTP Request instance
Request getTasks(int startIndex, int maxCount,
AsyncCallback<List<Task>> callback);
}

Accessing the RequestBuilder Object
  • Change the return type of the async method to RequestBuilder, proxy returns a fully configured RequestBuilder
  • Provides access to HTTP timeouts, and headers
  • Caller must call RequestBuilder.send()
  • Wrap modified async interface to provide your own special manipulation code
// Modified async interface
public interface TaskRemoteServiceAsync {
// Method returns the underlying HTTP RequestBuilder instance
RequestBuilder getTasks(int startIndex, int maxCount,
AsyncCallback<List<Task>> callback);
}

Raw RPC Serialization
  • For pre-serialization of responses or custom transports
    * Client accesses the generated SerializationStreamFactory
    * Server uses RPC.encodeResponseForSuccess method to encode
  • Streams are not symmetric

public Object clientDeserializer(String encodedPayload)
throws SerializationException {
// Create the serialization stream factory
SerializationStreamFactory serializationFactory =
GWT.create(TaskRemoteService.class);
// Create a stream reader
SerializationStreamReader streamReader =
serializationFactory.createStreamReader(encodedPayload);
// Deserialize the instance
return streamReader.readObject();
}

Best Practices
  • Use stateless servers - better handling, better scalability
  • Keep conversational state in the client
  • Consider possible failure modes, keep the user’s needs in mind
  • Judiciously control the amount of data sent to the client - consider pagination of data instead of one bulk transfer

Google Web Toolkit and Client-Server Communications

This article is written by Miguel Mendez

Communication Infrastructure

Frame
  • Module com.google.gwt.user.User provides Frame class
  • Pass information to the server by manipulating the URL
  • Retrieve responses from the Frame's content or the server can write script tags to be executed
  • History and browser compatibility issues to consider
  • Load events are not reliable across browsers; specifically in Safari 2

FormPanel
  • Module com.google.gwt.user.User provides FormPanel class
  • Provides interoperability with servers that accept traditional HTML form encoding
  • Data is sent asynchronously
  • Any Widget that implements HasName which is part of the FormPanel will have its data sent on submit
  • Enables file uploads
FileUpload Example

final FormPanel form = new FormPanel();

form.setAction("/myFormHandler");

// FileUpload requires the POST method, and multipart MIME

// encoding.

form.setEncoding(FormPanel.ENCODING_MULTIPART);

form.setMethod(FormPanel.METHOD_POST);

// Create a FileUpload widget.

FileUpload upload = new FileUpload();

upload.setName("uploadFormElement");

form.setWidget(upload);

// Get a root panel and add the form and a button

RootPanel rootPanel = RootPanel.get();

rootPanel.add(form);

rootPanel.add(new Button("Submit", new ClickListener() {

public void onClick(Widget sender) {

form.submit();

}

}));

RequestBuilder (XHR)
  • Module com.google.gwt.http.HTTP provides RequestBuilder
  • Builder for making HTTP GETs and POSTs requests
  • Asynchronous communications only
  • Restricted by the same origin policy
  • Browsers limit the possible number of simultaneous connections so don’t go crazy firing off requests
RequestBuilder Example
public void onModuleLoad() throws RequestException {

String url = GWT.getModuleBaseURL() + "get";

RequestBuilder builder =

new RequestBuilder(RequestBuilder.GET, url);

// Create a callback object to handle the result

RequestCallback requestCallback = new RequestCallback() {

public void onError(Request request, Throwable exception) {

//…

}

public void onResponseReceived(Request request,

Response response) {

//…

}

};
// Send the request

builder.sendRequest("payload", requestCallback);

}

XML Services

XML Encoding/Decoding
  • Module com.google.gwt.xml.XML declares XML related classes
  • XMLParser parses a string containing valid XML into a new Document instance
  • Document class can be used to explore and modify the structure of the document
  • Document class will also convert the structure back into a string
  • Manipulation of XML is somewhat laborious
XMLRPC Example
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "...");

RequestCallback requestCallback = new RequestCallback() {

public void onResponseReceived(Request request,

Response response) {

// Parse xml response into a Document object

Document result = XMLParser.parse(response.getText());

// ...

}

// Error handling omitted

};

// Create Document

Document doc = XMLParser.createDocument();

// Add elements to the document as necessary…

// Send the XML request
rb.sendRequest(doc.toString(), requestCallback);

JSON Services

JSON Encoding/Decoding
  • Module com.google.gwt.json.JSON declares JSON related classes
  • JSONParser converts between strings and JSON objects
  • JSON is a fundamental data encoding that does not support cyclic structures
  • JSONP, JSONRPC are protocols built on top of the JSON encoding
  • Again, the conversion to/from JSON can be somewhat laborious
JSON Service Example
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "...");

RequestCallback requestCallback = new RequestCallback() {

public void onResponseReceived(Request request,

Response response) {

// Parse json response into a JSONValue object

JSONValue result = JSONParser.parse(response.getText());

// ...

}

// Error handling omitted

};

rb.sendRequest("{...}", requestCallback);

Efficiency Tip: JavaScriptObject Overlays

Overlays result in no runtime overhead; very efficient
/**

* Java overlay of a JavaScriptObject, whose JSON

* representation is { count: 5 }.

*/

public class MyJSO extends JavaScriptObject {

// Convert a JSON encoded string into a MyJSO instance

public static native MyJSO fromJSONString(

String jsonString) /*-{

return eval('(' + jsonString + ')');

}-*/;

// Returns the count property of this MyJSO

public native int getCount() /*-{

return this.count;

}-*/;

}

GWT RPC

GWT RPC Overview
  • Designed to move Java instances between client code (in the browser) and a Java servlet
  • Uses Serializable and IsSerializable marker interfaces
  • Interfaces define the service, a generator creates the necessary marshaling code with built-inversioning and a serialization policy file
  • Supports Java 1.5 language constructs
  • Built on top of RequestBuilder (XHR)
  • Like the rest of GWT, recompile to pick up the latest performance improvements - faster serialization code, etc.
Declaring GWT RemoteServices
// Implemented by the servlet

@RemoteServiceRelativePath("tasks")

public interface TaskRemoteService extends RemoteService {

List<Task> getTasks(int startIndex, int maxCount)

throws TaskServiceException;

}

// Implemented by generated client proxy, needs to match sync

public interface TaskRemoteServiceAsync {

void getTasks(int startIndex, int maxCount,

AsyncCallback<List<Task>> callback);

}

// TaskRemoteService servlet

public class TaskRemoteServiceImpl extends RemoteServiceServlet
implements TaskRemoteService {

public List<Task> getTasks(int startIndex, int maxCount) 
throws TaskServiceException {
// Code omitted
}
}

Invoking GWT RemoteServices

// Get client proxy, annotation causes auto addressing

TaskRemoteServiceAsync service =

GWT.create(TaskRemoteService.class);

// Create a callback object to handle results
AsyncCallback<List<Task>> asyncCallback =
new AsyncCallback<List<Task>>() {
public void onFailure(Throwable caught) {
// Deal with TaskServiceException...
}

public void onSuccess(List<Task> result) {
for (Task task : result) {
// Process each task...
}
}
};

// Actually call the service
service.getTasks(0, 10, asyncCallback);

Accessing the Request Object
  • Async method signature changed to return a Request instance
  • Useful for canceling the HTTP request used by RPC
// Modified async interface
public interface TaskRemoteServiceAsync {
// Method returns the underlying HTTP Request instance
Request getTasks(int startIndex, int maxCount,
AsyncCallback<List<Task>> callback);
}

Accessing the RequestBuilder Object
  • Change the return type of the async method to RequestBuilder, proxy returns a fully configured RequestBuilder
  • Provides access to HTTP timeouts, and headers
  • Caller must call RequestBuilder.send()
  • Wrap modified async interface to provide your own special manipulation code
// Modified async interface
public interface TaskRemoteServiceAsync {
// Method returns the underlying HTTP RequestBuilder instance
RequestBuilder getTasks(int startIndex, int maxCount,
AsyncCallback<List<Task>> callback);
}

Raw RPC Serialization
  • For pre-serialization of responses or custom transports
    * Client accesses the generated SerializationStreamFactory
    * Server uses RPC.encodeResponseForSuccess method to encode
  • Streams are not symmetric

public Object clientDeserializer(String encodedPayload)
throws SerializationException {
// Create the serialization stream factory
SerializationStreamFactory serializationFactory =
GWT.create(TaskRemoteService.class);
// Create a stream reader
SerializationStreamReader streamReader =
serializationFactory.createStreamReader(encodedPayload);
// Deserialize the instance
return streamReader.readObject();
}

Best Practices
  • Use stateless servers - better handling, better scalability
  • Keep conversational state in the client
  • Consider possible failure modes, keep the user’s needs in mind
  • Judiciously control the amount of data sent to the client - consider pagination of data instead of one bulk transfer

Sep 22, 2009

Tutorial - Writing Instant Messenger Application - GWT

FYI.. this tutorial is from Google WebToolkit Application Book Author : Ryan Dewsbury

Instant Messenger Application

This tutorial shows how to build the web-based Instant Messenger application. The application is a good example of building on top of a welldefined GWT-RPC interface. Every client that loads the application will connect to a servlet on the server and make method calls through RPC. Each client connects to the same server, so it is possible for clients to collaborate with each other. The chapter also looks at building an unobtrusive user interface that integrates well with an existing web page and that only presents information to the user when necessary. We close the chapter by seeing how events can be added to HTTP using GWT-RPC and how to integrate with server features that make event-based protocols more efficient. You can work with a running instance of this application at http://messenger.gwtapps.com.

Using the Collaborator Application Pattern

Desktop applications are typically written for people working individually. This makes sense since desktop computers only have one person using them at a time. However, in the real world we tend not to work alone but in teams and multiple people have to collaborate on a single document. For example, many document-based applications are single-user based even when certain documents need to be edited by more than one person. Applications typically don’t have a way to manage this type of collaboration. We resort to passing documents through e-mail or copying them to disk. The Collaborator Application pattern addresses the awkwardness of manual collaboration by building collaboration systems directly into the application.

Building collaborative applications is made substantially easier due to the Internet and its pervasiveness. We can fairly simply transfer data from one source to another. Every person who needs to collaborate just must be able to connect to the Internet and use a web browser. It’s important to have low user requirements for collaboration, even more so than for a single- user application, so everyone who needs to be involved can get involved. Traditional web applications have provided a great collaboration platform in this respect, as shown by the popularity of e-mail and other online collaboration applications. The low barrier to entry for Ajax applications can bring richer experiences to web collaboration.

To build an application using the Collaborator pattern you need to define your model as a centralized model that is accessed through a controller, as illustrated in Figure 1. Each collaborative client interacts with the controller to operate on the model. The controller is then responsible for informing the remaining clients of the model changes. You may be thinking that using a collaboration pattern like this can be a challenge for applications that have their communication based on HTTP, because HTTP does not let servers send data to clients without a request being sent by the client. We’ll look at solutions to this problem later in this chapter.

Figure 1

Instant Messenger Design


If you’re reading this tutorial you most likely are familiar with what an instant messenger does. You’ve probably run into them many times and may even use instant messenger services on a daily basis. Their job is to provide instant textual communication between two or more people that is more conversational than e-mail and less intrusive than a phone call. They have been gaining usage with hundreds of millions of users[ Based on a February 2006 comScore survey (www.comscore.com/press/release.asp?id=800) ]. This is a truly successful
desktop Internet application only rivaled by e-mail clients and web browsers. Bringing this type of application into a browser through Ajax provides the added benefits associated with web-based applications: giving people the ability to communicate from anywhere with a web browser without the need to install client software. Furthermore, the ease of running, building, and deploying an Ajax instant messenger means that it can be used easily in many specialized situations without any barriers to entry.

For this sample application we will create a specialized instant messenger for a web page. It will integrate with a web page as an embedded widget complementing the page’s existing purpose with presence [ Presence is an instant messenger feature that provides realtime online status for you and your contacts ] and instant communication among its users. It will accomplish this by providing a contact list that has, instead of a list of friends or colleagues, a list of visitors to the web page. A visitor will be able to supply his name to be added to the list, and then be able to see other visitors and interact with them through instant messages.

Typically with instant messenger systems the clients do not connect directly to each other; instead, they relay messages through a server. Our application will do the same. Figure - 2 shows a simplified illustration of how clients communicate with each other through the server.

When the client loads the web page, the GWT application will be loaded as well and will connect to the server. The user can input a name and then receive events from the server, such as other users viewing the page and coming online or leaving the page, and messages sent from another user.

Figure - 2

Users can also send messages to other users. The server receives these requests and provides responses in a typical request-response behavior, and it also sends events based on these requests to other users using event protocol behavior.

The Instant Messenger server will run as a GWT servlet with a GWT-RPC interface. The clients will connect and make method calls to the servlet to support the instant messenger functionality. The servlet will implement the RPC interface and provide an event broadcasting system to each client. We’ll discuss the event implementation over GWT-RPC later in this chapter.

The application’s internal design follows the Model-View-Controller architecture. The model represents the objects on which the application operates, including the contacts in the contact list and messages. The view presents the contact list and other windows required to render the Instant Messenger on a web page. The controller implements communication with the server and manages model objects to be rendered in the view.

The Model

The Instant Messenger application’s model has three classes: ContactList, Contact, and Message. These classes are very simple and it is easy to suggest that they are not needed in this application; however, one goal of this sample application is to illustrate how to organize your code. If we were building more functionality into this application, we would be putting more data into our model and would find it useful to separate the application’s components.

Another benefit of the model for this application and for the use of GWT for client applications is that we can share our model objects with serverside code. Since we are implementing the server as a servlet, its implementation is also in Java. Furthermore, GWT-RPC allows transferring of Java objects, which lets us use our model objects again for the structure of our protocol’s data.

So let’s look at the structure of the model. If you’re familiar with instant messenger applications, the UML in Figure - 3 seems intuitive.


The ContactList class contains a list of Contacts and a me attribute. This attribute is a reference to a Contact instance that represents the current user. The Contact class has a name attribute representing the contact’s name, and the Message class has a message attribute for the body of the message. These classes can easily be expanded to add functionality to the application. Also notice that the Message and Contact classes implement GWT’s IsSerializable interface. Implementing this interface and creating a no-arg constructor allows their instances to be transferred over the GWT-RPC protocol. As of GWT 1.4 you can use Java’s Serializable interface instead.

These objects are implemented with simple Java code. The following code shows the implementation for the ContactList class:

public class ContactList {
private Contact me;
private List contacts = new ArrayList();
public ContactList( String name ){
me = new Contact( name );
}

public Contact getMe(){
return me;
}
public void addContact( Contact contact){
contacts.add( contact );
}
public int getContactCount(){
return contacts.size();
}
public Contact getContact( int index ){
return (Contact) contacts.get(index);
}
}
The class implements what the UML diagram in Figure 9-3 defined. The class provides three methods for the list of contacts: The addContact method inserts a new contact in the list, the getContactCount method returns the number of contacts in the list, and the getContact method returns the contact at a specific index. Now let’s look at the Contact class:


public class Contact implements IsSerializable{
private String name;
public Contact(){}
public Contact( String name ){
this.name = name;
}
public String getName(){
return name;
}
}
This is another simple class. It has just one attribute, the contact’s name. This class can be extended to provide more functionality. For example, you could add an e-mail address so that it could be displayed as a link for the user on the page to e-mail other users. Here we see the benefit of the model with this change. The change would be easily available to the controller, the server (since the model will still transfer over RPC), and the view.



The final class in the model is the Message class:


public class Message implements IsSerializable{
private String message;
public Message(){}
public Message( String message ){
this.message = message;
}
public String toString(){
return message;
}
}
Again, this is another simple class in our model. It has just one attribute, the message body. This class can also be easily extended to provide more information, such as adding a timestamp.



Building a Complementary Interface

This application’s view is responsible for presenting users with instant feedback about the presence of other users on the page and their messages. Typically an instant messenger sits hidden in the taskbar of an operating system, or its contact list fits snugly out of the way at the side of the desktop. By contrast, our Instant Messenger application can’t interact with the desktop or a taskbar and has to share space in a browser window. We’ve chosen to implement the messenger as a complement to an existing web page, so it should fit snugly somewhere on the page that does not interfere with the page’s main usage. We will insert the application on the web page based on an HTML element with the ID messengerView, so it is up to the person who implements the web page to define where this element is displayed. Typically it would be displayed in a page’s sidebar, out of the way of the main content, as illustrated in Figure - 4.


Using this defined area for the application is sufficient for logging in with a display name and presenting a list of other users on the page, but we need another view to display and send messages. Again, it is good to follow the example of a desktop messenger here since people are already familiar with this interface. In a desktop instant messenger, a window pops up when another user sends a message. This can be somewhat intrusive since the user could be working on anything on her computer when the window shows up. Some messengers show a nonintrusive toaster-style pop-up in the bottom, right corner of the screen. This pop-up doesn’t take the focus away from what the user is working on, but provides the ability to click it to bring the Chat window to the foreground. In our Ajax version we don’t have to worry too much about interrupting work on the desktop since we can only notify users of an incoming message in the browser window, but we can use the idea of a pop-up in the bottom, right corner to make the notification more familiar to users. Our Chat window will pop up in the bottom, right corner with all the widgets needed to display messages from the other user and send messages to him or her. Figure - 5 illustrates how the Chat window will be displayed in this application.


The pop-up appears in the bottom, right corner and overlaps whatever content is currently at that location. The user can have more than one conversation. When more than one pop-up appears, we will make it appear to the left of the previous one.

The sequence of events that occurs in the application’s view starts with the sign-in view being displayed in the contact list’s location and asking for the user’s display name. After the user provides a sign-in name, the contact list displays, the application starts receiving events from the server, and
the view responds to these events by rendering the model. The first events that the application may receive are new contacts to be displayed in the contact list. Then the view may receive new messages it will display in a Chat window, one per contact. The view can also receive events from the
user, including opening a Chat window by clicking on a contact. The user can enter messages into a Chat window, which the view sends to the controller to send to the server so that the recipient will receive the message.

To provide this functionality we need four view classes. The MessengerView class manages the views in the application, and the SignInView class provides a view for the user to enter a display name. The ContactListView class shows a list of Contacts on the page and allows the user to open Chat windows with each. The ChatWindowView class provides the list of messages for a chat between two contacts and allows the user to send messages. The UML diagram in Figure - 6 shows these classes.


---------pending----------------

Tutorial - Writing Instant Messenger Application - GWT

FYI.. this tutorial is from Google WebToolkit Application Book Author : Ryan Dewsbury

Instant Messenger Application

This tutorial shows how to build the web-based Instant Messenger application. The application is a good example of building on top of a welldefined GWT-RPC interface. Every client that loads the application will connect to a servlet on the server and make method calls through RPC. Each client connects to the same server, so it is possible for clients to collaborate with each other. The chapter also looks at building an unobtrusive user interface that integrates well with an existing web page and that only presents information to the user when necessary. We close the chapter by seeing how events can be added to HTTP using GWT-RPC and how to integrate with server features that make event-based protocols more efficient. You can work with a running instance of this application at http://messenger.gwtapps.com.

Using the Collaborator Application Pattern

Desktop applications are typically written for people working individually. This makes sense since desktop computers only have one person using them at a time. However, in the real world we tend not to work alone but in teams and multiple people have to collaborate on a single document. For example, many document-based applications are single-user based even when certain documents need to be edited by more than one person. Applications typically don’t have a way to manage this type of collaboration. We resort to passing documents through e-mail or copying them to disk. The Collaborator Application pattern addresses the awkwardness of manual collaboration by building collaboration systems directly into the application.

Building collaborative applications is made substantially easier due to the Internet and its pervasiveness. We can fairly simply transfer data from one source to another. Every person who needs to collaborate just must be able to connect to the Internet and use a web browser. It’s important to have low user requirements for collaboration, even more so than for a single- user application, so everyone who needs to be involved can get involved. Traditional web applications have provided a great collaboration platform in this respect, as shown by the popularity of e-mail and other online collaboration applications. The low barrier to entry for Ajax applications can bring richer experiences to web collaboration.

To build an application using the Collaborator pattern you need to define your model as a centralized model that is accessed through a controller, as illustrated in Figure 1. Each collaborative client interacts with the controller to operate on the model. The controller is then responsible for informing the remaining clients of the model changes. You may be thinking that using a collaboration pattern like this can be a challenge for applications that have their communication based on HTTP, because HTTP does not let servers send data to clients without a request being sent by the client. We’ll look at solutions to this problem later in this chapter.

Figure 1

Instant Messenger Design


If you’re reading this tutorial you most likely are familiar with what an instant messenger does. You’ve probably run into them many times and may even use instant messenger services on a daily basis. Their job is to provide instant textual communication between two or more people that is more conversational than e-mail and less intrusive than a phone call. They have been gaining usage with hundreds of millions of users[ Based on a February 2006 comScore survey (www.comscore.com/press/release.asp?id=800) ]. This is a truly successful
desktop Internet application only rivaled by e-mail clients and web browsers. Bringing this type of application into a browser through Ajax provides the added benefits associated with web-based applications: giving people the ability to communicate from anywhere with a web browser without the need to install client software. Furthermore, the ease of running, building, and deploying an Ajax instant messenger means that it can be used easily in many specialized situations without any barriers to entry.

For this sample application we will create a specialized instant messenger for a web page. It will integrate with a web page as an embedded widget complementing the page’s existing purpose with presence [ Presence is an instant messenger feature that provides realtime online status for you and your contacts ] and instant communication among its users. It will accomplish this by providing a contact list that has, instead of a list of friends or colleagues, a list of visitors to the web page. A visitor will be able to supply his name to be added to the list, and then be able to see other visitors and interact with them through instant messages.

Typically with instant messenger systems the clients do not connect directly to each other; instead, they relay messages through a server. Our application will do the same. Figure - 2 shows a simplified illustration of how clients communicate with each other through the server.

When the client loads the web page, the GWT application will be loaded as well and will connect to the server. The user can input a name and then receive events from the server, such as other users viewing the page and coming online or leaving the page, and messages sent from another user.

Figure - 2

Users can also send messages to other users. The server receives these requests and provides responses in a typical request-response behavior, and it also sends events based on these requests to other users using event protocol behavior.

The Instant Messenger server will run as a GWT servlet with a GWT-RPC interface. The clients will connect and make method calls to the servlet to support the instant messenger functionality. The servlet will implement the RPC interface and provide an event broadcasting system to each client. We’ll discuss the event implementation over GWT-RPC later in this chapter.

The application’s internal design follows the Model-View-Controller architecture. The model represents the objects on which the application operates, including the contacts in the contact list and messages. The view presents the contact list and other windows required to render the Instant Messenger on a web page. The controller implements communication with the server and manages model objects to be rendered in the view.

The Model

The Instant Messenger application’s model has three classes: ContactList, Contact, and Message. These classes are very simple and it is easy to suggest that they are not needed in this application; however, one goal of this sample application is to illustrate how to organize your code. If we were building more functionality into this application, we would be putting more data into our model and would find it useful to separate the application’s components.

Another benefit of the model for this application and for the use of GWT for client applications is that we can share our model objects with serverside code. Since we are implementing the server as a servlet, its implementation is also in Java. Furthermore, GWT-RPC allows transferring of Java objects, which lets us use our model objects again for the structure of our protocol’s data.

So let’s look at the structure of the model. If you’re familiar with instant messenger applications, the UML in Figure - 3 seems intuitive.


The ContactList class contains a list of Contacts and a me attribute. This attribute is a reference to a Contact instance that represents the current user. The Contact class has a name attribute representing the contact’s name, and the Message class has a message attribute for the body of the message. These classes can easily be expanded to add functionality to the application. Also notice that the Message and Contact classes implement GWT’s IsSerializable interface. Implementing this interface and creating a no-arg constructor allows their instances to be transferred over the GWT-RPC protocol. As of GWT 1.4 you can use Java’s Serializable interface instead.

These objects are implemented with simple Java code. The following code shows the implementation for the ContactList class:

public class ContactList {
  private Contact me;
  private List contacts = new ArrayList();
  public ContactList( String name ){
  me = new Contact( name );
 }

  public Contact getMe(){
    return me;
 }
  public void addContact( Contact contact){
    contacts.add( contact );
 }
  public int getContactCount(){
    return contacts.size();
 }
 public Contact getContact( int index ){
    return (Contact) contacts.get(index);
 }
}
The class implements what the UML diagram in Figure 9-3 defined. The class provides three methods for the list of contacts: The addContact method inserts a new contact in the list, the getContactCount method returns the number of contacts in the list, and the getContact method returns the contact at a specific index. Now let’s look at the Contact class:


public class Contact implements IsSerializable{
    private String name;
    public Contact(){}
    public Contact( String name ){
      this.name = name;
    }
    public String getName(){
      return name;
    }
}
This is another simple class. It has just one attribute, the contact’s name. This class can be extended to provide more functionality. For example, you could add an e-mail address so that it could be displayed as a link for the user on the page to e-mail other users. Here we see the benefit of the model with this change. The change would be easily available to the controller, the server (since the model will still transfer over RPC), and the view.



The final class in the model is the Message class:


public class Message implements IsSerializable{
private String message;
public Message(){}
public Message( String message ){
this.message = message;
}
public String toString(){
return message;
}
}
Again, this is another simple class in our model. It has just one attribute, the message body. This class can also be easily extended to provide more information, such as adding a timestamp.



Building a Complementary Interface

This application’s view is responsible for presenting users with instant feedback about the presence of other users on the page and their messages. Typically an instant messenger sits hidden in the taskbar of an operating system, or its contact list fits snugly out of the way at the side of the desktop. By contrast, our Instant Messenger application can’t interact with the desktop or a taskbar and has to share space in a browser window. We’ve chosen to implement the messenger as a complement to an existing web page, so it should fit snugly somewhere on the page that does not interfere with the page’s main usage. We will insert the application on the web page based on an HTML element with the ID messengerView, so it is up to the person who implements the web page to define where this element is displayed. Typically it would be displayed in a page’s sidebar, out of the way of the main content, as illustrated in Figure - 4.


Using this defined area for the application is sufficient for logging in with a display name and presenting a list of other users on the page, but we need another view to display and send messages. Again, it is good to follow the example of a desktop messenger here since people are already familiar with this interface. In a desktop instant messenger, a window pops up when another user sends a message. This can be somewhat intrusive since the user could be working on anything on her computer when the window shows up. Some messengers show a nonintrusive toaster-style pop-up in the bottom, right corner of the screen. This pop-up doesn’t take the focus away from what the user is working on, but provides the ability to click it to bring the Chat window to the foreground. In our Ajax version we don’t have to worry too much about interrupting work on the desktop since we can only notify users of an incoming message in the browser window, but we can use the idea of a pop-up in the bottom, right corner to make the notification more familiar to users. Our Chat window will pop up in the bottom, right corner with all the widgets needed to display messages from the other user and send messages to him or her. Figure - 5 illustrates how the Chat window will be displayed in this application.


The pop-up appears in the bottom, right corner and overlaps whatever content is currently at that location. The user can have more than one conversation. When more than one pop-up appears, we will make it appear to the left of the previous one.

The sequence of events that occurs in the application’s view starts with the sign-in view being displayed in the contact list’s location and asking for the user’s display name. After the user provides a sign-in name, the contact list displays, the application starts receiving events from the server, and
the view responds to these events by rendering the model. The first events that the application may receive are new contacts to be displayed in the contact list. Then the view may receive new messages it will display in a Chat window, one per contact. The view can also receive events from the
user, including opening a Chat window by clicking on a contact. The user can enter messages into a Chat window, which the view sends to the controller to send to the server so that the recipient will receive the message.

To provide this functionality we need four view classes. The MessengerView class manages the views in the application, and the SignInView class provides a view for the user to enter a display name. The ContactListView class shows a list of Contacts on the page and allows the user to open Chat windows with each. The ChatWindowView class provides the list of messages for a chat between two contacts and allows the user to send messages. The UML diagram in Figure - 6 shows these classes.


---------pending----------------

Text Widget

Copyright © Vinay's Blog | Powered by Blogger

Design by | Blogger Theme by