In this article, we will look at Common Java Architectures. We will look at the main advantages and disadvantages of two tier architectures. We will go into detail into many of key architectural attributes of this type of architecture. This is part of a larger series of articles to help you prepare for the java architect exam. The first article, “Tutorial:Architectural Design for the Java Architect Exam”.

Common Java Architectures, Common Architectural Goals

In the first article, Tutorial:Java Application Design for the Java Architect Exam”, we identified the following guiding principles:
  • Simplicity
  • Productivity
  • The importance of object orientation
  • The primacy of business requirements
  • The importance of empirical process
  • The importance of testability

We’ve discussed these guiding principles and their benefits. Next we will look at the architectural capabilities that are required irrespective of the type of Java EE architecture that is created by the architect.

When your are selecting a Java EE 5 architecture for you project, there are a number of factors that you need to consider. There are a number of goals that are considered valid across all enterprise applications. These goals are:
  • The architecture should be robust this is because enterprise software is important to an organization. Users don’t want to waste time dealing with issues related to the application, they just want it to work so that they can focus on their jobs. In order to achieve this, the software must be reliable and bugfree. Therefore we will leverage those parts of Java EE that allow us to build robust solutions and ensure that we write quality code.
  • The architecture should be performant and scalable enterprise applications must meet the performance expectations of the organization. They must possess sufficient scalability for the application to support increased load with the appropriate hardware. Scalability is an extremely important quality for Internet applications to possess. This is because with internet applications, it is difficult to predict user volumes and behavior. Therefore it is essential to understand the underlying Java EE infrastructure in order to meet both these goals. Scalability will generally require the deployment of multiple server instances in a cluster. Clustering requires sophisticated application server functionality. We must ensure that our applications are designed so that operation in a cluster is efficient.
  • The architecture should take advantage of OO design principles. Object oriented design principles provide proven benefits for complex systems. The way to promote good OO design practice is through the use of proven design patterns. Design patterns provide templates for resolving common problems. There are more than 23 design patterns which were initially popularized in the book, “Design Patterns: Elements of Reusable Object-Oriented Software”. These patterns are not tied to any technology or language and based on these has sprung up whole "JEE patterns" industry. While initially a number of the original "J2EE patterns" were workarounds caused by difficulties with EJBs, as EJBs are now based on Plain Old Java Objects (POJOs) in Java EE, they have now evolved to align with the classic (non-technology-specific) design patterns.
  • The architecture should avoid unnecessary complexity. In Extreme Programming (XP), the mantra is to do "the simplest thing that could possibly work". It is important to avoid excessive complexity as this may be an indication that an application architecture isn't capable of meeting the functional and non-functional requirements. Due to the range of components available, the temptation to over-engineer Java EE solutions by adding complexity in return for capabilities never expressed in business requirements is always there. The problem is that complexity adds to costs throughout the software lifecycle and can therefore be a serious problem. To avoid this we analyze thoroughly the requirements to ensure that our architecture aligns well with them.
  • The architecture should be maintainable and extensible. In the lifecycle of a software application, the maintenance is by far the most expensive phase. One should always factor in maintainability when designing Java EE solutions, especially when the organization has chosen Java EE as one of the strategic languages for the enterprise. Java EE applications will therefore be a key part of an organization's software mix for years, and must be adopt to meet new business needs. In order to achive maintainability and extensibility, it is important that you create a clean design, which ensures that each component of the application has a clear responsibility as well as the components being loosely coupled
  • The architecture should be delivered on time. In order for the organization to achieve it’s objects, it is critical that is is able to deliver new functionality on time. This vital consideration is often neglected when architecting a solution using JEE.
  • The architecture should be easy to test. Testing is an essential activity that is used throughout the software lifecycle to ensure that the code is of sufficient quality to be put into production. You must always be conscious of the implications of design decisions on ease of testing.
  • The architecture’s components should be reusable. Enterprise software should always fit into an organization's long term strategy. By modularizing the application via different component, we can foster reuse of these components in order to eliminate code duplication and leverage IT application investments fully. Code reuse is achieved via good OO design practice.


