You are on page 1of 36

Middleware and Application Integration

Companies generally have various existing applications developed in different programming languages on various platforms. The functionalities are scattered across these applications and thus data is also scattered across the applications. Now if one application needs data from another application, the applications have to communicate with each other. However, very often, their storage and representation does not match, and this is a big problem to resolve. This is shown in the figure below, where the two incompatible formats are text and some EDIbased format.

Application A

Text

EDI

Application B

Thus customization in the applications that are communicating is necessary to make calls from one application to another application. This is a time consuming process involving lots of coding and testing efforts. Also it has to be taken care that the existing applications which are up and running live should not be affected anyhow. Now imagine a situation where an intermediate system sits between these applications and handles the communication across the applications smoothly, thus integrating the various applications developed in different programming languages on various platforms, without making a considerable customization in the code of the existing applications. This intermediate system which handles the communication is called as middleware. The idea is shown below.

Middleware

Application A

Text

EDI

Application B

Page 1 of 36

What is Middleware? Middleware is connectivity software that is used to integrate the two separate and usually already existing applications. Typically, middleware programs provide messaging services so that different applications can communicate What is the need of Middleware? In the era of mainframe central computing, services were carried out by many business applications mutually cooperating in a single general-purpose computer called as a mainframe. Then, the client-server systems appeared and various server systems were constructed around a mainframe so that they could use its data. This brought the need for stronger linkages across servers and between servers and mainframes. Following are the main considerations when strengthening these linkages: 1. 2. 3. Generally, one system has to be integrated with multiple systems. Because the systems are already in use, they should be connected with as few reconfigurations as possible. The linkage should be performed in real time to speed up business activities.

To meet these requirements, instead of traditional point-to-point communication, a new integration system called the hub-and-spoke communication was introduced. In this system, data flow is controlled in a unified way by part of the hub and differences in the data formats of information systems are absorbed by conversion. This allows quick linkage between different systems with minimum reconfiguration and is the system used to achieve application integration.

Page 2 of 36

Page 3 of 36

Types of Middleware Following are some of the types of the middleware: 1. Transaction Processing Middleware: This middleware sits between client program and database and ensures that all databases are updated properly. Messaging Middleware: Messaging middleware provides a common interface and transport between the applications. It facilitates synchronous or asynchronous communication. Also a message enrichment, message transformation, routing etc can be performed. Distributed Processing: Distributed object systems such as CORBA, DCOM and RMI enable processes to be run anywhere in the network. Database Middleware: This middleware provides a common interface between a query and multiple, distributed databases. Application Server Middleware: A Web-based application server that provides interfaces to a wide variety of applications is used as middleware between the browser and legacy systems.

2.

3. 4. 5.

Middleware are used for integrating the applications using concept of Enterprise Application Integration (EAI). Various Integration Styles Following are various Integration styles: 1. File Transfer: Integration of the applications where the communication happens by transferring the files. 2. Shared Database: Multiple applications share a common database. Here, the communication across applications happens via databases. 3. Remote Procedure Call (RPC): In this kind of integration communication between applications happens by directly calling the APIs of another application. Here both the applications are tightly coupled with each other. 4. Messaging: In this kind of integration, some middleware software lies in between the applications being integrated and communication happens by passing the messages synchronously or asynchronously between the applications.

Page 4 of 36

Products currently available around middleware There are various middleware products that are available in market and used for Enterprise Application Integration (EAI). Depending on requirements a specific product can be selected. Some of them are IBM WebSphere Integration Message Broker, webMethods, and TIBCO. Key functions performed by Middleware

Hiding distribution, i.e. the fact that an application is usually made up of many interconnected parts running in distributed locations. Hiding the heterogeneity of the various hardware components, operating systems and communication protocols. Providing uniform, standard, high-level interfaces to the application developers and integrators, so that applications can be easily composed, reused, ported, and made to interoperate. Supplying a set of common services to perform various general purpose functions, in order to avoid duplicating efforts and to facilitate collaboration between applications Authenticate users and transactions between systems

Middleware Case Study (Conceptual only): Online Bill Payment system Consider a situation of online payment where the users of an Online Bill Payment System (A) want to make a payment. This system generates or expects messages in XML format. On the other hand, the accounts are maintained in an AS/400 based host system (B), which consumes and also produces incoming messages in fixedlength text format. How do we now integrate A and B by making minimum changes to both applications? Following figure depicts how these applications can be integrated using middleware without making any considerable modification in the existing applications. Also the services of the existing applications remain uninterrupted.

Page 5 of 36

The process flow is as follows: 1. Application A creates an XML message and forwards it to the middleware. 2. Middleware picks the XML message, transforms it to request fixed length format message and routes it to the Bank Host (Application B) for payment. 3. After effecting the payment, application B produces the response fixed length format message and sends a confirmation response to the middleware. 4. Middleware picks the fixed length message sent by application B, t f it t th XML g d t it t li ti A g i Future challenges in designing middleware

Middleware systems rely on interception and indirection mechanisms, which induce performance penalties. As applications become more and more interconnected and interdependent, the number of objects, users and devices tends to increase. This poses the problem of the scalability of the communication and administration. Universal computing is a vision of the near future, in which an increasing number of devices embedded in various physical objects will be participating in a global information network. Mobility and dynamic reconfiguration will be dominant features, requiring permanent adaptation of the applications.

