JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Editing eclipse classpath file

July 14, 2008 by itadmin Leave a Comment

While creating a project in Eclipse, by default it creates a .classpath file in the project directory. That file will be usedfor storing file names and other dependent files needed in the classpath to compile and execute the project successfully. Normally this file will be updated automatically when ever you update the project libraries here :


Show Full Image

The following are the few sample values used in the classpath setting :
[code]
src – setting source folders path
lib – setting jar files path
output – setting path for generating class files from the source files.
[/code]

The following is sample .classpath file
[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?><classpath>

<classpathentry kind="src" path="src/java"/>

<classpathentry kind="lib" path="lib/log4j.jar"/>

<classpathentry combineaccessrules="false" kind="src" path="/Project"/>

<classpathentry kind="output" path="WebRoot/WEB-INF/classes"/>

</classpath>

[/code]

Filed Under: Eclipse

Create EJB 3.0 project in NetBeans 6.1

July 4, 2008 by itadmin Leave a Comment

Introduction

This article explains how to create EJB 3.0 project using NetBeans IDE 6.1. This article will not explain the details of EJB 3.0 but will give basic knowledge on how to create simple EJB 3.0 project using NetBeans 6.1 IDE.

also read:

  • Java EE Tutorials
  • EJB Interview Questions
  • EJB 3 Web Services
  • Annotation and Dependency Injection in EJB 3
  • Query API in EJB 3

Creating Project in NetBeans 6.1

Step 1 : Create Project

Show Full Image

Step 2 : Select Enterprice Project

Show Full Image

Step 3 : Specify Project Name

Show Full Image

Step 4 : Select server and create EJB,WEb modules

Show Full Image

Step 5 : Project is created

Show Full Image

Filed Under: Java EE Tagged With: EJB

OpenCms 7 Development

May 21, 2008 by itadmin Leave a Comment

Overview

This book is a guide for developers interested in building websites using the OpenCms content management system. The book is intended for developers who are familiar with Java, JSP, and building web applications based on the Java J2EE framework.

also read:

  • HTML Tutorials
  • CSS Tutorials
  • JavaScript Tutorials

In this book, we will develop a website designed for a blog writer. In the course of building our site, we will go over these topics:

  • The site design
  • Overview of OpenCms
  • Setting up an OpenCms development environment
  • Creating structured content types
  • Creating templates
  • Utilizing search
  • Extending OpenCms
  • Allowing online users to contribute site content

We will go over all the steps involved in building a blog website using OpenCms. We will start by describing the features and requirements of our website and will then provide an overview of OpenCms. Next, we will discuss how to create a development environment. We then will go over the steps involved in creating structured content types, to hold our site content. After that, we will cover creation of templates and Java code, to display the content. The site also supports search and user comments;, so we will cover the Lucene search engine as well to show how to provide login support. As the site additionally supports RSS clients and feeds, we will discuss how to add new features to OpenCms. Before we get into the development details, we will first discuss some of the skills required to develop sites with OpenCms. This will provide us with a basis for understanding the environment and tools, which we will need to do our development work.

The Site Design

Before the development of any site can begin, there should be an understanding of the site’s feature requirements. The feature requirements will often be driven by the actual layout and design of the site. We will design and build a blog website named ‘Deep Thoughts’. The design of the site homepage layout looks like this:

The blog site is designed to support the following features:

  • Blogs are listed in descending order of date, with the most recent blog appearing at the top.
  • Each blog entry is listed in teaser style, with a link to the full blog appearing at the end.
  • Blog entries support a list of topics attached to them.
  • Archives of previous blogs appear on the righthand side, in descending order.
  • Past blog archives can be browsed.
  • The site supports contents search with paginated results.
  • Ads may be placed on the righthand side.
  • Users may self register for the site.
  • Registered users may add comments and create a customized RSS feed on their homepage.
  • Blogs may be viewed in various RSS formats.

    In addition to the features seen in the mockup, we will also support:

  • Direct editing of content in preview mode.
  • User submitted comments.
  • There are two additional mockups for the site. The first one shows a detailed view of a blog. This view is shown when a user clicks on a blog from the homepage:

    The last mockup shows what the search result screen looks like. Search results are shown in decreasing order of relevance to the search term. The pagination controls at the bottom of the page allow for the results to be scrolled, if necessary:

    Required Developer Skills

    The level of technology and coding skills required to do site development will vary depending upon the requirements and features of the site. Designing and architecting a site that properly utilizes and leverages OpenCms is an exercise in itself, which we will not discuss in this book. However, we will discuss the development tasks that are involved, once the architecture has been designed. In general, we can think of four different developer levels and skills.

    Basic Site Development

    OpenCms may be used to manage content right after installation. One way of using it is to import static fi les into the Vir tual File System (VFS) and utilize the publishing and version control features to manage them. In this scenario, files from an existing non-content managed website may easily be content managed. Files in the VFS may be created, edited, and previewed in the offline staging area, before they are
    published to the online file system. When published, versions can be taken to allow for roll back, if necessary.
    Files in the VFS may also be exported to the Real File System (RFS) and served statically or by a web server. In this way, the website can operate in exactly the same way it did, prior to being placed into OpenCms, except for the fact that it is now version controlled. The following illustration shows how OpenCms can be used in this fashion:

    Utilizing OpenCms this way is straightforward, needs little, if any development effort, and probably doesn’t require use of this book! However, it is worth mentioning here that there are a number of sites that can take advantage of this. For this developer audience, the skill levels will include the following:

    • Operational understanding of the use of OpenCms
    • Operational knowledge of Application, Web, and Database servers
    • HTML coding capabilities

    OpenCms also provides a sample site called TemplateOne, packaged as a module. This module contains structured content types and templates. Although somewhat complex and confusing, content types and templates provided with TemplateOne may be used to construct sites without requiring development work. The documentation for these templates may be downloaded from the OpenCms website and installed into OpenCms.

    Sites Requiring Custom Content Types

    After looking at the TemplateOne samples, we may soon realize that it does not quite address our site requirements. Perhaps, the template layouts are not what we desire or the structured content types do not contain the fields necessary to hold our data. In this case, we will want to develop our own JSP code and extend or create our own custom content types. This level of development will require some understanding of Java, JSPs and XML.
    This type of development involves working within the framework provided by OpenCms, to defi ne the templates, content types, and JSPs, and also perhaps java classes that we need. Developing, at this level, does not require us to utilize a development environment such as Eclipse or Netbeans. But we will probably want to use a nice editor for our JSP and XML code.
    Before undertaking this task, we will want to understand the feature and content requirements of our site in detail. This will allow us to properly design the templates and custom content types, which our site will need. This is a design exercise which will not be touched upon in this book. However, we will discuss the specific tasks required in implementing templates and the custom content types once they have
    been designed.

    For this type of development, the developer requires first level skills plus:

    • Understanding of OpenCms modules
    • Basic Java and JSP coding skills
    • Understanding of OpenCms configuration
    • Understanding of OpenCms content types

    Sites Requiring Custom Features

    There are different types of projects that require integration of features which are not provided with OpenCms. For example, we may need a feature that automatically imports data from a back office application into a structured content type. Or perhaps we need to create a content type that we can easily use to define RSS feeds from articles in our site. For these types of projects, we will want to code in Java, using a development environment. We will also probably want to build OpenCms for ourselves, so that we can step through the source and gain a better understanding of how our own code will need to work. We will discuss how to do these, in the later chapters of this book.
    Developing custom features in OpenCms will require the second level skills, plus:

    • Advanced Java coding skills
    • Understanding of OpenCms Java interfaces

    OpenCms Application Overview

    Before undertaking development, it will be helpful to understand the basic design of OpenCms. OpenCms is structured as a typical J2EE web application conforming to a 3-tier web application architecture:

    A web server on the front-end tier services incoming requests. The requests are passed through to an application server in the middle tier, where the OpenCms application runs. The OpenCms application utilizes the database on the third tier to read and store its content. For production, using an array of web servers will typically distribute load to the application server tier. A common choice is to use the Apache web server, utilizing the mod_jk plug-in to distribute load. For development purposes, using a web server is optional, and instead the application server container may be accessed directly. Open Cms supports a wide variety of application servers, including commercial servers such as IBM Websphere and BEA WebLogic. It also supports open source servers such as Tomcat and JBoss. A popular choice among developers is the Apache Tomcat server. We will be using the Apache server for our development environment.
    On the back end, OpenCms supports a variety of databases, including Oracle, Postgreas, and the popular open source database, MySQL. The OpenCms installation setup procedure provides a wizard interface guiding the user through the creation of the database schema. Optionally, it allows for manual creation of the database schema through provided scripts.
    This wide variety of choices makes it easy to install and run OpenCms in many mixed environments. It also allows for easy integration with other technologies, such as portals, CRM systems, and document management systems. Next, let’s take a look at the file structure of an installed environment.

    The OpenCms Directory Structure

    OpenCms must be installed into the application server as an exploded Web Application Resource (WAR) fi le, due to the way OpenCms JSP files are handled. We will discuss more of this, in the later chapters. After extracting the WAR fi le and
    completing the setup process, the file directory structure should look something like this:

    The Real File System Layout

    The web application directory structure should be familiar to anyone who has looked at or developed a web application.
    OPENCMS_WEBAPP_NAME/

    • WEB-INF
    • META-INF
    • export
    • setup
    • resources

    These directories are explained in detail here:

    • WEB-INF: This path contains the web.xml deployment descriptor, and other files used by the application. There are a number of sub-directories located here:
      • classes: This should also be a familiar directory. It contains all class files and property fi les used by the application that are not packaged into JAR files.
        config: This directory contains configuration files. Some settings in these fi les are exposed through the Workplace
      • Administrator and may be changed there. There are many other settings which must be managed manually. However, we will cover some of the settings in the later chapters but many of them are for advanced customizations and are not covered in this book. Here is a summary of the configuration files:

      • opencms.properties         This file contains the configuration information for connecting to the database. The setup program will automatically populate this file, based on the input selections.
        opencms.xml         This is a master configuration file containing the names of classes used to configure a system area. Each class implements the I_CmsXmlConfiguration interface and is called upon, at startup, to parse its configuration
        and initialize its area. This file will rarely need alterations.
        opencms-system.xml         This file contains core system settings such as locales, cache and site definitions. Most of the settings must be changed manually.
        opencms-vfs.xml         This file contains settings related to the virtual file system. This file needs to be edited when adding a new resource type, and this is covered in a later chapter.
        opencms-workplace.xml         This file contains settings related to the Workplace Explorer interface. This file also needs to be edited when adding a new resource type.
        opencms-search.xml         This file contains settings related to searching and search indexes. Most of the settings in this file can be managed though the Workplace Administrator.
        opencms-importexport.xml         This file controls the behavior of importing and exporting files from the VFS.
        opencms-modules.xml         This file contains a registry of modules and is managed by the Module Manager within the Workplace Administrator. Settings in this file should not be modified manually.
      • imageCache: This directory contains a cache of images that have been served from the VFS. All content including images is saved in the database. As images may take a long time to read and retrieve, they are cached here upon first retrieval.
      • index: This directory is where search indexes are built and maintained.
      • jsp: This directory contains JSP files that originate in the VFS. In order to run a JSP file from the VFS, it must first be exported to the disk and made accessible to the web application. This is the default location for these files. As JSPs must be written to the file system, the application must be deployed as an exploded WAR file.
      • packages: This directory contains files that have been exported by OpenCms with the intention of importing to another system. Exported files may include VFS database extraction files as well as exported modules.
      • setupdata: This directory contains a script file used by the installer. It may be deleted after the setup process is complete. Note also that this script may be altered, before a setup is run to customize an installation.
      • META-INF: This is a standard web application directory.
      • export: This directory contains files and resources that have been exported from the VFS to the real file system. If a file in the VFS has been marked for export, then it will be exported to this location. The actual time it gets exported is dependent upon the export configuration. URLs within the VFS that reference this file will be updated accordingly.
      • setup: This directory contains the setup application. After OpenCms has been successfully installed, this directory may be removed.
      • resources: This directory contains resources, such as images, that are used frequently by the application. OpenCms will export frequently accessed items from the VFS into this directory. Items should not be placed here manually, but should rather be managed within a module. This is covered in more detail, in later chapters.

      The Virtual File System Layout

      Now let’s look at the layout of the files in the virtual file system, where the bulk of the application structure exists. To view the entire virtual file system, we must be logged in as Admin and have the root site (/) selected. Underneath the root, there are two main branches:

      • sites: Each directory located underneath this branch represents a site in OpenCms, and is the mechanism used to segregate site content. The title property of each folder appears in the ‘Site’ pull-down of the Workplace Explorer. Adding a site entry is a two-part manual process. First a new folder must be created in the VFS. Then a site entry must be added to the opencmssystem. xml configuration file. Each added site entry must have a unique domain name or IP address. When a request is made originating from the assigned domain or IP address, OpenCms will set the site context so that a request for a file appears to be relative to the site root. For example, if the site http://www.mysite.com is mapped to /sites/mysite/ then a request for index.html coming from that domain will appear to be located at /.
      • system: This directory contains files that comprise the bulk of the OpenCms Workplace Explorer application. There are a number of sub-folders under this directory, which are used by the application. Here is a summary of the folders:
        • categories: This folder is used to defi ne categories that may be applied to a resource. The hierarchy of folder items in this location determines the available categories that may be applied. New categories may be added by creating folders in this location.
        • galleries: This folder is used as a shared repository for content galleries. Galleries created here can be made available to all sites.
        • handler: This folder contains templates used as the handlers for 404 and 500 site error messages.
        • login: This contains the default OpenCms login page template.
        • lost-found: This folder is used to place resources that have conflicts during import or export operations.
        • modules: This folder contains sub-folders with modules and corresponding module resources.
        • orgunits: This folder contains folders used to maintain Organizational Unit structures.
        • shared: This folder contains resources that may be shared.
        • workplace: This folder contains resources that are used by the Workplace Explorer interface.

      The level of development required will determine if any resources within these locations need modifications.

      OpenCms Architecture

      OpenCms has a modular architecture centered on a VFS. The file system is considered virtual as it resides inside a database and not on a hard disk. The VFS is similar to a real file system that supports folders, fi le types, and permissions. Access permission masks on the files and folders, and controls access that users and groups have to the files. The OpenCms VFS also provides a feature very similar to symbolic links in a Unix file system. A link is a directory entry that contains meta-information which is kept separate from the file contents. The core also provides support for basic features such as publishing, access control, and revisions. Layered above this are application level features such as configuration, the user interface, and module support. Module support is a key feature of OpenCms, providing the ability to extend and modify it. Module support is layered on top of OpenCms. A logical view looks like this:

      It is interesting to note that although OpenCms is a web application, it comes with a shell application that provides an interpretive interface to the API from a Java command line interface! Furthermore, it is possible to script this interface to install content into the VFS. Most of our development will center around using, or extending these core features. While working on our project, we will strive to work within the framework that OpenCms provides, rather than modify any OpenCms source code.

      Extensibility through Modules

      Modules are a key aspect of the OpenCms design. They provide a way to package together necessary components that may be easily plugged into OpenCms. Modules are the way that new content types, templates, or web capabilities are added to OpenCms. Later in this book, we will go into the details of creating an administration module for OpenCms.

      The OpenCms Web Request Process

      It would be useful to understand how a request made to OpenCms results in the display of content. The structure of a typical OpenCms URL looks like:
      http://[server]:[port]/[context]/[servlet]/[parameters]
      For example:
      http://mydevserver:8080/opencms/opencms/system/logon/index.html
      Server: mydevserver
      Port: 8080
      Context: opencms
      Servlet: opencms
      Parameters: /system/logon/index.html
      The request will invoke the opencms servlet with the parameter /system/logon/index.html. When the servlet runs, it goes through the following sequence:

      1. Uses the passed in parameter to locate the item in the virtual file system
      2. Determines its access permissions, and see if it can be accessed by the requestor
      3. Determines its file type
      4. Based on its file type, locates a resource loader for that type
      5. Invokes the resource loader to load the file

      There is a bit more going on; but for our discussion we will consider only the previous steps. It can be seen that after permission has been established, a resource loader is utilized to load the file. Resource loaders are responsible for encapsulating the knowledge required to load and execute items requested from the VFS. There are several types of resource loaders provided by OpenCms, and there is a one-to-one
      mapping between an OpenCms file type and a resource loader. Most site content is structured XML, and the assigned loader for this type is the
      CmsXmlContentLoader. When this resource loader is invoked, it examines the properties assigned to the resource, specifically looking for the template-elements property. This property must contain the full path to a template used to render the XML content. The resource loader passes control to the template. When the template runs, it takes the responsibility of parsing the original XML resource, and displaying it. Most templates will be JSP fi les, but they are not restricted to this type. In fact, when a template is invoked, it follows the same loading process, resulting in its corresponding resource loader being invoked. This allows for new template languages to be plugged into OpenCms, by writing and adding new resource loaders.
      As resource loaders act on file types, the extension of a file in the VFS is not signifi cant. This means that a file with an HTML extension in the VFS may, in fact, be run as a JSP file, or vice versa. A useful way to leverage this, is to create a file with a .CSS extension that is in fact a JSP file. The JSP could then dynamically generate the CSS based on browser type. We will discuss resource loaders in more detail in a later chapter.

      OpenCms Web Application Packaging

      Although OpenCms is distributed in a standard WAR file it must be exploded when it is deployed into the application server. This is because, in order to execute a JSP stored in the OpenCms virtual file system, the JSP must be written to the real file system first. As the web application writes to the file system, it cannot be run as a WAR file.

      Building a Complete Site with OpenCms

      In this book, we will build a sample blog site using OpenCms. The site will have the following features:

      also read:

      • DOJO Tutorials
      • jQuery Tutorials
      • We will be able to create blog entries easily.
      • The site will have search capabilities.
      • The site will provide an archive view of our blogs.
      • The site will provide the ability to import RSS feeds from another news site.
      • The site will be able to serve our blog entries as an RSS feed.

      Summary

      We now have a basic understanding of the architecture of OpenCms and how the various pieces fit together. The following chapters will delve into the details of developing with OpenCms.

    Filed Under: Internet Tagged With: OpenCms 7

    Programming Web Services using Apache Axis

    July 27, 2007 by itadmin Leave a Comment

    The article titled Programming Web Services using Apache Axis shows how Axis Framework has simplified the creation of Web Services. It will start with the definition of Web Services and its related terminologies like SOAP and WSDL. Following that the ease with which Web Services are published are explained. The later section explores about the various tools available in the Axis distribution like the Tcp Monitor, Soap Monitor, Mapping between Java and WSDL. Finally the article ends up by giving a Sample Web Service Application deployed in Axis.

    also read:

    • What is UDDI?
    • Apache Axis 2 Web Services
    • RESTFul Java Web Services

    1) Web Services

    1.1) Introduction
    Web Services enables two applications running in two different machines to communicate. Data exchange between two heterogenous applications can be possible with Web Services. Technically, Web Services uses XML to exchange data between applications. Web Service is not a single technology, but instead it is a mix of the following technologies.

    • SOAP
    • WSDL

    Let us look into these two terminologies briefly in the following sections.
    1.2) SOAP
    SOAP, which stands for Simple Object Access Protocol, defines the Request and the Response message format in a Web Service Application. Simply put, it is nothing but a XML structure adhering to a well defined Schema. A Web Service client sends Request to a Web Service in the form of SOAP message and gets the response back in SOAP message only. Let us look into the structure of the SOAP message in the following section.
    A SOAP message consists of a SOAP Envelope which forms the outer most layer and it merely serves as a container for the SOAP Header and SOAP Body Elements. The SOAP Header will carry information that doesn’t constitute to the original part of the message. For example, a SOAP Header may carry some Application Specific Information language such the Locale information. This SOAP Header is optional only. They SOAP Body consist of the original data that needs to be processed by the Web Service Application. Consider the following xml snippet which illustrates the SOAP message.

    [code lang=”java”]
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <soapenv:Header>
    </soapenv:Header>

    <soapenv:Body>
    </soapenv:Body>

    </soapenv:Envelope>
    [/code]

    1.3) WSDL

    Web Services Description Language (WSDL) is again a XML Document that describes the definition of Web Services so that they can be accessible by the Client. Technically, WSDL Document contains the name of the Web Services, the arguments it is going to accept, the URL through which it can be accessed. At a higher level, WSDL contains two definition set, one is the Abstract Definition set which contains very generic information about the various supported data-types along with the information pertaining to messages, port-types and operations. The second is the information very specific to the type of protocol that can be used to access the services, the supported protocol list, the URL information etc. Following is the structure of the WSDL Document.

    [code lang=”java”]
    <?xml version="1.0" encoding="UTF-8"?>

    <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:tns="http://ttdev.com/ss"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="SimpleService"
    targetNamespace="http://ttdev.com/ss">

    <wsdl:types>

    <!– Definition of types here –>

    </wsdl:types>

    <wsdl:message name="requestName">
    <wsdl:part name="requestName"/>
    </wsdl:message>

    <wsdl:message name="responseName">
    <wsdl:part name="responseName"/>
    </wsdl:message>

    <wsdl:portType name="serviceName">
    <wsdl:operation name="operationName">
    <wsdl:input message="requestName" />
    <wsdl:output message="responseName" />
    </wsdl:operation>
    </wsdl:portType>

    <wsdl:binding name="bindingName">
    <soap:binding style="document"
    transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="operationName">
    <soap:operation soapAction="someUrl" />

    <wsdl:input>
    <soap:body parts="requestName" use="literal" />
    </wsdl:input>

    <wsdl:output>
    <soap:body parts="responseName" use="literal" />
    </wsdl:output>
    </wsdl:operation>
    </wsdl:binding>

    <wsdl:service name="serviceName">
    <wsdl:port binding="bindingName" name="bindingName">
    <soap:address
    location="ClientAccessibleUrl"/>
    </wsdl:port>
    </wsdl:service>

    </wsdl:definitions>
    [/code]
    One of the good things about the Axis Engine is that Developers doesn’t really need to know the low-level issues like the SOAP message, WSDL because they are given higher level of abstraction.

    2) Utilities

    Let us look into the following Utilities that comes along with Axis Distribution.

    • Tcp monitor
    • Soap Monitor
    • Mapping between Java and WSDL File

    2.1) Tcp monitor
    Tcp Monitor can be used to monitor the Http Request and Http Response made to Axis Application. To start the Tcp Monitor, have the following Utility file that starts the Gui for the Tcp Monitor Application,
    RunTcpMonitor.java

    [code lang=”java”]package net.javabeat.apache.axis.webservices.playerservices;

    import org.apache.axis.utils.tcpmon;

    public class RunTcpMonitor {

    public static void main(String[] args) {
    tcpmon.main(args);
    }
    }[/code]
    Enter some port number (other than 8080), say 9090 in the Listen Port Text Field and click the Add button. You can see a new second tab opening in the same dialog. Now, launch the browser with the following URL, 'http://localhost:9090/axis'. Now go back to the Tab window to find the Request and the Response in the form of Html format. By listening to the port 9090, whatever Request comes to port 8080, the Tcp Monitor simply forwards the Request and Response to the listening port.

    Http Request and Response monitoring using Tcp Monitor

    2.2) Soap Monitor
    SOAP Monitor functions very similarly like a Tcp Monitor. Whereas Tcp Monitor is used to intercept Http Request and Http Response messages, SOAP Monitor is used to track the SOAP Request and SOAP Response Messages. SOAP Monitor is implemented as a Handler and by default it is not enabled for all the Web Services. If we want to enable SOAP Monitor Handler for both Request and Response SOAP messages, then add the following entry in the deployment descriptor file for the Web Service.

    [code lang=”xml”]
    <deployment xmlns="http://xml.apache.org/axis/wsdd/"
    xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">

    <service name="SomeService" provider="java:RPC">

    <requestFlow>
    <handler type="soapmonitor"/>
    </requestFlow>

    <responseFlow>
    <handler type="soapmonitor"/>
    </responseFlow>

    <parameter name="className" value="SomeService"/>
    <parameter name="allowedMethods" value="*"/>
    </service>

    </deployment>
    [/code]

    Now, whenever, you request for a Web Service, the Soap Monitor will track the Request and Response from the Web Service and will display the Xml Request and Xml Response content in the UI as shown below.

    Soap Monitor monitoring the Soap Request and Soap Response.

    3.3) Mapping between Java and WSDL File

    Axis comes with Utilities that maps between Java Class and WSDL file Objects. For example, let us assume that we have a WSDL file and we want to generate the various Java Classes that can be used to generate the Client and the Server code describing the Web Service. For example, consider the following WSDL file that represents the Add service with a simple add() operation taking two parameters. Following is the example WSDL File,
    AddServer.wsdl

    [code lang=”java”]
    <wsdl:definitions targetNamespace="http://localhost:8080/axis/services/AddService">

    <wsdl:message name="addRequest">
    <wsdl:part name="in0" type="xsd:int"/>
    <wsdl:part name="in1" type="xsd:int"/>
    </wsdl:message>

    <wsdl:message name="addResponse">
    <wsdl:part name="addReturn" type="xsd:int"/>
    </wsdl:message>

    <wsdl:portType name="AddService">
    <wsdl:operation name="add" parameterOrder="in0 in1">
    <wsdl:input message="impl:addRequest" name="addRequest"/>
    <wsdl:output message="impl:addResponse" name="addResponse"/>
    </wsdl:operation>
    </wsdl:portType>

    <wsdl:binding name="AddServiceSoapBinding" type="impl:AddService">
    <wsdlsoap:binding style="rpc"
    transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="add">
    <wsdlsoap:operation soapAction=""/>

    <wsdl:input name="addRequest">
    <wsdlsoap:body
    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    namespace="http://addservice" use="encoded"/>
    </wsdl:input>

    <wsdl:output name="addResponse">
    <wsdlsoap:body
    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
    namespace="http://localhost:8080/axis/services/AddService"
    use="encoded"/>
    </wsdl:output>
    </wsdl:operation>
    </wsdl:binding>

    <wsdl:service name="AddServiceService">
    <wsdl:port binding="impl:AddServiceSoapBinding" name="AddService">
    <wsdlsoap:address
    location="http://localhost:8080/axis/services/AddService"/>
    </wsdl:port>
    </wsdl:service>
    </wsdl:definitions>
    [/code]
    To generate the various client and the server related Java files from the WSDL file, Axis provides a Utility called WSDL 2 Java. For example, consider the following Java program makes use of the Utility.
    AddWSDL2Java.java

    [code lang=”java”]import org.apache.axis.wsdl.WSDL2Java;

    public class AddWSDL2Java {

    public static void main(String[] args) {
    WSDL2Java.main(new String[]{
    "http://localhost:8080/axis/services/AddService?wsdl"});
    }
    }[/code]
    It is important to understand that the default mappings for WSDL to Java. For example, the elements 'portType', 'binding' and 'service' in the WSDL file will be converted into its corresponding Java class type. In the WSDL, the name of the portType is 'AddService' which has a single operation by name 'add' with two parameters called 'in0' and 'in1'. For this, the corresponding class which is generated by the Utility looks like,
    AddService.java

    [code lang=”java”]public class AddWSDL2Java {

    public static void main(String[] args) {
    WSDL2Java.main(new String[]{
    "http://localhost:8080/axis/services/AddService?wsdl"});
    }
    }[/code]
    The 'binding' element in the WSDL file specifies the type of binding (Rpc or Document) and its specifies the protocol used to access the Web Service. It also defines the Encoding Mechanism used for the two input parameters. For this, the corresponding class generated class s given below,
    AddServiceSoapBindingStub.java

    [code lang=”java”]/**
    * AddServiceSoapBindingStub.java
    *
    * This file was auto-generated from WSDL
    * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
    */

    package localhost.axis.services.AddService;

    public class AddServiceSoapBindingStub extends org.apache.axis.client.Stub
    implements localhost.axis.services.AddService.AddService {

    private java.util.Vector cachedSerClasses = new java.util.Vector();
    private java.util.Vector cachedSerQNames = new java.util.Vector();
    private java.util.Vector cachedSerFactories = new java.util.Vector();
    private java.util.Vector cachedDeserFactories = new java.util.Vector();

    static org.apache.axis.description.OperationDesc [] _operations;

    static {
    _operations = new org.apache.axis.description.OperationDesc[1];
    _initOperationDesc1();
    }

    private static void _initOperationDesc1(){
    org.apache.axis.description.OperationDesc oper;
    org.apache.axis.description.ParameterDesc param;
    oper = new org.apache.axis.description.OperationDesc();
    oper.setName("add");

    param = new org.apache.axis.description.ParameterDesc(
    new javax.xml.namespace.QName("", "in0"),
    org.apache.axis.description.ParameterDesc.IN,
    new javax.xml.namespace.QName(
    "http://www.w3.org/2001/XMLSchema", "int"),
    int.class, false, false);
    oper.addParameter(param);

    param = new org.apache.axis.description.ParameterDesc(
    new javax.xml.namespace.QName("", "in1"),
    org.apache.axis.description.ParameterDesc.IN,
    new javax.xml.namespace.QName(
    "http://www.w3.org/2001/XMLSchema", "int"),
    int.class, false, false);
    oper.addParameter(param);

    oper.setReturnType(new javax.xml.namespace.QName(
    "http://www.w3.org/2001/XMLSchema", "int"));
    oper.setReturnClass(int.class);
    oper.setReturnQName(new javax.xml.namespace.QName("", "addReturn"));
    oper.setStyle(org.apache.axis.constants.Style.RPC);

    oper.setUse(org.apache.axis.constants.Use.ENCODED);
    _operations[0] = oper;
    }

    public AddServiceSoapBindingStub() throws org.apache.axis.AxisFault {
    this(null);
    }

    public AddServiceSoapBindingStub(java.net.URL endpointURL,
    javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
    this(service);
    super.cachedEndpoint = endpointURL;
    }

    public AddServiceSoapBindingStub(javax.xml.rpc.Service service)
    throws org.apache.axis.AxisFault {
    if (service == null) {
    super.service = new org.apache.axis.client.Service();
    } else {
    super.service = service;
    }

    ((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
    }

    protected org.apache.axis.client.Call createCall()
    throws java.rmi.RemoteException {
    try {
    org.apache.axis.client.Call _call = super._createCall();

    if (super.maintainSessionSet) {
    _call.setMaintainSession(super.maintainSession);
    }
    if (super.cachedUsername != null) {
    _call.setUsername(super.cachedUsername);
    }
    if (super.cachedPassword != null) {
    _call.setPassword(super.cachedPassword);
    }
    if (super.cachedEndpoint != null) {
    _call.setTargetEndpointAddress(super.cachedEndpoint);
    }
    if (super.cachedTimeout != null) {
    _call.setTimeout(super.cachedTimeout);
    }
    if (super.cachedPortName != null) {
    _call.setPortName(super.cachedPortName);
    }

    java.util.Enumeration keys = super.cachedProperties.keys();
    while (keys.hasMoreElements()) {
    java.lang.String key = (java.lang.String) keys.nextElement();
    _call.setProperty(key, super.cachedProperties.get(key));
    }
    return _call;
    }
    catch (java.lang.Throwable _t) {
    throw new org.apache.axis.AxisFault(
    "Failure trying to get the Call object", _t);
    }
    }

    public int add(int in0, int in1) throws java.rmi.RemoteException {
    if (super.cachedEndpoint == null) {
    throw new org.apache.axis.NoEndPointException();
    }
    org.apache.axis.client.Call _call = createCall();
    _call.setOperation(_operations[0]);
    _call.setUseSOAPAction(true);
    _call.setSOAPActionURI("");
    _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
    _call.setOperationName(
    new javax.xml.namespace.QName("http://addservice", "add"));

    setRequestHeaders(_call);
    setAttachments(_call);

    try {
    java.lang.Object _resp = _call.invoke(new java.lang.Object[] {
    new java.lang.Integer(in0), new java.lang.Integer(in1)});

    if (_resp instanceof java.rmi.RemoteException) {
    throw (java.rmi.RemoteException)_resp;
    }
    else {
    extractAttachments(_call);
    try {
    return ((java.lang.Integer) _resp).intValue();
    }catch (java.lang.Exception _exception) {
    return ((java.lang.Integer)
    org.apache.axis.utils.JavaUtils.convert(
    _resp, int.class)).intValue();
    }
    }
    } catch (org.apache.axis.AxisFault axisFaultException) {
    throw axisFaultException;
    }
    }

    }[/code]
    Similarly, there is one more file generated for the 'service' element which contains the URL to access the Web Service. Axis also provides Java2WSDL, which takes the Java interface having the various Web Service operations as input and will generate the corresponding WSDL file that can be accessible by the Clients.

    3) Sample Application

    Let us finish off the article by giving a Sample Application. This Sample Application is all about querying information from a Web Application. For this, let us assume that we have a mini Cricket Database maintained in the backend and we publish the various services to the Client in the WSDL file. Both types of clients, Browser Client and Console Client are included in the sample Application.
    3.1) Pre-requisites
    For the sample application to work, we need a Web Container (like Tomcat) along with the Axis Distribution.

    • Axix – http://www.apache.axis.org
    • Tomcat – http://www.apache.tomcat.org

    After downloading these bundles make Tomcat point to Axis as a Web Application. To make this one happen, follow the steps,

    1. Go to AXIS_ROOT directory where you can find a directory called 'webapps'.
    2. Copy the axis directory within the 'webaps' directory and paste it into TOMCAT_ROOT\webapps directory.
    3. Start the Tomcat Server by running the startup.bat in the TOMCAT_ROOT\bin directory.
    4. Point to the Browser with the URL 'http://localhost:8080/axis/' (assuming that you are running the server in your local machine with the default port number 8080) to see the following page.

    Home page for Axis

    3.2) Player.java
    Let us model the properties of the player like the player name, the country to which he belongs to, age and the number of runs scored in the Player class. Following is the implementation of the Player class which merely contains the getters and the setters for the above mentioned properties.
    Player.java

    [code lang=”java”]package net.javabeat.apache.axis.webservices.playerservices;

    public class Player {

    private String name;
    private String country;
    private int age;
    private long runsScored;

    public Player(String name, String country,int age, long runsScored){
    this.name = name;
    this.country = country;
    this.age = age;
    this.runsScored = runsScored;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getCountry() {
    return country;
    }

    public void setCountry(String country) {
    this.country = country;
    }

    public int getAge() {
    return age;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public long getRunsScored() {
    return runsScored;
    }

    public void setRunsScored(long runsScored) {
    this.runsScored = runsScored;
    }
    }[/code]

    3.3) Player Database.java
    This is the Helper class which creates some Player objects during the start-up. This class will be used by the Player Service class (which will be seen later) for querying the various player information. Following is the implementation of the PlayerDatabase class.
    PlayerDatabase.java

    [code lang=”java”]package net.javabeat.apache.axis.webservices.playerservices;

    import java.util.*;

    public class PlayerDatabase {

    private static List players;

    public static List list(){
    return players;
    }

    public static Player getPlayer(String name){
    Iterator iterator = players.iterator();
    while (iterator.hasNext()){
    Player player = iterator.next();
    if (player.getName().equals(name)){
    return player;
    }
    }
    return null;
    }

    static {
    initPlayers();
    }

    static void initPlayers(){
    players = new ArrayList();
    players.add(new Player("Tendulkar", "India", 34, 15000L));
    players.add(new Player("Ganguly", "India", 35, 12000L));
    players.add(new Player("Dravid", "India", 32, 11000L));
    }
    }[/code]

    3.4) Player Service.java
    We wish to publish the services of this class to the Clients. The Class given below has four services namely getAgeForPlayer, getCountryForPlayer, getRunsForPlayer and listAllPlayers, the meaning of which is well known from the name of the method names itself.
    PlayerService.java

    [code lang=”java”]package net.javabeat.apache.axis.webservices.playerservices;

    import java.util.List;

    public class PlayerService {

    public int getAgeForPlayer(String name){
    return PlayerDatabase.getPlayer(name).getAge();
    }

    public String getCountryForPlayer(String name){
    return PlayerDatabase.getPlayer(name).getCountry();
    }

    public long getRunsForPlayer(String name){
    return PlayerDatabase.getPlayer(name).getRunsScored();
    }

    public String listAllPlayers(){
    List players = PlayerDatabase.list();
    StringBuilder result = new StringBuilder();

    for(Player player : players){
    result.append(player.getName() + " ");
    }
    return result.toString();
    }
    }[/code]

    3.5) Deploying the Player Service
    As we have seen already, the Admin Client Tility can be used for deploying and un-deploying a Web Service Application. To make things simpler, let us have a simple Java class that does the job of deploying the Player Service to Axis. Following is the code for the same.
    DeployPlayerService.java

    [code lang=”java”]DeployPlayerService.java

    package net.javabeat.apache.axis.webservices.playerservices;

    import org.apache.axis.client.AdminClient;

    public class DeployPlayerService {

    public static void main(String[] args) {
    AdminClient.main(new String[]{"src/deployment/player-service-deploy.wsdd"});
    }

    }[/code]
    The above code references a Xml file called 'player-service-deploy.wsdd' which contains the information to deploy the class PlayerService as a Web Service. Following is the code snippet for the Xml file.
    player-service-deploy.wsdd

    [code lang=”xml”]
    <deployment xmlns="http://xml.apache.org/axis/wsdd/"
    xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">

    <service name="PlayerService" provider="java:RPC">
    <parameter name="className"
    value="net.javabeat.apache.axis.webservices.playerservices.PlayerService"/>
    <parameter name="allowedMethods" value="*"/>
    </service>

    </deployment>
    [/code]

    As we can see, the service name is given as 'PlayerService' which is referring the class 'net.javabeat.apache.axis.webservices.playerservices.PlayerService' containing all the service methods. Also, we have assigned the value '*' to the property 'allowedMethods' meaning that we have granted permission to access all the public methods inside the PlayerService class. Before running the DeployPlayer class, make sure the class-path is made to point the following jars.

    • AXIS_ROOT\lib\activation.jar
    • AXIS_ROOT\lib\axis.jar
    • AXIS_ROOT\lib\axis-ant.jar
    • AXIS_ROOT\lib\commons-discovery-0.2.jar
    • AXIS_ROOT\lib\commons-logging-1.0.4.jar
    • AXIS_ROOT\lib\jaxrpc.jar
    • AXIS_ROOT\lib\log4j-1.2.8.jar
    • AXIS_ROOT\lib\mail.jar
    • AXIS_ROOT\lib\saaj.jar
    • AXIS_ROOT\lib\wsdl4j-1.5.1.jar
    • TOMCAT_ROOT\lib\xercesImpl.jar
    • TOMCAT_ROOT\lib\servlet-api.jar

    After successful deployment, you can see the following output made in your console,

    [code] Processing file src/deployment/player-service-deploy.wsdd <Admin>Done processing</Admin></code>[/code]
    To check whether the deployment has actually happened or not, launch your browser (with the Tomcat Server running) to the following URL. http://localhost:8080/axis/servlet/AxisServlet. There you can see the Player Service among the list of other Web Services, under which you can also find out the list of the operations supported by the Service.
    Player Service along the list of Web Services

    3.6) Un-deploying the Player Service
    Un-deploying the Service follows the same procedure as that of the Deployment , except that the Wsdd Xml file should contain proper instructions for un-deploying a service. Following is the Xml file that un-deploys the Player Web Service.

    [code lang=”xml”]<undeployment xmlns="http://xml.apache.org/axis/wsdd/"> <service name="PlayerService"/> </undeployment>
    [/code]

    The code snippet is very simple as the name of the service is pointing to 'PlayerService' which we want to un-deploy. Following is the Admin Client utility that should be run to un-deploy the service.
    UnDeployPlayerService.java

    [code lang=”java”]UnDeployPlayerService.java

    package net.javabeat.apache.axis.webservices.playerservices;

    import org.apache.axis.client.AdminClient;

    public class UnDeployPlayerService {

    public static void main(String[] args) {
    AdminClient.main(new String[]{"src/deployment/player-service-undeploy.wsdd"});
    }
    }[/code]
    Running the above java program and open to the browser to the URL, http://localhost:8080/axis/servlet/AxisServlet, to find the Web Service not listed in the page.
    3.7) Invoking the Web Services
    To invoke all the supported operations of the Player Web Service, first make sure that the class files (Player.class, PlayerDatabase.class and PlayerService.class) are copied to TOMCAT_ROOT\webapps\axis\WEB-INF\classes directory. Restart the Tomcat server and launch the Browser to the following URL, http://localhost:8080/axis/servlet/AxisServlet'.
    Use the following URL’s to access the various web services operations

    • http://localhost:8080/axis/services/PlayerService?method=listAllPlayers
    • http://localhost:8080/axis/services/PlayerService?method=getRunsForPlayer&name=Tendulkar
    • http://localhost:8080/axis/services/PlayerService?method=getCountryForPlayer&name=Dravid
    • http://localhost:8080/axis/services/PlayerService?method=getAgeForPlayer&name=Ganguly

    3.8) Creating a Console-based Client
    Let us see how to access the Web Service using the Axis Client API with a normal Console Client. Following is the code snippet for the same.
    PlayerServiceClient.java

    [code lang=”java”]package net.javabeat.apache.axis.webservices.playerservices;

    import java.net.URL;

    import org.apache.axis.client.Service;
    import org.apache.axis.client.Call;

    public class PlayerServiceClient {

    public static void main(String[] args) {

    try{
    URL url = new URL("http://localhost:8080/axis/services/PlayerService");

    Service service = new Service();

    Call call = (Call)service.createCall();
    call.setTargetEndpointAddress(url);
    Object result = call.invoke("listAllPlayers", new Object[]{});
    System.out.println(result);

    result = call.invoke("getRunsForPlayer", new Object[]{"Tendulkar"});
    System.out.println(result);

    result = call.invoke("getCountryForPlayer", new Object[]{"Dravid"});
    System.out.println(result);

    result = call.invoke("getAgeForPlayer", new Object[]{"Ganguly"});
    System.out.println(result);
    }catch(Exception exception){
    exception.printStackTrace();
    }
    }
    }[/code]
    The above Client is making use of Axis specific API to access the Web Service. A Call (org.apache.axis.client.Call) object encapsulates a Web Service, which should point to a URL as represented by the Call.setTargetEndpointAddress(). A Call object is usually created using the Service object which is represented by org.apache.axis.client.Service. Invocation of the Web Service operation is made by specifying the operation name and the list of arguments it is going to accept through Call.invoke().

    4) Conclusion

    This article showed you how to write Web Servcies using the Apache Axis Framework. This Framework has simplified the Developmental Process a lot by hiding many of the Xml Stuffs and the low-level Configuration Details and has matured a lot. To summarize, this article initially explained the concepts like SOAP and WSDL which are the core Components for any Web Service Implmentation. Then it explained about Tcp Monitor and SOAP Monitor which are used to intercept Http/SOAP Request and Response. Then the Mapping Utilities for the conversion between Java and WSDL file is covered in detail. Finally the article ended up by giving a Sample Application along with the Clients.

    Filed Under: WebServices Tagged With: Apache Axis

    Comparison of AJAX Frameworks: Prototype, GWT, DWR and Thinware

    May 25, 2007 by itadmin Leave a Comment

    Introduction

    These days we can see that the concept of Web 2.0 is becoming popular. Web 2.0 refers to the concept of new web applications that are interactive in nature and are intended to help people to collaborate and offer services for them, not just static HTML. This stuff became possible, in part, by means of the AJAX technology. For us, java developers, to build applications that are aligned with this very concept of Web 2.0 involves the selection of one tool (or framework) that helps us to accomplish our needs. This article help us in writing a simple web application with the most popular AJAX frameworks designed for Java, in this way we can highlight the main benefits and drawbacks between each of them.

    also read:

    • HTML Tutorials
    • CSS Tutorials
    • JavaScript Tutorials

    Sample application

    The first framework that we want to afford is Prototype and this is not an arbitrary decision. Recently, it has been ranked as the most widely used framework for AJAX development based on Java [1], see Figure 1.
    Es posible que tu navegador no permita visualizar esta imagen.
    Figure 1.

    As the literature [2] mentioned, there exist three ways of designing the Ajax interaction between server and client:

    • Content-centric.This approach involves returning from the server side the HTML codethat would be inserted directly into the client page.
    • Data-Centric.We can receive the information from the server in a standard format,such as XML or JSON, this way we gain independence of the data with

      respect to the presentation layer.

    • Script-Centric.Using this approach you write client code (Javascript code) in the serverside enabling you to update the appropriate client’s structures by

      means of the script code.

    At a glance, you probably ask yourself what does the $’s operator means. It is a very handly alias for the javascript function: document.getElementById, that you might used before. The Ajax.Updaterobject, as you can see, receives, in an anonymous array, the following elements:

    • Identificatorfor the HTML which generates the data.
    • Optional parameters.In this case, we indicate the method of the request (if it is not specified post is the default value) and a javascript function that is invoked if everything went ok.

    is requested, should be something like the following:
    [code lang=”java”]import java.io.IOException;

    import java.io.PrintWriter;

    import javax.servlet.ServletException;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    /** * Servlet implementation class for Servlet: TablePrototypeServlet * */
    public class TablePrototypeServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    private static String[] columns= { "Fruit", "Price", "Stock", "Descrption" };

    private static String[][] data = { {"Lemon", "23.4", "25", "Lemon fruit"}, {"Apple", "34.4", "5", "Apple fruit"}, {"Banana", "10.4", "10", "Banana fruit"}, {"Melon", "17.8", "7", "Melon fruit"}, {"Pear", "20.6", "8", "Pear fruit"}, {"India Berry", "18.5", "15", "India Berry"} };
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response);
    } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter writer = response.getWriter();
    writer.write("<TABLE>");
    writer.write("<THEAD>");
    writer.write("<TR>");
    for (int i=0;i<columns.length;i++) { writer.write("<TH>");
    writer.write(columns[i]);
    writer.write("</TH>");
    } writer.write("</TR>");
    writer.write("</THEAD>");
    writer.write("<TBODY>");
    for (int i=0;i<data.length;i++) { writer.write("<TR>");
    for (int j=0;j<data[i].length;j++) { writer.write("<TD>");
    writer.write(data[i][j]);
    writer.write("</TD>");
    } writer.write("</TR>");
    } writer.write("</TBODY>");
    writer.write("</TABLE>");
    } } [/code]
    As you can see, Prototype provides a very flexible and strong support for the usage of Ajax technologies using a Content-centric approach. If we want to use another approach,
    that provides a cleaner separation of the user interface and the business logic implemented on the server, the burden of the code will be translated to the client side, this should happen because we got to:

    1. Parse the data ina standard format (JSON or XML) based on the particular semantics definedfor the application being developed.
    2. And then, manipulatethe interface elements of the DOM to generate the appropriate output.

    GWT

    For our sample application, you can develop a GWT application without using an IDE, but is much easier the other way around. I prefer to use Googleipse which is an Eclipse plugin that supports GWT. Before using Eclipse, we got to create a GWT project compatible with Eclipse. We can do that executing the following commands:

    [code]projectCreator -eclipse

    gwtTable -out gwtTable

    Created directory gwtTable\src

    Created file gwtTable\.project[/code]

    This creates the gwtTable project into the gwtTable folder. After that, we got to create an application in the following way:

    applicationCreator -eclipse

    gwtTable -out gwtTable javabeat.net.example.client.TableExample

    Created directory gwtTable\src\javabeat\net\example

    Created directory gwtTable\src\javabeat\net\example\public

    Created file gwtTable\src\javabeat\net\example\public\TableExample.html

    Created file gwtTable\TableExample.launch

    Created file gwtTable\TableExample-compile.cmd

    One of the main benefits of developing a GWT application within an IDE environment is the debugging capabilities that it provides (step next, step into, etc.). To take advantage of it we got to define a Debug launcher configuration in Eclipse for this project. Look at the Debug windows of Eclipse under Java Application tree. As it is shown in Figure 4, the Debug launcherconfiguration for the project called gwtTable has already been created for us, and it is ready to run!

    To implement the asynchronic call, that we need to retrieve the data from the server, we implement a JavaBean that encapsulates the generated data. In this example we implement the class TableData in the following way:
    [code lang=”java”]
    package javabeat.net.example.client;
    import com.google.gwt.user.client.rpc.IsSerializable;
    public class TableData implements IsSerializable { private static String[] columns= { "Fruit", "Price", "Stock", "Descrption" };
    private static String[][] data = { {"Lemon", "23.4", "25", "Lemon fruit"}, {"Apple", "34.4", "5", "Apple fruit"}, {"Banana", "10.4", "10", "Banana fruit"}, {"Melon", "17.8", "7", "Melon fruit"}, {"Pear", "20.6", "8", "Pear fruit"}, {"India Berry", "18.5", "15", "India Berry"} };
    public String[][] mydata=null;
    public TableData() { mydata = data; } } [/code]
    after that, we got to define interface which has the remote methods that retrieve the data from the server. the method that we define in this interface is straight forward:
    [code lang=”java”] package javabeat.net.example.client;[/code]
    You also have to define an interface that the client, or the eventual downloaded JavaScript code, will use to call this service method. The GWT uses a callback design pattern, with this in mind we have to develop the following code:
    [code lang=”java”]
    package javabeat.net.example.client;
    import com.google.gwt.user.client.rpc.AsyncCallback;
    public interface TableServiceAsync { void getData(AsyncCallback callback);
    }[/code]
    This class must extend RemoteServiceServlet. In other words, this class and the interface it implements has to be deployed in your servlet container.

    Configuration files

    What is more interesting of this technology is that the client code (that runs on the browser of the client) is implemented in the server side as Java code! GWT compiler is the piece of the puzzle that does all the magic when it translates the Java code into Javascript code for us. With this design in mind, we define a Java class for building the main page of the web application, in this case TableExample.java (which already has a vanilla implementation generated by the command line executed above).
    [code lang=”java”]package javabeat.net.example.client;
    import com.google.gwt.core.client.EntryPoint;
    import com.google.gwt.core.client.GWT;
    import com.google.gwt.user.client.Window;
    import com.google.gwt.user.client.rpc.AsyncCallback;
    import com.google.gwt.user.client.rpc.ServiceDefTarget;
    import com.google.gwt.user.client.ui.Button;
    import com.google.gwt.user.client.ui.ClickListener;
    import com.google.gwt.user.client.ui.Label;
    import com.google.gwt.user.client.ui.RootPanel;
    import com.google.gwt.user.client.ui.Widget;
    import com.google.gwt.user.client.ui.FlexTable;
    /** * Entry point classes define onModuleLoad()</code>. */ public class TableExample implements EntryPoint { TableServiceAsync service = (TableServiceAsync) GWT.create(TableService.class);
    ServiceDefTarget endpoint = (ServiceDefTarget) service;
    /** * This is the entry point method. */ public void onModuleLoad() { final Button button = new Button("Load data!");
    final FlexTable table = new FlexTable();
    endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "/javabeatservice");
    button.addClickListener(new ClickListener() { public void onClick(Widget sender) { service.getData( new AsyncCallback() { // what to do if it works public void onSuccess(Object result) { TableData td = (TableData)result;
    for (int i=0; i<td.mydata.length;i++) { for (int j=0; j<td.mydata[i].length;j++) { table.setHTML(i, j, td.mydata[i][j]);
    } } } // what to do if it fails public void onFailure(final Throwable caught) { Window.alert("failure – \n" + caught.getMessage());
    } });
    } });
    RootPanel.get("slot1").add(button);
    RootPanel.get("slot2").add(table);
    } }[/code]
    Then, we can see the final results using the Debug launcher defined previously in Eclipse (Figure 5).
    Es posible que tu navegador no permita visualizar esta imagen.
    Figure 5.

    DWR

    DWR has a different conception than the other frameworks (because of its design and the way it hasto be used), for this and for its popularity it seemed important to us to mention it in the article. As it is illustrated in Figure6, DWR allow us to work in a RPC’s classic environment, in which you get the freedom to handle the asynchrony communication in an explicit way. It is important to notice that DWR doesn’t provide the user’s interfaces that can be plugged within our web applications, which is an important drawback compared with GWT and Thinware.

    http://getahead.org/dwr/examples/table
    As you can tell from the example, DWR is a very useful approach if you have good Javascript skills because you got to update the GUI by means of Javascript code and DOM manipulation (data-centric approach).

    ThinWire

    Why you should used Thinware instead of GWT? Thinware published an article [4], which identifies many reasons why you may use it instead of GWT, in our opinion, the more representative are the following:

    • Full JavaAPI Access. GWT puts some restrictions on the Java code thatit can translate to Javascript. Thinware doesn’t have this limitation because the GUI is fully developed in Java code.
    • Linear Flowof Logic.As all the logic is implemented in the server, asopposed to GWT, it is easier to develop applications that contain server calls because we don’t have to trace the values from one language into another.
    • Richer Setof Dynamic Component Widgets. You can compare both widget capabilitiesfrom the demo application distributed by both frameworks and make your own judgment. Saying so, we agree with the Thinware’s team at this point. We consider that Thinware’s widgets are powerful than those provided by GWT.
    • Full ScaleDebugging.Easier to debug than GWT, because you develop usinga single language.

    ThinWire framework consists of the set of three JAR files shown in , plus a set of javadocs and a template of a file named web.xml.

    22,379 commons-fileupload.jar
    313,731 thinwire.jar

    To code our application, we just need to implement a main class like the following:
    [code lang=”java”] package javabeat.net.thinware.example;
    import thinwire.ui.Application;
    import thinwire.ui.Button;
    import thinwire.ui.Frame;
    import thinwire.ui.GridBox;
    import thinwire.ui.Label;
    import thinwire.ui.Panel;
    import thinwire.ui.TabFolder;
    import thinwire.ui.event.ActionEvent;
    import thinwire.ui.event.ActionListener;
    import thinwire.ui.layout.TableLayout;
    public class Main { private static String[] columns= { "Fruit", "Price", "Stock", "Descrption" };
    private static String[][] data = { {"Lemon", "23.4", "25", "Lemon fruit"}, {"Apple", "34.4", "5", "Apple fruit"}, {"Banana", "10.4", "10", "Banana fruit"}, {"Melon", "17.8", "7", "Melon fruit"}, {"Pear", "20.6", "8", "Pear fruit"}, {"India Berry", "18.5", "15", "India Berry"} };
    private static GridBox comp = null;
    private static void loadData() { //insert the data for (int i = 0; i > data.length; i++) { comp.getRows().add(new GridBox.Row(data[i]));
    } } /** * @param args */ public static void main(String[] args) { Frame frame = Application.current().getFrame();
    frame.setTitle("ThinWare: Simple Table Example.");
    frame.setVisible(true);
    comp = new GridBox();
    comp.setBounds(255, 70, 250, 150);
    comp.setVisibleHeader(true);
    Button button = new Button("Load data!");
    button.setBounds(255, 270, 70, 30);
    button.addActionListener(Button.ACTION_CLICK, new ActionListener(){ public void actionPerformed(ActionEvent e){ loadData();
    }//end actionPerformed }//end ActionListener constructor );
    //end addActionListener GridBox.Column col;
    Panel panel = new Panel();
    panel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
    panel.setVisible(true);
    //insert the header data for (int i = 0; i > columns.length; i++) { comp.getColumns().add(col = new GridBox.Column());
    col.setName(columns[i]);
    } panel.getChildren().add(comp);
    panel.getChildren().add(button);
    frame.getChildren().add(panel);
    } } [/code]

    to make the magic happened we need to add the following servlet to our web.xml configuration file:
    [code lang=”xml”]<servlet>
    <description> El WebServlet</description>
    <display-name> WebServlet</display-name>
    <servlet-name>WebServlet</servlet-name>
    <servlet-class> thinwire.render.web.WebServlet</servlet-class>
    <init-param>
    <description>
    </description>
    <param-name>mainClass</param-name>
    <param-value>javabeat.net.thinware.example.Main</param-value>
    </init-param>
    <init-param>
    <description>
    </description>
    <param-name>extraArguments</param-name>
    <param-value>initParam,clientInfo,header</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>WebServlet</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping> [/code]
    As you can see, all the client and server interaction is handled by the framework and you don’t have to mess with the plumbing related with the asynchronic communication. The output generated with this example would be similar to the snapshot illustrated in Figure 7.
    Es posible que tu navegador no permita visualizar esta imagen.
    Figure 7.

    Conclusion

    also read:

    • DOJO Tutorials
    • jQuery Tutorials

    As we have been seeing the web is changing and maturing into something different, something more dynamic and interactive. To become part of it we got to use the best tools available to accomplish this kind of new interaction. We presented four of the best tools for that matter, each one of those has its own benefits and drawbacks. Although, the functionality of each is important, you have to take into account which one you estimate will fulfill your needs thinking about the future, because every tool of this kind is growing and making the difference every day. Saying so, Prototype (because of its flexibility and clarity) and GWT (because it is support by Google) are the ones that we think are most valuable.

    Filed Under: AJAX Tagged With: AJAX Frameworks

    • « Previous Page
    • 1
    • …
    • 4
    • 5
    • 6

    Follow Us

    • Facebook
    • Pinterest

    As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

    JavaBeat

    FEATURED TUTORIALS

    Answered: Using Java to Convert Int to String

    What is new in Java 6.0 Collections API?

    The Java 6.0 Compiler API

    Copyright © by JavaBeat · All rights reserved