Outside of these goals and the organization’s business requirements, in the contemporary world of computing devices of various form factors and programming languages capable of running of different hardware, there are also to other goals that could be relevant to your application:
  • The application should support for multiple client types. Based on the statement above, it is an implicit assumption that JEE applications will need to support multiple JEEtechnology client types, such as web applications, standalone Java GUIs using Swing or other windowing systems. The advent of "thin" web interfaces has mitigated the need for this since even for internal applications are moving toward “thin” web interfaces.
  • The application should be portable across application servers. This allows for the organization to have flexibility and choice in the resources used by a JEE application. It’s importance of course is tied to the overall enterprise strategy of the organization and the likelihood of any changes being made in the short to medium term future.


Capabilities

In order to express the goals outline above, the application architecture must express a set of quality driven capabilities that are the same irrespective of the number of tiers that have been designed in the system. We detail the characteristics that are required in the section below.

Availability
The assurance that a service/resource ensures a high level of operational continuity during a contractually relevant time period. This unit is often expressed as a uptime percentage in terms of the number of nines. (i.e. 5 nines 99.999% which translates into 52.56 minutes per year).
Capacity 
Is concerned with the throughput of the application. It can be the ability of the application to run a number of jobs per unit time or some other measurement related to performance analysis.

Extensibility

is concerned with the ability of the system to incorporate relevant new technologies or functionality in an efficient manner.

Flexibility

is concerned with the ability to support architectural and hardware configuration changes in a cost-efficient manner. This is the key to some of the other architectural qualities such as availability, reliability, and scalability. This is done through facilitating location independence of the application code. This means that the effects of changes to the environment or code are localized. Below is a figure showing the impact of flexibility:



Tutorial:Review of Common Java Architectures for the Java Architect Exam-c2-flexibilityarchitecture.jpg
Figure:Effects of Flexibility

Manageability

Maintainability relates to the concepts of portability, transferability (from one development team to another) and adaptability. In order to maintain a system it is necessary to measure and monitor in order to ensure the continued health of a system in relation to the concepts outlined above. An example of a metric that could be used in relation to a particular system is the metric, number of staff hours per month to used to perform normal upgrades.

Reliability

Reliability relates to the resiliency and structural solidity of a system. It is used to measure the level of risk as well as the likelihood of potential application failures and also the defects injected due to modifications made to the software. The objective of checking and monitoring reliability is to minimize application downtime, application outages and errors that directly affect users, and to enhance the image of IT and its impact on a company’s business performance. An example of a metric of reliability would be, users will experience failed sessions no more than 1 time in 1000 attempts (99.9 percent reliability).

Performance

is the ability of the system to respond within the set of performance criteria that has been set forth for the successful functioning of the system. It relates to the ability of the system to met response times for the server as well as for rendering content and concurrency or throughput. For example, one could do performance testing for the first visible response in browser under maximum specified load occurs in less than 3 seconds more than 95 percent of the time. This measurement could be made at the organization’s external firewall. We would also look to identify and control access to expensive process and network boundaries. This is shown in the figure below:


Tutorial:Review of Common Java Architectures for the Java Architect Exam-c2-performancetesting.jpg
Figure:Performance Testing Through Company Network

Scalability
refers to how well an application can cope with changed volumes that are typically, greater concurrent load, often resulting from a increase in the user community. Scalability usually refers to scaling up to a larger load. There are two types of scalability
Vertical scalability comes from adding capacity (i.e. memory, CPUs) to existing servers in order to increase the power of the server. This type of scaling makes fewer demands on the architecture. It is done generally when you believe that the application’s performance is constrained by resource limits. 
Horizontal scalability is done by scaling up to a cluster of servers in order to increase overall throughput of the system. In this case, you are adding servers for your application.

Security
The ability to ensure that information is neither modified nor disclosed except in accordance with the security policy.

Testability

is about the degree of support that a component has for being able to test it within a given context. It is focused on avoiding untestable idioms. Some of the common causes for untestable code are:
  • Components that are tied to a particular container (i.e. J2EE style EJBs)
  • Component that use the Singleton Design Pattern as they force the calling code to have complete knowledge about the class being tested and it being difficult to replace a singleton with a test stub.
  • Static facades since they don’t provide a service interface, all callers are tied to the particular class and the static methods cannot be overridden.
  • Some Java Libraries such as JNDI, JAXP and JavaMail.