Page 6 of 36

Managing large applications that are heterogeneous, and in permanent evolution raises many questions; such as consistent observation, security, tradeoffs between autonomy and interdependence for the different subsystems, definition and implementation of resource management policies.

Service Oriented Architecture (SOA)


Introduction
SOA (Service Oriented Architecture) has become a buzzword of late. Although the concepts behind SOA have been around for over a decade now, SOA has gained extreme popularity of late due to Web Services. Lets first have a look into the most basic SOA architecture before we start talking about the subject in depth. The following diagram depicts the simplest of SOA architectures.

In its most basic form, the SOA consists of the three components represented in the above diagram:

1. Service Provider - The Service Provider is the one exposing a business service for use by multiple clients. 2. Service Registry - The Service Registry is the place where the Service Provider must register his business service so as to expose his service to multiple clients for easy access.

Page 7 of 36

3. Service Requestor - The Service Requestor also known as the client who wishes to access the service exposed by the Service Provider has to perform two steps in order to actually use the service. First the Service Requestor (Client) has to search the Service Registry to retrieve information on the actual service itself. This information could comprise of various things like the location of the service, the technology used etc. Once the Service Requestor (Client) has this information, it can then call the Service Provider (Service) directly and exchange relevant information. This is how SOA works in its most basic as well as in its most advanced form, no matter what technology is used. Before we dive in and talk about what SOA is and what the essentials behind SOA are, it is useful first step to look back at the evolution of SOA. To do that, we have to simply look at the challenges developers have faced over the past few decades and observe the solutions that have been proposed to solve their problems.

The Problem
Early programmers realized that writing software was becoming more and more complex. They needed a better way to reuse some of the code that they were writing. When researchers took notice of this, they introduced the concept of modular design. With modular design principles, programmers could write subroutines and functions and reuse their code. This was great for a while. Later, programmers started to see that they were cutting and pasting their modules into other applications and that this started to create a maintenance nightmare. When a bug was discovered in a function somewhere, they had to track down all of the applications that used the function and modify the code to reflect the fix. After the fix, the deployment nightmare began. To explain the term deployment nightmare let us look into a client-server based architecture system that existed before SOA came into picture.

Page 8 of 36

The Client-server environments placed majority of application logic and the presentation logic on the client-side. As one can presume, large maintenance costs were associated with the distribution and maintenance of application logic across user workstations in this type of architecture. Because each client housed the application code, each update to the application required a redistribution of the client software to all workstations. In larger environments, this resulted in a highly burdensome administration process.

The Solution
Researchers proposed classes and Object Oriented software to solve this and other similar problems. Again, as software complexity grew, developers started to see that developing and maintaining software was complex and they wanted a way to reuse and maintain functionality, not just code. Researchers offered yet another abstraction layer to handle this complexity, which was called as Component based software. Component-based software is a good solution for reuse and maintenance, but it does not address all of the complexities developers are faced with today, such as distributed software, application integration, varying platforms, varying protocols, various devices, the Internet, etc. Today's software has to be equipped to answer the call for all of the above. In short, SOA (along with Web Services) claims to provide a solution to all of the above. It is argued that by adopting SOA, we eliminate some of the headaches associated with specific protocols and platforms, and helps in the integration of applications.

What Is Service-Oriented Architecture?


Service Oriented Architecture is a style of design that guides all aspects of creating and using business services throughout their lifecycle (from conception to retirement). SOA is also a way to define and provision an IT infrastructure to allow different applications to exchange data and participate in business processes, regardless of the operating systems or programming languages underlying those applications. An SOA can be thought of as an approach to building IT systems in

Page 9 of 36

which business services (i.e., the services that an organization provides to clients, customers, citizens, partners, employees, and other organizations) are the key organizing principle used to align IT systems with the needs of the business. In contrast, earlier approaches to building IT systems tended to directly use specific implementation environments such as object orientation, procedure orientation, and message orientation to solve these business problems, resulting in systems that were often tied to the features and functions of a particular execution environment technology such as CICS, IMS, CORBA, J2EE, and COM/DCOM. What we really mean by the above statements can be explained with the help of a simple example: E.g. Consider a Bank wanting to expose a service to expose a Debit service to its users. In an SOA view of the functionality, the following facts would be considered: 1. A User could be anything from a single person holding an account with the bank, to an organization which is a customer of the bank to other banks wanting to have direct Debit (ECS) transactions for accounts in the bank. How to develop an interface that will be independent of the number/type of users added to the interface requirement. Provide an interface which will be capable of exposing the entire functionality/service in a single piece or only a part of the business functionality/service as required. How to make the interface platform independent so that the Client software dependencies can be reduced to a bare minimum or more possibly, none at all. The SOA would consider building an interface for the said functionality which will be developed entirely from the business perspective so as to make it completely scalable so that even though some additional requirements flow in at a later stage the system can accommodate them without any major changes.

2. 3. 4. 5.

On the other hand simple IT systems could view the functionality in the following ways: 1. 2. 3. What are the current number/types of users that will access the functionality/service? What is the platform/technology required for developing the required service. Only the current requirements for developing the service will be considered. E.g. How are the clients going to access the service? The implementation of the service built on such information will ultimately lead to a less scalable system.

Page 10 of 36

The major difference between service-oriented development and previous approaches is that service orientation lets you focus on the description of the business problem, whereas previous approaches require you to focus more on the use of a specific execution environment technology.

Key Components of SOA


In the context of SOA, we have the following terms: Service Message Dynamic discovery Each of the above plays an important role in SOA.

Service
A service in SOA is the part that is exposed to the outside world. A service can also be invoked by other services as a part of a much larger functionality. Take an example of transferring of funds from one bank account to another. Here there are three services involved: 1. Withdrawal Service 2. Deposit Service 3. Overdraft Service Say the Deposit Service is invoked for depositing a certain amount in account no. 001 after withdrawing the same amount from account no. 002. Here the Deposit Service will internally call the Withdrawal Service which will internally invoke the Overdraft Service to check if the amount to be withdrawn from account no. 002 is actually valid or not. In the above example the Deposit Service can be considered as a standalone service from the requirement perspective with the Withdrawal Service and Overdraft Service acting as helper services. In some other instance it is also possible for the Withdrawal Service and Overdraft Service to function as standalone services as per the requirement.

Page 11 of 36

Message
Service providers and consumers communicate via messages. Services expose an interface contract. This contract defines the behavior of the service and the messages they accept and return. Because the interface contract is platform- and language-independent, the technology used to define messages must also be agnostic to any specific platform/language. Therefore, messages are typically constructed using XML documents that conform to XML schema. XML provides all of the functionality, granularity, and scalability required by messages.

Dynamic Discovery
Dynamic discovery is an important piece of SOA. At a high level, SOA is composed of three core pieces: service providers, service consumers, and the directory service. The role of providers and consumers are apparent, but the role of the directory service needs some explanation. The directory service is an intermediary between providers and consumers. Providers register with the directory service and consumers query the directory service to find service providers. Most directory services typically organize services based on criteria and categorize them. Consumers can then use the directory services' search capabilities to find providers.

SOA and Web Services


Although the concepts behind SOA were established long before Web Services came along, web services play a major role in a SOA. This is because web services are built on top of well-known and platform-independent protocols. These protocols include HTTP, XML, UDDI, WSDL, and SOAP. It is the combination of these protocols that make web services so attractive. Moreover, it is these protocols that fulfill the key requirements of a SOA. That is, a SOA requires that a service be dynamically discoverable and invokeable. This requirement is fulfilled by UDDI, WSDL, and SOAP. SOA requires that a service have a platformindependent interface contract. This requirement is fulfilled by XML. SOA

Page 12 of 36

stresses interoperability. This requirement is fulfilled by HTTP. This is why web services lie at the heart of SOA. Some people confuse SOA with Web Services. SOA and Web Services are two completely different things. SOA is a concept, a design paradigm and Web Service is one of the methods to realize it.

Benefits of Service Oriented Architecture (SOA)


1. Platform Independence Since web services can be published and consumed across development and operating platforms, an enterprise can leverage its existing legacy applications that reside on different types of servers and build additional functionality without having to rebuild the entire thing. It also helps an enterprise to integrate its applications with those of its partners. 2. Location Transparency Web services are often published to a directory where consumers can look them up. The advantage of this approach is that the web service can change its location at any time. Consumers of the service will be able to locate the service through the directory. 3. Greater Testability Small, independent services are easier to test and debug than monolithic applications. This leads to more reliable software. 4. Parallel Development Since the services are independent of each other and contracts between services are pre-defined, the services can be developed in parallel this shortens the software development life cycle considerably. 5. Better scalability Since the location of a service does not matter anymore, the service can be transparently moved to a more powerful server to service more consumers if required. Also, there can be multiple instances of the service running on different servers. This increases scalability. 6. Higher availability Since the location of a service does not matter and you can have multiple instances of a service, it is possible to ensure high availability.

When not to use an SOA


Following is a list of cases where one might not want to go for a SOA: When the customer has a homogeneous IT environment If the organization uses the technologies of a single vendor, then it's possible that the additional overhead of an SOA would not be cost-effective for the organization.
1. 2.

When true real-time performance is critical When things don't change

Consider the braking system of a car. No one will ever want it to be SOA based.
3.

Page 13 of 36

This is the "if it works, don't mess with it" situation. When tight coupling is a pro, not a con Loose coupling is great for enabling communications between applications in a distributed computing environment, and making it easier to change the elements of such an environment. When building an application that will reside on a single computer, however, loosely coupling the components of that application from each other introduces needless overhead.
4.