Java EE Architectures

We now have the guiding principles, the overall goals as well as key architectural capabilities that are expected for a Java EE application. Next let’s examine the key architectural building blocks for JEE applications. Afterwards we will show you how to assemble these building blocks into an entire application architecture. Three core building blocks are:
  • Client Tier
  • Business Tier. This is central to successful applications.
  • Presentation layer. This may be a UI or a remoting facade.
  • Data access layer. Objects accessing a persistence store—usually, one or more relational databases.
  • Resource Tier.


Let’s look at some important J2EE architectures using these building blocks.
We’ll primarily focus on web applications, although most of the points are relevant to all types of applications. Essentially the differences between web applications and other applications are confined to the presentation tier. The service layer should be identical.

A Java EE platform and application is a multitiered system, we view the system in terms of tiers. A tier is a logical partition of the separation of concerns in the system. Each tier is assigned its unique responsibility in the system. We view each tier as logically separated from one another. Each tier is loosely coupled with the adjacent tier. The figure below shows a Java EE application represented as a stack of tiers:

Tutorial:Review of Common Java Architectures for the Java Architect Exam-c2-logicalsepofconcerns.jpg
Figure:Logical Separation of Concerns

Client Tier
This tier represents all client devices or system clients used for accessing the system or application. A client can be a Web browser, a Java or other application, a Java applet, a smart phone, a iPad, network application, or even a batch process.

Presentation Tier

The presentation tier encapsulates all presentation logic that is needed by clients to service their access to the system. The presentation tier handles processes such as intercepting of client requests, providing single sign-on, conducting session management, managing access to business services, constructing the responses, and delivering the responses to the client. Servlets, JSPs and JSF component beans reside in this tier. Note that servlets, JSP and JSF components produce UI elements. It is also in this tier that one accesses exposed business services from the business.

The Importance of Logical Separation

It’s not always necessary to physically separate business objects from the presentation tier. What is important is to have a logical separation. The first part of a logical separation is to have a well-defined business services layer. The other part is to ensure that accessing such services is straightforward and doesn’t generate any dependency in the UI tier on the technology behind the business service interface.

The Business Tier

The well-defined service layer is the key to a sound architecture. It is the service layer that exposes business logic to clients such as web or other user interfaces or even a remoting layer. It consists of multiple interfaces, each with a well-defined contract. A well-defined service layer should be the following:
  • complete - it should expose all operations that clients will need. It may need to expose distinct interfaces that support the needs of different clients.
  • simple - complexity is only warranted by the complexity of business requirements concerned - the mechanics shouldn’t impose greater complexity.
  • defined in terms of interfaces, rather than classes - this follows good OO practice.
  • object oriented - don’t impose any unnecessary constraints on the business objects. For example, they should not be forced to implement special interfaces or extend a particular superclass.
  • independent of presentation technology.
  • easy to write - this maximizes productivity while reducing costs.
  • makes no assumptions about the underlying data access technology - data access is a lower level issue. Business objects should never deal with data access technologies such as JDBC directly or catch technology-specific exceptions.
  • handles transaction management - clients calling to the business service layer should not have to worry about transactions.
  • compatible with horizontal scalability if needed - there should be nothing in the business services layer preventing clustering. This doesn’t mean that the business services layer itself is providing horizontal scalability.
  • easy to test and thoroughly tested - this is critical as rigorous testing of business objects is essential for building quality applications.


Stateless or Stateful Service Layers

Service objects generally tend to be stateless because service layers of this type are highly scalable. This means that they pose no issues related to replication issues nor do they need to allocate additional resources for every client which would be necessary for a stateful service layer. This means that on the middle tier it is possible to share resources between multiple clients. As such it is much easier for stateless service layers to support remote clients if required.