Conclusion
Reaching the end of the short discussion on SOA we might be able to draw a few conclusions mentioned below: 1. SOA helps in improving the software quality if employed in the proper way. 2. Even if implementing SOA is not entirely possible for an organization, the focus could be on developing components from the business point of view rather than building components that only satisfy the current requirement. 3. SOA in itself is not capable of solving all maintenance problems as is claimed. There will be maintenance issues if the requirements change drastically. Since SOA is just a design paradigm implemented by individuals it is always possible to miss out on a few possible requirements that could arise in the future and could have been taken care of in the current SOA implementation. 4. Also there can be situations where implementing an SOA could actually be an overhead few of which are listed under the topic When not to use an SOA. 5. The benefit potential offered by SOA can only be truly realized when applied across multiple solution environments. 6. One must never conclude that the entire enterprise must become serviceoriented. This is not possible in most of the cases. It is very much possible that an organization has more that one SOA implementations based on reusable and interoperable services built on a vendor-neutral communications platform.

The Death of J2EE

Page 14 of 36

Background
Since the arrival of the Java programming language, the already confusing terminology of the technology stack became even more perplexing! There seemed to be no dearth of technology words, acronyms, and buzzwords that one could read about (and even throw at others!). More the jargon one knew, the better it was (even if one does not actually know what it really means, or how it actually works!). This also seemed to reach its peak with the arrival of the J2EE (Java 2 Enterprise Edition) set of technologies. Then Java became a decade-old technology in 2005. At this juncture, the concept of Web Services had also started to gain a lot of attention, but was not a part of the core set of J2EE technologies. Hence, it was thought that the next wave of J2EE should also cover Web Services. Apart from this, there were some things that Sun had learnt, based on the feedback on the J2EE technologies as they existed at that point of time. For example, it had become clear that the whole specifications and development around the Enterprise JavaBeans (EJB) technology had to be simplified, and also that EJB was not good at representing data from database tables, as it was earlier perceived to be. Other natural technology progressions had to be considered as well, as a course of natural technology upgrade. This updated J2EE, if we can call it that way, is now packaged as Java Enterprise Edition 5 (Java EE). This is how we should call this technology now, and not as J2EE. J2EE is dead! Well, I must confess that this is purely a name change, but

works well to grab attention!

Sun discourages the usage of the acronym J2EE now, and for good measure. This article attempts to demystify all the confusion surrounding Java versioning and what Sun has done to resolve it. The Java-related technologies that help us create enterprise-wide applications are to be called as Java Enterprise Edition (Java EE) now, and not as J2EE.

What is the fuss all about?


For some strange reasons, Sun had decided to name the second release of the Enterprise Java related technologies as Java 2. Hence, everything that was developed on top of it, became Java 2 xxxxx (please refer to the table shown later for more details). This left people wondering as to when would Java 3, Java 4, etc would emerge. On the contrary, Java had already moved from the second release to the fifth release by then! Hence, Java 2 Enterprise Edition 5.0 (or J2EE 5.0 for short) actually meant Java Enterprise fifth edition (and not the second edition)! But the 2 after Java had somehow just stayed on! It served no real purpose or

Page 15 of 36

made any sense. This should have been Java Enterprise Edition 5.0 (i.e. JEE 5.0 in short). This was, clearly, incredibly confusing and unnecessary. Thankfully, Sun has now simply dropped the 2 from the Java name, and the dot zero from the version number. Hence, the nomenclature has become quite simple now, compared to the dreadful days when everyone was confused about which version of which product one was referring to. To understand and appreciate this better, let us have a quick recap of what Sun had done earlier to create all this confusion. Old Old long name acronym JDK New long Description name, with the 2 gone Java No change This is needed if we wanted to just compile Development standard (core) Java programs, which do Kit not make use of enterprise technologies such as JSP, Servlets, EJB, etc. In other words, these programs can make use of all the standard language features such as classes, strings, methods, operators, loops, and even AWT or Swing for graphics. This would translate a java program (i.e. a file with .java extension) into its compiled bytecode version (i.e. a file with a .class extension). Many .class files could be compiled into a Java archive file (i.e. a file with a .jar extension). Java Runtime No change This is the run time environment under Environment which a Java program compiled above would execute Java 2 Java SE It is basically JDK + JRE. Standard Edition Java 2 Java EE This is the enterprise version of Java, Enterprise which meant support for server-side Edition technologies in the Web tier (e.g. Servlets and JSP) as well as in the application tier (e.g. EJB). People specialize in some or all of these tiers.

JRE J2SE J2EE

Note that not only is the 2 dropped, so also is the short-form of Java in the form of the letter J. Now, we must not refer to the older J2SE as JSE. We must call it as Java SE, for example.

Page 16 of 36

Overview of Java EE 5.0


Enough about the naming fiasco! Let us have a quick overview about what Java EE 5.0 offers now. For this purpose, we have borrowed some really good diagrams from the official Java EE 5.0 tutorial developed by Sun Microsystems. The following diagram depicts the communication between the various Java EE application layers. The client tier is usually made up of a Web browser, which means it can primarily deal with HTML pages and JavaScript (among others). These technologies communicate with the Web tier made up of JSP pages, Servlets, and JavaBeans (not EJB!). For example, a Servlet may display a login page to the user, and after the user provides the login credentials, authenticate the user by checking the user id and password against a table maintained in the database, as discussed next. The JSP pages and Servlets then communicate with the Business tier, i.e. with one or more Enterprise JavaBeans (EJB). Note that the Business tier is optional, and is implemented only if the application needs to be able to handle very large volumes of data, provide high security, throughput, availability, robustness, etc. In any case, the Web tier usually talks to the EIS tier for database processing (either directly, or via the Business tier, as explained earlier).