In a Java EE application, a service layer consists of POJOs running within the EJB container. The benefit of an EJB container is that it will provide the following:
  • management of the lifecycle of business objects - EJB container manages the POJOs. There is no need for anything special for the EJB There is no need to implement anything special for it to do this outside of some annotations that tells the container that it is an EJB.
  • provides a lookup facility capable of resolving dependencies of managed objects that may have collaborators also being managed by the EJB container - this is an application of the Inversion of Control (IoC) pattern which is one of the key responsibilities of the EJB container.
  • provide numerous enterprise services such as declarative transaction management to EJBs running within the container - this is usually done using Aspect Oriented Programming (AOP).

As per good OO design, clients should use interfaces, not classes to access business logic. These interfaces are used to define the contract of the service layer, allowing complete pluggability of different implementation classes. The use of IoC makes defining separate interfaces and implementations easy. One can have business objects and the presentation tier components that use running in the same JVM. Horizontal scalability can be achieved by clustering the entire application deployment in additional JVMs.

Exposing Business Objects

When you have a well-defined service layer, servicing clients should be easy. There are some things that an architect should never expose to clients. Examples of this are:
Remote service layer can work only with serializable parameters and return types. You also need to consider how long it takes the various objects to marshal, unmarshal and travel over the network. Some persistence frameworks require you to explicitly disconnect objects from the persistence store.

Integration Tier


This tier is responsible for communicating with external resources and systems such as data stores and legacy applications. The business tier is coupled with the integration tier whenever the business objects require data or services that reside in the resource tier. The components in this tier can use JDBC, J2EE connector technology, or some proprietary middleware to work with the resource tier. One element which has become more common this tier is the use of Enterprise Service Bus (ESB). This is because it has predefined connectors for most of the most commonly used systems as well as being capable of transformation from one format to another and choreography. It is access to this tier that holds persistent data that most likely determines the performance of enterprise applications. Persistent data tends to be held in a single relational database. In some cases, persistent data can be held in multiple transactional data stores or legacy applications. These systems all tend to be transactional.

Resource Tier

This is the tier that contains the business data and external resources such as mainframes and legacy systems, business-to-business (B2B) integration systems, and services such as credit card authorization.

Network Considerations
The communication between the client and the the other tiers depends on the network. The network is imperfect. Although the client appears to be a stand-alone entity, it is part of a distributed application so it cannot be programmed. There are three aspects of the network which show that it is not perfect:
Latency is non-zero. There is always some delay that can be significant to the response times of the application
Bandwidth is finite. Again impacting the performance of the application
The network is not always reliable.

A well-designed enterprise application must compensate for these issues, starting with the client. Ideally, the client connects to the server only when it has to, transmits only as much data as it needs to, and works reasonably well when it cannot reach the server.

Network Security Considerations


Clients are constrain in how the connect to an enterprise by the different security requirements existing on different networks. For example, clients connecting over the Internet, usually communicate with servers through a firewall. The presence of a firewall limits the available choices of protocols available to the client unless the client has control over the network. Generally firewalls are configured to allow Hypertext Transfer Protocol (HTTP) to pass across, but not other protocols such as Internet Inter-Orb Protocol (IIOP). Because of this general conventions with public facing firewalls, web-based services using HTTP are more commonly used in comparison to services using other protocols such as RMI or CORBA (i.e. IIOP). 

In addition, security requirements also affect user authentication. When the client and server are in the same security domain then authenticating a user is relatively straightforward since you can have the user log in only once to obtain access to the entire enterprise. This scheme is known as Single Sign On. However if the client and server are in different security domains such as when someone is logging in over the internet, the a more sophisticated scheme is needed for single sign on. An example of such a scheme is what is proposed by the Liberty Alliance.

Web Browser Clients

Of all the clients available, web browsers provide the thinnest clients available. Their basic purpose is the rendering of data in human readable form. They tend to rely on servers for application functionality. In terms of deployment, browser are a compelling choice since they require almost no updating. Instead changes to the application, can be uploaded and rendered in a web browser with little to no change to the web browser. Finally they are so widely used in computers and well as mobile devices that it is a ready made platform for delivering new functionality. This is because the leverage the wide use and availability of markup language like HTML as well as other standards such as JavaScript, Cascading Style Sheets (CSS) and the Document Object Model (DOM) means that web browser are ubiquitous and ready for delivering content. The one problem is that standards are notimplemented in the same way across all browsers.