Based on this, the Java EE APIs can be depicted as follows:

Page 17 of 36

Of course, it is not possible to explain any of these in detail here, but a small word on what is new, may perhaps help. In the Web tier (Web container in the above diagram), we now have: Better support for Web Services. This is provided by the APIs called as JAX-WS, JAXB, StAX, SAAJ, and JAXR. Some of these existed earlier, but were very clumsily stacked together. More modern way of developing dynamic Web pages. The JSP technology has become highly tag-oriented, rather than being code-intensive. In other words, the developer does not have to write a lot of code for doing things; but has to instead make certain declarations. Java Server Faces (JSF), which is user input validation technology, built in response to Microsofts Web Controls in ASP.NET. In the Business tier (EJB container in the above diagram), we now have: Much easier way of writing Enterprise JavaBeans (EJB). EJB version 3.0 is again lot more declarative, than code-oriented, making the job of the developer far easier. There are several other changes in EJB, in line with these basic changes. In the EIS tier (Database in the above diagram), we now have: Java Persistence API for easier integration of applications with database.

Page 18 of 36

What does this mean for us?


For a start, we should now resist using the older terms such as J2SE or J2EE in all our internal/external references. *** We should get ourselves familiar with the technology of Web Services (dont worry another article in the series would do that!) *** We need to make our technology teams aware of the new ways in which things are done (e.g. make use of the improved syntaxes in JSP, ensure that we upgrade to EJB 3.0 wherever possible). *** We need to be aware of the new areas in Java EE, over and above Web Services, such as JSF. *** We need to get more and more people certified on the new examinations based on Java SE 5 and Java EE 5. ***

Understanding Hibernate
Introduction
Persisting data means storing it on the disk. Persistent data is useful in almost any application and managing persistence and retrieval of data is one of the major challenges that modern technologies/products are facing. A solution called Object-Relational Mapping (ORM) has gained major popularity over the past few years. ORM is a piece of software/product for the representation and conversion of data between the database and the object-oriented programming languages. Hibernate is one such open-source ORM solution. Some of the other popular ORM project/products are iBatis, Data Access Objects from Apache, NDO (.NET Data Objects) for .NET, TopLink from Oracle, and PowerDesigner. In this article, we focus on Hibernate.

Object-Relational Mapping
ORM software greatly simplifies the transformation of business data between an application and a relational-database. ORM can be viewed as a bridge between an application and the relational-database as illustrated in the following diagram.

Page 19 of 36

Application

ORM Middleware acts a Bridge

Relational Database like MySQL or Oracle

Why Hibernate?
Java provided an initial solution for persistence in the form of Java Database Connectivity (JDBC). JDBC provides simple classes and interfaces to connect to and work with a database. One of the major drawbacks of JDBC is that, one has to embed the application's data into the SQL syntax. For example, for saving the data on the disk, the business object (e.g. a Customer Java object, or an Invoice Java object) has to be converted (i.e. flattened) to rows and columns of a database table. Another solution emerged to this problem as a part of the Enterprise JavaBeans (EJB) technology. Called as entity bean, it was one of the major components in the EJB specification. It failed to provide a persistent layer in the applications because of the inherent complexity. Hibernate is one of the ORM solutions for persisting and querying data from a database. Hibernate does not replace JDBC. Instead, it sits on top of JDBC to connect to the database. Internally, Hibernate uses JDBC calls to connect to a database. However, the programmer does not even need to know this, since Hibernate provides a layer of abstraction on top of JDBC. As a side effect of this, Hibernate can integrate well with all kinds any of Java SE/Java EE application and with any kind of frameworks (such as spring, Struts etc).

How Hibernate Works?


Let us understand how Hibernate works with the help of a small conceptual example. Two components are needed for this sample application. A Java class whose instances are to be persisted on the disk (instead of using traditional JDBC technology). XML mapping file which provides mapping information between the Java class and the database table.

Page 20 of 36

Let us understand all of these. It is expected that the reader has some basic understanding of how Java and XML work. Java class for representing a User Object We have a Java class called User, whose attributes (name, age, and userid of the person) need to be persisted on the disk. Just to add, this class is an example of the standard JavaBeans specification for representing the attributes/properties titled name, age, and userid. As we can see, there is a get and set method per attribute. The get methods can be called by other classes in our application to get or retrieve the attribute values (i.e. name, age, and userid) for a particular instance (i.e. object) of User. Similarly, the set methods can be used by other classes in the application to set or store values for a particular instance (i.e. object) of User. For example, another class, say ReadUser can make the following call: String name = User.getName (); This will return the users name as a string from the User class to the ReadUser class. We are deliberately keeping things simple at the cost of some minor technical errors.

Page 21 of 36

User Java class

Explanation

User.java:
package test; public class User { private String name; private int age; private long userid; public User() { } public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } public long getUserid(){ return userid; } public void setUserid(long id){ this.userid = id; } }

Class User

Attributes: name, age userid Methods: setName(), getName(), setAge(), getAge(), setUserid(), getUserid()

Object1

1111

Amit

27

Object2

2222

Rajesh

24

Page 22 of 36

Client class that wants to persist a User Object on the disk using Hibernate The following Java class (the client application) would make use of our User class explained above, in order to persist the user id, name, and age on the disk. Let us understand it now. package client; import org.hibernate.*; import org.hibernate.cfg.Configuration; import test.User; public class RunClient { public static void main(String[] args) { try{ Configuration conf = new Configuration().configure(); SessionFactory sessionFactory = conf.buildSessionFactory(); Session session =sessionFactory.openSession(); User obj = new User(); obj.setUserid(1111); obj.setName("Amit"); obj.setAge(24); // begin a new transaction Transaction t = session.beginTransaction(); // only marks the object to be persisted session.save (obj); // commit the test values into database t.commit(); session.close(); }catch(Exception e.printStackTrace(); } } } e){

Here, Hibernate configuration file & mapping files are loaded. We will not discuss it in the current context.

obj (instance of User) 1111 Amit 24

Persistence of java object into database table. One more row is inserted into database table User Table Abhay 28 Vijay Ajay Amit 31 27 24

1000 1001 1100 1111

Page 23 of 36

As we can see, the client application first performs some configurations, which we need not worry about here. It then has the following code: User obj = new User (); obj.setUserid (1111); obj.setName ("Amit"); obj setAge (24); We first create an empty object called as obj, which is of type User. We then call the set methods corresponding to the user id, name, and age (as described earlier). This will cause an instance of the User class, titled obj, to be created with the attribute values as specified above, in memory. However, our aim is to store these on the disk, and that too, without using JDBC. For this purpose, we have the following code: // begin a new transaction Transaction t = session.beginTransaction (); // Persist object on the disk using Hibernate session.save (obj); // commit the test values into database t.commit (); The question now is how the obj object, which is in memory, goes to the disk. For this purpose, we need to take a look at the following mapping file. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="test.User" table="User"> <id name="id" column=Userid"> <generator class="assigned"/> </id> <property name="name"> <column name="Name"/> </property> <property name="age"> <column name="Age> </property> </class> </hibernate-mapping>

Java Class name

Userid is Primary Key of the database table. Property name and column name from the table. Property name and column name from database table.

Page 24 of 36

As we can see, the User Java class is mapped to a User database table. The individual User attributes such as userid, name, and age are mapped to respective columns in the User table. So, when the session.save () method in the Java client code shown earlier gets called, it uses the above Hibernate mapping file to transfer the User object from memory to disk. This is how the object gets persisted on the disk. The query/retrieval operation would work in a similar fashion, and is therefore, not explained separately here.

Making Payments using SMS


Introduction
This document explains the idea of making various kinds of payments via a mobile phone using the simple Short Messaging Service (SMS) technology. It is based on the idea of the presence of a gateway between the payer and the bank.

SMS Gateway Provider (SGP)


The SMS Gateway provider (SGP) is a company that hosts services, which facilitate the communication between a mobile phone subscriber and a billing company or a bank. There are many ways to send an SMS using via an SGP. The bank can send an email (using SMTP), an HTTP request, a flat file, or an XML message to the SGP; which the SGP can transform into an SMS to the mobile phone subscriber. This is shown below.

Page 25 of 36

Bank/Biller

SGP

User

Message

SMTP FTP HTTP/HTTPS

SMS

Type PAY and send SMS to 8888

Of these, we will cover the HTTP approach.

Making bill payments using SMS


Let us take an example to illustrate the flow of bill payment through SMS. Consider that Mr A is the customer of AB Electricity Board (ABEB), which allows its customers to make bill payments online (via Internet or by sending an SMS). Hence, the bill payment application is also hosted by ABEB in this case. Requirements To provide the bill payment facility using SMS, ABEB will require: Mechanism to send alerts to the customer in the form of an SMS Tie up with SMS Gateway provider (SGP) Parsing mechanism to parse the HTTP request coming from SGP

Phase 1 Billing company to customer via SGP When the bill is ready and the billing date approaches, the online bill payment application of ABEB will send an SMS alert to the customer A via the SGP as shown below.

Page 26 of 36

Step 1: The application sends the authentication details of the billing company to the SGP via HTTP/HTTPS. This would prove to SGP that the billing company can use SGPs services, based on an earlier agreement between them. For example, let us consider Clickatell as an SGP. Sample HTTP request to be sent for authentication from the application to SGP would be: http://api.clickatell.com/http/auth?api_id=xxxx&user=xxxx&password=xxxx. In response to this request, the SGP will send back a session id if the authentication is successful. At this stage, the billing company would send a second HTTP request containing the session id received from SGP, the customers mobile number, and text message to be sent to the customer. The URL would look something like this: http://api.clickatell.com/http/sendmsg?session_id=xxxx&to=xxxx&text=xxxx&from =xxxx. Step 2: SGP will parse the second HTTP request and route the message to the customer using a protocol called as SMPP (Short Message Peer to Peer). In this example, Customer A will receive the SMS as You have a bill from ABEB for Rs. 350 due on 08/08/2007. Reply Pay 1234 to pay this bill. 1234 represents a unique identifier associated with each bill (which is discussed later in this document). Phase 2 Customers response to billing company via SGP

Page 27 of 36

Now suppose that user A pays the bill by sending the appropriate reply (SMS) to ABEB.

Step 1: Customer will reply back to the same message. Mobile Service provider of the customer will send the message to the SGP using SMPP protocol. Step 2: The SGP will forward the message to the ABEB application in the form of another HTTP/HTTPS request, at the appropriate URL. At this stage, the HTTP request will be parsed by ABEB application and it will extract the text message e.g. PAY 1234. By using 1234, which is the unique identifier for this bill, the ABEB application will execute the bill payment instruction, which will transfer money from the customer As account to ABEBs account. At this stage, the customer would receive a mobile alert in the form Your Bill Payment Instruction has been successfully submitted. The transaction ID is 0001144.

Page 28 of 36

CAPTCHA
What is CAPTCHA?
Tried reading the above line? Yes, you are right! The text is What is CAPTCHA?. You must have seen such distorted characters while opening an e-mail account or creating your account on the site of your mobile phone service provider. CAPTCHA stands for Completely Automated Public Turning to tell Computers and Humans Apart. In CAPTCHA, a computer generates a challenge (the obscured characters that we see on the screen) and expects the human user to see them and manually reenter them in the space provided. Since any computer cannot solve CAPTCHA, a solution to CAPTCHA is believed to be provided by a human being. A common type of CAPTCHA requires user to enter distorted or unclear text in which characters are not easily readable. Following picture will show the usage of CAPTCHA in day-to-day life.

This is CAPTCHA

Characteristics of the CAPTCHAs

Page 29 of 36

1) CAPTCHA can be solved by the humans. 2) It can not be solved by the computers. 3) Every time new tests can be generated automatically which require Artificial Intelligence (AI). 4) CAPTCHAs stop computers from doing certain actions which are supposed to be done only by the humans.