Another, more significant cost of using browser clients is potentially low responsiveness. The client depends on the server for presentation logic, so it must connect to the server whenever its interface changes. Consequently, browser clients make many connections to the server, which is a problem when latency is high. Furthermore, because the responses to a browser intermingle presentation logic with data, they can be large, consuming substantial bandwidth.

Communicating with the Server


Browser clients use HTTP transport protocol to connect to a JEE application over the Web. The interaction on a browser interface is done primarily through clicking hyperlinked text or images, and completing and submitting forms. Browser clients translate these gestures into HTTP requests for a Web server. It is the server that provides the majority of the application’s functionality. Very little functionality exist in the browser save for data input and data rendering. User requests to retrieve data from the server normally map to HTTP GET requests. The URLs of the requests sometimes include parameters in a query string that qualify what data should be retrieved. 

User requests to update data on the server normally map to HTTP POST requests. POST requests can include a MIME envelope of type application/x-www-form-urlencoded, containing parameters for the update. After a server handles a client request, it must send back an HTTP response; the response usually contains an HTML document. A JEE application should use JSP pages or JSF components to generate HTML documents.

Java Clients

There are three different categories of Java clients. These can be divided into three categories.

Application Clients
These are stand-alone application clients execute in the Java 5 Runtime Environment, Standard Edition in a standard computer. They are very similar to the stand-alone applications that run on traditional desktop computers.

Applet Clients

Applet clients are user interface components that generally execute within a Web browser or sometimes although they can execute in other applications or devices supporting the applet programming model. Generally most of the functionally exists on the server and the applet serves are typically more dependent on a server than are application clients, but are less dependent than browser clients. 


MIDlet Clients
MIDlet clients are small applications programmed to the Mobile Information Device Profile (MIDP), a set of Java APIs which, together with the Connected Limited Device Configuration (CLDC), provides a complete Java Platform Micro Edition (JME) runtime environment for cellular phones, two-way pagers, and palmtops.

Validating User Inputs in Java Clients

You can program input validation logic on Java clients. Java clients have a more responsive interface so it is straightforward to write input validation logic.

Communicating with the Server


Java clients may connect to a Java EE application as Web clients (via the Web tier), EJB clients (via to the EJB tier), or EIS clients (connecting to the EIS tier).
  • Web Clients - Java Web clients connect over HTTP to the Web tier of a Java EE application. This aspect of Web clients is particularly important on the Internet, where HTTP communication is typically the only way a client can reach a server. Many servers are separated from their clients by firewalls, and HTTP is one of the few protocols most firewalls allow through. The main issue is that you need to manually program the translation of user input into HTTP requests and interpret HTTP responses in order to update the view. A key consideration for implementing these actions is the format of the messages between client and server. This is because Java clients are free to use any format for sending and receiving messages. This aspect is attractive in low bandwidth environment since binary messages consume little bandwidth.
  • EJB Clients - EJB clients connect directly to the EJB tier using Java Remote Method Invocation (RMI) calls. The problem is that connecting as an EJB client is not always possible especially in cases where the calls need to pass through firewalls not controlled by the organization. Also only applet and application clients may connect as EJB clients. This doesn’t prevent you from using an EJB client within a company intranet, where firewalls generally do not intervene between servers and clients.
  • EIS Clients - EIS clients require a powerful interface, such as the JDBC API, to manipulate data on a remote resource. The danger is that if this interface is misused your data can be compromised. Furthermore, non-trivial EIS clients tend to implement business logic since most of the business logic is attached to the client. This makes it harder to share among multiple types of clients. Although acceptable in limited circumstances such as for administration or management tasks, these types of clients should be limited to cases where the user interface is small or nonexistent and the task is simple and well understood.


Managing Conversational State
Java clients are capable of managing their own session state because they can cache and manipulate substantial amounts of state in memory. This differs from browser clients which need a robust server-side mechanism to maintain session state, This is because Java clients can continue to work while disconnected, which is beneficial in high latency environments or when a connection consumes significant bandwidth. 


Supporting a disconnected operation, requires that the Java client retrieve enough usable data for the user before going offline. The initial cost of downloading such data can be high, but you can reduce this cost by constraining what gets downloaded, by filtering on user preferences, or requiring users to enter search queries at the beginning of each session. Many applications for mobile devices already use such strategies; they also apply well to Java clients in general.

When Java clients manipulate enterprise data, they must know about the model as well as some if not all of the business rules surrounding the data model. For example, the client must understand the concept of booked and unbooked seats for a reservation application and mirror the model of that concept which exists on the server. Then the client could prevent users from trying to select seats that are already reserved, thus enforcing a business rule that is also implemented on the server. Generally, clients manipulating enterprise data must duplicate logic on the server, since in any case the server will enforce all business rules regardless of what its clients do. 


When Java clients manipulate enterprise data, applications need to provide schemes for data synchronization. For example, in a reservation application, if between the time when the user downloads the seating plan and when the user decides the seats they want to buy, another user buys some or all of those seats, the application needs a process for resolving such a conflict. In this case, the server's data has priority over the client's data since tickets are sold on a first come basis and hence the client whose purchases updates the server first gets the tickets. The application could mitigate problems with this by asking the second user if he or she wants the seats that the first user did not buy or, it could refresh the second user's display with an updated seating plan and have the user pick seats all over again.

The Future of Web Services

In the early days of the Internet, it was common for enlightened businesses to connect to it using SMTP, NTTP, and FTP clients and servers to deliver messages, text files, executables, and source code. As the Internet became a more fundamental tool for businesses and was being used to integrate their corporate information into the emerging Web framework, the focus on transactional protocols shifted to a focus on data objects and the links between them.

The technologies characterizing the early Web framework were HTML-GIF/JPEG, HTTP, and URIs. The combination of these standardized formats, a single application protocol, and a single universal namespace was very powerful as corporations using these technologies integrated their diverse online publishing systems into something much more compelling than any one of them could have built. Once organizations converged on common formats, the HTTP protocol, and a single addressing scheme, the Web went from a set of Web sites to became the world's most diverse and powerful information system. Organizations built links between their information and other organization’s and individuals. Amazing third party applications also weaved the information together such as Google, Yahoo and Babelfish.

The first generation web services were not integrated with each other and were not designed so that third parties could easily integrate them in a uniform way. The next generation will be more like the integrated Web that arose around online publishing and human-computer interactions. In fact, the second generation web services will be built much more heavily on the architecture that has made the Web work, using the following: standardized formats (XML vocabularies)
a standardized application protocol (i.e. HTTP)
a single URI namespace.

This next generation of web services will most likely follow the architectural style called REST, the underlying architectural model of the current Web. It stands for "representational state transfer" and was created by Roy Fielding while he was doing his PhD dissertation. REST explains many of the feature of the Web such as URIs, HTTP, HTML, JavaScript, as well as other features.

Massively Scalable Web Services

The two most massively scalable, radically interoperable, distributed applications in the world today are the Web and email. They are so scalable and interoperable primarily because they depend on standardized, extensible message formats (HTML and MIME), and they depend on standardized, extensible application protocols (HTTP and SMTP). The key thing to grasp is that each has a standardized, extensible, global addressing scheme.
In the world of XML web services, properly implemented, XML web services permit you assign addresses to data objects so that they may be located for sharing or modification.
This is the web's central concept of a single unifying namespace of URIs. URIs allow the dense web of links that make the Web worth using. They bind the Web into a single mega-application.

URIs identify resources, which are fundamentally conceptual objects. Representations of them are delivered across the web billions of times per day via HTTP messages. These ideas are so simple and yet they are profoundly powerful and successful. URIs are extremely loosely coupled. You can even pass a URI from one "system" to another using a piece of paper and OCR. URIs are late bound. They do not declare what can or should be done with the information they reference. It is because they are so radically "loose" and "late" that they scale to the level of the Web. This is the future of web because of its simplicity and power. Web Services going forward will be built more and more as REST Web services. If you want to know more about REST, see the articles, "Tutorial:Review of REST Web Services for the Web Service Developer Exam I” and "Tutorial:Review of REST Web Services for the Web Service Developer Exam II" that is part of the Web Service Developer Exam series.

Conclusion

OK. That's it for the common java architectures.