Applications of CAPTCHA
CAPTCHAs are mainly used to differentiate between a human user and a computer. CAPTCHAs are used to prevent automated software performing actions CAPTCHAs can be used in following areas but there are so many other areas where CAPTCHA can be implemented. 1) Online Polls: There are many Web sites where online poll is conducted. It is assumed each individual user must vote only once and enough care is also taken by applying certain measures. But it is so simple to write software program to do the entries (in favor of certain topic or in favor particular participant) in the application automatically and. So this will dilute the whole intention of the conducting polls. CAPTCHAs can stop such automated entries and will do updates only when there is response from CAPTCHAs. 2) Free email service: There are many companies (Yahoo, Google etc) that offer free e-mail service. It is observed that, most of them suffer from a specific type of attack called as bots, that automatically sign up number of hoax accounts, thus wasting the servers space and also bandwidth. This can be improved by using CAPTCHA by verifying the user CAPTCHA before signing up the account.

3) Search engine bots: There are some Web sites that they dont want

to be indexed by search engine. This can be achieved by an HTML tag which prevents search engine bots from reading the Web pages. But some bots are smart enough that they can break the boundary However, to make sure that bots would not enter the Web site, CAPTCHAs are needed. and spam. You can identify that there is human behind the sending an email and accept only such emails.

4) Worms and Spam: CAPTCHAs also offer solution against email worms

Page 30 of 36

5) Posting of blogs:

There are certain programs that post bogus comments on various sites. The purpose is to make that Web page/site more visible to the search engine. This can be avoided by using CAPTCHAs where only humans are allowed to post the blogs.

6) Protecting email addresses from scrapers: Spammers are continuously in search of email addresses and can identify an email addresses posted in clear text. CAPTCHAs provide an effective solution to hide email addresses from Web scrapers. The user has to solve CAPTCHA before showing your e-mail address.

Implementation issues
1) Accessibility: CAPTCHAs must be accessible for all the human users. CAPTCHAs are mainly based on reading text which is not possible for disabled persons. CAPTCHAs should provide an audio version along with visuals. 2) Image presentation: CAPTCHA image must be distorted randomly before appearing on the user screen. Each image must be unique other wise such sites can be attacked.

3) Script level security: The CAPTCHA code should be secure and there
should not be any security problems. This can be achieved by not sending the answer from system to CAPTACHA as a plain text in the HTML form. Also, the application should not use the same CAPTCHA repeatedly.

Introduction to Struts 2.0


Struts 2 Background
Apache Struts is an open source framework based on MVC (Model View Controller) architecture used for developing Java Web applications. Working with Struts involves developing code using JSP, Servlets, HTML and Java. However, the first version of Struts (Struts 1) has some drawbacks and due to growing demand of Web applications plus development of new frameworks like Spring, Stripes and Tapestry led to the creation of Struts 2 which has features like Ajax, rapid development and extensibility. Struts 2 is combination of Apaches Struts Ti and Web Work 2 projects.

Page 31 of 36

Struts 2 Features
Some of the general features of Struts 2 are as follows: Architecture: In Struts 2, Filter Dispatcher (classes for action dispatching in Struts (the controller part of MVC)) decides the suitable action for the request sent by the user. Then the Interceptors use the required processing and the action method executes all the aspects such as data storage and retrieval. This result can be seen on the browser. There is some common processing required on every action like input validations, file uploading or pre-population of controls before the page displays etc. Interceptors are the objects, which performs all such things before and after action is executed. Tags: Tags allow the creation of dynamic Web applications with less coding. Tags help in creating style sheet driven markup. A tag in Struts 2.0 also supports validation and localization of coding. MVC: MVC in Struts 2.0 acts as co-coordinator between applications model and Web view. The framework has its own library and markup tags to present data dynamically. Configuration: Struts 2 has deployment descriptor in XML format with the name as web.xml. The initialization of resources takes place after scanning all the classes using Java packages declared in web.xml. Configuration can be controlled via struts.xml. The configuration files are reliable so that it helps apply changes without starting the Web containers. Struts 2 provide easy integration with the Spring framework. Request handling in every action can be customized. Provides good support for Ajax.

Struts 2 Architecture
Following is the request life cycle in Struts 2 application. User sends the request for processing some transactions or demanding some resource. Request is handled by Filter Dispatcher and Filter Dispatcher determines the appropriate Action. Interceptors are applied on the request for the common functionalities such as validation, workflow etc. Action method is executed to perform database related operations. The result renders the output and the response is returned via filter as per configuration done. Finally output is displayed to the user and some clean up processing is also done as the configuration done.

Architecture

Page 32 of 36

Struts 2 is framework based on standard technologies like Java Filters, Java Beans, XML, etc. For the Model, any data access technologies like JDBC, EJB, and Hibernate can be used and View can be integrated with JSP, XSLT and PDF etc.

Page 33 of 36

Browser

HTTPServletRequest

ActionContextCleanup Other Filters Filter Dispatcher

Action Proxy

Action Invocation

Interceptor Interceptor Action

ActionMapper Tag Subsystems HTML, Form etc Template (JSP)

Configuration Manager struts.xml

Result Interceptor Interceptor

HTTPServletResponse

Servlet Filters

Struts Core

Interceptor

User Created

Action ContextCleanUp filter is optional and useful when integration is to be done with other technologies. Filter Dispatcher delegates the control to ActionProxy to perform an action. Action Proxy takes the help of configuration manager which is initialized from struts.xml. Then the Action Proxy creates an Action Invocation, which invokes Interceptors and invokes the action. Finally the result is rendered to JSP templates. Then Interceptors are executed again in reverse order and response returns after clean up process.

Why Struts 2?

Page 34 of 36

Simplified Design: Programming of abstract classes instead of interfaces was one of the problems of Struts 1 is resolved in Struts 2. Simplified Actions: Actions are simple POJOs (Plain Old Java Object). Any Java class which has execute() method can be used as an action class. And there is no need to implement interfaces all the time. Simplified testability: Struts 2 actions are HTTP and framework independent; this enables Struts application testing easy. Better tag features: Struts 2 enables adding of a style sheet-driven markup capability, which helps in creating pages with less code. Editing tag markup is made easy and JSP tags are fully supported. Easy Configuration: Most configuration values have defaults, which can be used directly. There are XML based configuration files, which is very easy to change as per the needs. Quick start: Many changes can be made at the run time without restarting the Web container. Easy Spring integration: Struts 2 provides easy integration with the Spring framework and one just needs to add Spring beans. Easy plug ins: Any extensions can be added simply by dropping in a JAR file, and no manual configuration required. Ajax Support: Ajax support includes the following: a) Client side validation b) advanced div template provides dynamic reloading of partial HTML c) template which has ability to load and evaluate JavaScript remotely d) rich pub-sub event model.

Comparing Struts 1 and Struts 2


Sr.No. Point 1 Servlet Dependency Struts 1 Action have dependencies on servlet API since the HTTPServletRequest and HTTPServletResponse objects are passed to the execute() method. Programming of abstract class is must rather than an interface. Action classes need to extend framework dependent abstract classes. Supports manual validation via validate() method by using ActionForm. Struts 2 Actions are not container dependent. Actions can be tested in isolation.

Action classes

Actions are not container dependent. Provides a base ActionSupport class to implement commonly used interfaces.

Validation

Threading Model

Supports manual validation via validate() method and the XWork validation framework which makes validation easy and flexible. Action resources must be Action object is created

Page 35 of 36

thread safe and for each request. synchronized. There thread safety issue. should be only one instance of a class to handle all requests. 5 Gathering Input Uses ActionForm to capture inputs and which require extending the base classes of the framework. Uses JSTL-EL and has relatively weak collection and indexed property support.

No

ActionForm is not required. Uses Action properties and which can be access from Web page via taglibs. Uses JSTL but supports powerful and flexible expression language Object Graph Notation language (ONGL)

Expression Language

Values in views

Uses standard JSP Uses ValueStack mechanism to bind objects technology where taglibs into page. can access values without coupling to the views and also allows the reuse of views. Has separate request processor for each module, but all Actions in a module must share the same life cycle. Supports creating different life cycles for each action via Interceptor stacks which can be customized and used with different actions.

Action Execution

Page 36 of 36

You might also like