Monthly Archives: July 2013

Search Engine Indexing

Search engine indexing

It’s usual practice now a days to have an application’s stage environment as well as production URL’s exposed to the internet. To avoid Google bots indexing through your staging URL, use the following meta tags in your web application’s head section as shown below:

If you want only Google bots to avoid indexing your staging URL’s, use the following meta tag as show below:

This is something very useful. If you dont do these for your staging URL’s, when user’s search for your application using the various search engines, due to high level of testing, it could be that the search engine returns your staging URL as the first search result above your production URL and this can be catastrophic for your applications success.

For more details, please contact the below link:

https://support.google.com/webmasters/answer/93710?hl=en

Page Visitors: 257

Spring Book – Chapter 8 – Data Access

One of the very important aspect in any enterprise application is the ability to get data in and out of your application with ease. Thinking on the same lines, Spring framework provides extensive support for data access. In this Chapter we will first explore the various data access technologies and then see the support provided by Spring for using these technologies in your application.

Spring effectively makes data access easier by managing the various resource for you, by providing abstraction and easy API helpers and by supporting all major data access technologies available in the industry so that you don’t have to get yourself bogged down to a particular technology. Going along with the Spring philosophy it lets your Spring application integrate to any data access technology with ease.

In this Chapter we will see the support given the Spring framework in interacting between data access layer and the service layer in your application. Spring compressive support for transaction management will be covered briefly as we have dedicated Chapter 9 for this specific topic. In this chapter we will also be covering various data access frameworks and technologies which the Spring framework integrates with almost ease.

Enterprise Data Access

Spring integrates and works just fine with all leading data access technologies at present available in market. Accessing eternal system like a database requires various resources at various stages. You will also have to look for resource contention and make sure that resource which is limited is managed properly and efficiently. Such resource management becomes critically important in mission critical enterprise application.

Putting the burden of maintaining these resources in an application to a developer not only puts additional pressure in a developer but also puts an additional risk on the overall application’s success. Spring provides comprehensive resource management capability which takes this burden away from the developer and entrust him with writing the actual business application logic.

Resource Management

As discussed earlier Spring integrates seamlessly with almost all data access technologies like JDBC, Hibernate, iBatis, JPA or JDO in a consistent way. Using Spring, you are not locked down to a particular technology and as case may be, you have the freedom of switching between the various technologies without worrying too much about the technology specific nitty-gritties. Figure 8-1 also shows the various classes which will be used to in the code samples in this chapter in various sections.

Figure 8-1. Spring Integration with well know data access technologies

Spring internally take care of the various resource management functionalities specific to data access technologies so that the developer concentrates on the actual application logic rather than data access technology specific coding.

Some of the key features which the Spring framework provides in resource management are:

  • Transaction Management
  • Connection Management
  • Exception Handling

In a typical application, the resource management capabilities are related with connection and transaction management. While trying to manage connection and transaction, there are exceptions that arise and resource management should also be capable of dealing these exceptions in timely and orderly fashion. Figure 8-2 shows a typical resource management scenario in an application.

Figure 8-2. A typical resource management scenario in any application

The following sections will look into these features of Spring in some detail so that you get a clear picture of what are the features which Spring transparently does for you in developing your application.

Page Visitors: 10629

Spring Book – Chapter 7 – Testing

Testing is an integral part of enterprise software development. It is one of the most important phases of the Software Development Lifecycle (SDLC) and has gained more importance in last decade or so. Having said that, there are many constraints either from framework level or project level, which makes testing effort in a project more challenging and time consuming. In this chapter we will first touch upon the importance of testing and see what are the various testing techniques employed in a typical application. Along the way we will see the problems imposed by various frameworks in achieving full test coverage.

After that we will see, how the Spring framework supports you in making your application more testable.

Why Testing Is Important?

As definition goes, testing is the practice of making objective judgments regarding the extent to which the system meets, exceeds or fails to meet stated objectives. Software Testing is the process used to help identify the correctness, completeness, security, and quality of developed computer software. Testing is a process of technical investigation, performed on behalf of stakeholders, that is intended to reveal quality-related information about the product with respect to the context in which it is intended to operate.

There are two fundamental purposes of testing; verifying specifications and managing risk.  First, testing is about verifying that what was specified is what was delivered. It verifies that the product meets the functional, performance, design, and implementation requirements identified in the specifications. Second, testing is about managing risk for both the acquiring organization and the system’s vendor/developer.

To find the importance of testing, you need to understand the goals of testing. Below are some of the important goals of testing:

  • Verify against a written and agreed specification
  • Assess quality of the software
  • Reveal failures if any in the delivered software
  • Verify contract such as legal, standards etc.
  • Learn how program works

TDD

Test-driven development (TDD) is an evolutionary approach to development which instructs you to have test-first development intent. You start by writing a test and then you code to elegantly fulfill the test requirements.

The steps in a typical TDD are shown in Figure 7-1 below. The first step is to quickly add or expand a unit test to your test suite. Next you run the test suite to ensure that the new test does in fact fail. You then update your functional code until it passes the test suite. Once the test suite does not fail, you should refactor the code; and then start over again.

Figure 7-1. TDD Steps

Refactoring – is a development practice for restructuring an existing code, altering its internal structure without changing its external behavior. Refactoring keeps the code clean and easy to understand.

Types of Testing

Tests can be grouped by where they are added in the software development process, or by the level of specificity of the test. The main levels during the development process are unit, integration, and system testing.

Unit Testing

Unit testing is a testing methodology employed to test a specific unit in an application. It does this verification process totally in isolation from other components. This testing has become so prominent that in some software development methodologies (Agile), the unit test cases have to be written before the actual class implantation which does the real work.

Unit tests must follow the FIRST Rules; these are Fast, Isolated, Repeatable, Self-Validated and Timely. Unit tests should be written in such a manner so as to test all the methods in the class along with all exception paths in the methods. The main aim of unit testing is to quickly test any new code or change to any existing code without spending much effort an time.

Though there are advantages, there are inherent limitations to this type of testing.  These don’t address the testing of the actual functional requirements of the application. These tests only cover testing of each module in the application. Also, we can’t test scenarios like asynchronous services which require configuring of JMS message queues inside the application server. Having said that, this is one of the testing types which is very important and can be used to test as much application functionality as possible.

Multiple unit test cases constitute to form a test suite. There are several open source products which allow the application team to setup and run these unit test cases. One of the well-known products is called JUnit. Being most popular, it has good integrations with other tools (Eclipse) and frameworks (Ant, Maven).

These types of tests are usually written by developers as they work on code to ensure that the specific intended function is working. Unit testing alone cannot verify the functionality of a piece of software, but rather is used to assure that the building blocks using which the software is built, work independently of each other.

Page Visitors: 5829

Spring Book – Chapter 6 – Enterprise Integration

Spring’s core support includes its capability of configuring application, enterprise integration, its testing capabilities and data access methodologies. In Chapter 4, I introduced you to various configuration styles available in Spring. In Chapter 5, I continued on to explain the various simplifications that you can do in your application. In this Chapter I will be covering enterprise integration which is one of the core support provided by the spring framework in detail.

I always like to call an application enterprise. For an application to be called enterprise, it needs to have enterprise components/objects on which it is built. I call an object enterprise when it has capability to handle transactions, capable of existing in a secured environment, has capability to integrate with other system, and so forth.

Using Spring framework, you can make simple POJOs getting transformed into what I call as enterprise objects, with minimal involvement of developers. Developers spend more time writing the actual business logic and the Spring container does all the magic behind the scenes.

Spring framework provides comprehensive infrastructural support for what we call an enterprise application. One such important component in any enterprise application is its capability to integrate. Spring handles plumbing involved in integrating various components in an enterprise application so that you can focus on actual business logic/business use case. Integrating enterprise application can be done in many ways. Each way has its own advantages and disadvantages. We will be discussing the various enterprise integration styles available in some detail in subsequent sections and will also cover the support rendered by Spring to achieve these integration styles in your enterprise application.

Integration Styles

Enterprise Application Integration (EAI) is an application of technology defined as the integration of data and services between applications. The patterns of modern day EAI are usually attributed to Enterprise Integration Patterns, by Gregor Hohpe, et. al., that categorizes and explains many of the integration patterns common to integration solutions. Hohpe, et. al., list four types of integration styles:

1. Shared Database: two systems query the same database for data to be passed. An example of this is when you have two EARs deployed whose entity classes (JPA, Hibernate, etc.) shared common tables for performing various business processes.

2. Remote Procedure Call: each of two systems expose services that the other can call. An example of this is EJB services, or SOAP and REST services.

3. Messaging: two systems connect to a common messaging system and exchange data and invoke behavior using messages. An example of this is the familiar hub-and-spoke JMS architecture.

4. File Transfer: two systems produce files whose payload is the message to be processed by the other system. An example of this is polling a directory or an FTP directory for a file and putting appropriate business logic and processing it.

These styles are disparate because no one solution will work all the time. According to requirement in your application, choose the right style which best fits your requirement. These architectural styles are different with each having its own unique advantages and disadvantages. The standards in JEE fall short to some extent and don’t provide complete solution when integration with other systems.

Shared Database

Integration between two systems can be as simple as joining two tables. Nevertheless, there arise several issues when you try to integrate two systems using this integration methodology. First of all it is difficult to come up with a single schema that will suit the needs of both the application and second is the creation of interdependencies between two systems having diverse requirements and mixing it could as good as mixing oil and water. That means it will never gel together in the ideal enterprise application as we think.

Having said that Shared database has its own advantages like it’s simple and transactional. Some of the disadvantages which can be attributed to this style of integration are that it could be slower and retard or obstruct the database schema evolution over a period of time with more and more features added onto the enterprise application due to changing business dynamics.

Figure 6-1. Shared Database Integration style

Spring framework provides extensive support for this integration style. The support by Spring for this integration style is as below:

  • Extensive support for transaction management
  • Ease of using JDBC using JdbcTemplate
  • Support for Object Relational Mapping (ORM)  integration
  • DataAccessException hierarchy makes exception handling easy
  • Spring Data, an umbrella project in the Spring framework

These will be explained to some extent in the following sections.

Transaction Management

Transaction management is critical in any form of applications that will interact with the database. The application has to ensure that the data is consistent and the integrity of the data is maintained.

Comprehensive transaction support is among the most convincing reasons for using the Spring framework. The Spring framework provides a consistent abstraction for transaction management that delivers various benefits. Some of which are:

  • Consistent programming model across different transaction APIs such as Java Transaction API (JTA), Java Database Connectivity (JDBC), Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO)
  • Declarative transaction management
  • Simpler API to code on
  • Excellent integration with Spring’s data access abstractions

We will be covering Spring’s support for managing transactions in Chapter 8, “Data Access” in detail. I just wanted to bring in this point here so that you will be able to link when we discuss this topic later in subsequent chapter.

Spring JDBC

Using conventional could be clumsy and not so clear way of doing things. Spring makes coding in JDBC easy and elegant using JdbcTemplate.

We will be covering Spring’s support for JDBC in Chapter 8, “Data Access” in detail.

Page Visitors: 2883

Spring Book – Chapter 5 – Application Configuration – Simplified

As we saw in Chapter 4, Spring provides three ways of configuring the container: XML, annotations, and last but not the least, Java configuration. The fact is, both XML and annotations have valid pros and cons. I am not saying that Java configuration is the answer to all the cons of both XML and annotations. I have given detailed pros and cons of each configuration styles in Chapter 4.

Configuration Styles – Pros and Cons

Just to re-state, pros of XML configuration can be:

  • Separation of concerns
  • Configurations kept outside the classes
  • Configuration easy to view
  • Configuration changeable without recompiling, etc.

Cons of XML style of configuration are:

  • Since XML is all string based, when used in the Java context, all these have to be converted to appropriate Java types, and this conversion could be painful and time consuming for the Java Virtual Machine.
  • Typos are very difficult to debug
  • Not type safe because of these strings

Pros of annotation-based configuration are:

  • Being Java it’s type safe, Spring does the configuring of its container in a speedy way
  • Indirect advantage being, it self-documents the class (open the class and you can see what is being injected by Spring)

Cons of annotation-based configuration are:

  • Cluttering of POJO’s
  • Any change requires change of application code
  • Any change requires recompilation and deployment

Pros of Java configuration are:

  • Being Java it’s type-safe, Spring does the configuring of its container in a speedy way
  • Clean separation of concerns
  • Single resource representing the application configuration
  • For systems which needs change constantly, configuration can change without changing the application code which is key for such systems.

Cons of Java configuration are:

  • Any change requires recompilation and deployment

Just by looking at the pros of Java configuration style, you can see that it includes the advantages provided by both XML and annotation type configuration. The only significant con to Java configuration is the requirement to recompile and redeploy if a change in configuration occurs.

In sum, Java is one of the best configuration styles that can be used in your application. However, we cannot just ignore other configuration styles. In this Chapter we will explore the different ways to simplify configuration so that we can mix and match various configuration styles in your application and make use of the advantages provided by all the various styles available with the Spring framework.

Bean definition inheritance

If multiple beans in your XML configuration scheme have certain features in common, you can use Java to create a parent bean, allowing your child bean to override some values or to add other values as needed. This way of using parent and child bean definitions can save a lot of time in addition to reducing your bean definition complexities. This can be called as a sort of templating pattern in Java.

Take an example class Employee as shown in the following example. We will be using this as the base class to explain the bean inheritance in detail.

[java]public class Employee{

private String name;

private String address;

private String designation;

//….

}[/java]

Inheritance with abstract

In the following example, parentEmployee bean cannot be instantiated as the class created is abstract in nature. This way you can make parentEmployee as a template and not allow others to instantiate it. If you try to instantiate parentEmployee bean you will get org.springframework.beans.factory.BeanIsAbstractException exception.

[xml]<bean id="parentEmployee" class="com.mybook.sample.Employee" abstract="true">

<property name="address" value="Dubai"/>

<property name="designation" value="STE"/>

</bean>

<bean id="childEmployee" parent="parentEmployee">

<property name="name" value="john"/>

<!– Here we are overriding the parent property namely designation–>

<property name="designation" value="SSE"/>

</bean>[/xml]

Page Visitors: 3752

Spring Book – Chapter 4 – Configuration Styles

In this Chapter, I will be explaining the various types of configuration styles that are available in Spring Framework to achieve Dependency Injection (DI). I will explain in detail the various configuration styles with working sample codes for clear understanding of each configuration styles. I will then give some best practices which can be followed to make your code maintainable and ways to avoid confusions and frustration to the developers as the application grows in size over a period of time.

Introduction to Spring Configuration Styles

Spring provides the following three ways of supplying metadata to the spring container to make the beans in your application ready to be used in your application as fully capable java objects:

  • XML
  • Annotations
  • Java

We can even mix and match the various ways of configurations in your application at will and spring doesn’t specify a particular way as best because it depends on the application that you are developing and the standards that your organization have already set. In the following sections, we will explore in detail the various configuration styles on which you could build your enterprise application.

History of Configuration Styles

Even though Spring allows developers to use any of the configuration styles currently available in your Spring application, it has supported various styles over a period of time, starting from the first version of Spring Framework, which was released in 2004. The history of configuration styles can be represented in tabular form as below:

Spring Version

Year

Configuration Style

Figure

Spring 1.0 2004 XML

Figure 4-1. XML Configuration

Spring 2.5 2007 Annotation

Figure 4-2. Annotation Configuration

Spring 3.0 2009 Java

Figure 4-3. Java Configuration

XML-based configuration

XML based configuration style was the first style based on which Spring Framework began its journey in the framework business. As the framework evolved over a period of time various alternatives to XML based configuration came and the framework accepted one by one configuration style gracefully. Spring uses dependency injection (DI) to achieve simplification and testability. (See Chapter 3 for detailed information about what DI is and the different forms of DI and their use.) However, the XML configuration files are verbose and unwieldy. They can become hard to read and manage when you are working on a large project where many Spring beans are defined. Simple XML based dependency injection in Spring is done shown in Listing 4-1:

Listing 4-1. XML based Dependency Injection in Spring

Lifecycle

Figure 4-4. XML based configuration lifecycle

Spring container loads the XML definitions according to the file locations supplied to the various ApplicationContext provided by Spring Framework. (The various ApplicationContext provided by Spring Framework are detailed in below section namely “Creating ApplicationContext”). Once this is done the BeanFactoryPostProcessor methods defined in the application are called. Soon after this, the actual bean instantiation and dependency injection happens. If BeanPostProcessor is defined, these are called as described in Chapter 3.

The following section provides an example of declaring/injecting various configurations using XML.

Injecting Scalar Values

Here in the below code snippet, “myString” and “32” are two scalar variables (member variables) in the class LoyaltyServiceImpl which need to be injected using the configuration.

Listing. Injection of Scalar variables in XML configuration

Corresponding Java code to the above XML configuration is:

Listing. Java Code for the above XML configuration

To show the example of bean configuration which requires injecting of lists and other collection types namely properties, Set and Map, I would like to use a class as below:

Listing. Class used to explain the injection of various types in XML configuration

Page Visitors: 4628

Spring Book – Chapter 3 – Spring Quick Start

In this chapter, we’ll see how Spring works and review its working principles. We’ll take a detailed look at bean definitions, accessing bean instances, and various bean scopes available in Spring Framework. The chapter also goes into detail about the Application Context lifecycle, with deep dives into the various phases of the lifecycle so that you understand the crux of Spring. Finally, because Dependency Injection is a very important concept in Spring, reducing code maintenance as well as increasing developer productivity, we provide a comprehensive discussion of this subject.

How Spring Works

The Spring container is at the core of Spring Framework. It creates the objects, wires them together, configures them, and manages their complete lifecycle from start (creation) to end (destruction). It uses dependency injection (DI) to manage the components that make up an enterprise application. Each object in the Spring container is called a Spring bean.

The Spring container gets its instructions by reading configuration metadata provided to it and, based on this, it decides what objects to instantiate, configure, and assemble. The configuration metadata can be provided to the container either by XML, Java annotations, or Java code. Weak-application POJO classes combined with the provided metadata instructions added to the Spring Container become powerful components in the enterprise application. Spring achieves all this by not locking down the application to any JEE-specific application servers. Figure 3-1 provides a high-level view of how Spring actually works in lay terms.

Figure 3-1. How Spring works

A Typical Application Requirement

A typical enterprise application consists of many components working together to achieve a business-problem solution. (In our sample application, various modules, such as Customer and Shipment, interact at various stages in an application to realize a business case. Implementing some changes in business dynamics will be cumbersome, however. (With Spring, you have a choice to swap the implementation with mere configurations.) As illustrated in Figure 3-2, each component might or might not interact with another, and as a whole, the enterprise application becomes monolithic in nature, with no way to separate the various components from the enterprise application if there is a change in business dynamics. It also becomes very hard to swap a component with a new implementation, which is a vital requirement in modern business dynamics and is an integral factor when architecting any enterprise application. Spring Framework tries to address these issues in an enterprise application in an easy way, without overhead, and it also reduces maintenance nightmares.

Figure 3-2. Various components in an application work together to actualize a business application.

Flaws

The main flaws in a typical enterprise application can be summarized as:

  • Parts (components) in an enterprise application find it difficult to search and integrate with other parts of the same application.
  • A part becomes obsolete because of changing business dynamics of an enterprise application, and it becomes hard to swap or change. This introduces maintenance nightmares and diminishes application agility.

Figure 3-3. A typical interaction between components in our sample application

As shown in Figure 3-3, components interact with one another in an enterprise application in a tightly coupled way, and any change in one component in the assembly point can adversely affect the other component and its behavior. As already mentioned, it also becomes very hard to swap one component with a similar or more sophisticated component, because of business changes/challenges. In the model shown in Figure 3-3, using Spring, at various stages of application, development components can be swapped according to your business needs. For example, if persisting logic changes—for example, moving away from conventional JDBC to Hibernate—you can easily swap the CustomerRepository with a new implementation based on Hibernate and replace it using the application configuration file of Spring container.

In a typical application development cycle, testing cannot be overlooked or ignored. Unit testing with the actual infrastructure might not be the right solution, however,  for the infrastructure aspect as well as for the time aspect. In this case, using Spring Framework, each component in the application can be swapped without any code changes to take in a new component implementation that doesn’t have dependency on the actual infrastructure but that does have dependency on a memory database, which is faster and more reliable for unit testing by developers. That is, using Spring, you can write a new implementation of any component, and the application can use these sample implementations by mere Spring configurations for doing the system testing. An easy and convenient way of testing is to use mocks. Spring out-of-box supports unit testing with JUnit and TestNG. Spring provides a separate set of classes to help you unit test your Spring classes. In Chapter 7, we cover testing of Spring applications in detail.

It’s a general conception that over a period of time, with growing complexity and size of the projects, JEE applications becomes more complex and unmanageable. Some of the reasons sttributed for this can be summarized as below:

  • JEE applications tend to contain excessive amounts of “plumbing” code which are unnecessary and unmanageable creating complexity and cluttering of code.
  • The EJB component model is generally considered to be unduly complex.
  • Compared to unit testing capability provided by other fraemworks available in the market, JEE applications are hard to unit test.

Spring to the Rescue

Spring works on the core principle of Inversion of Control (IoC). Using IoC, it tries to address the common issues that any enterprise application faces in the real world. It does this by taking the burden off the shoulders of the developers and allowing easy configurations of various components in an enterprise application. Developers always program to the interface, and Spring out-of-box gives support to creating and autowiring various instances needed by objects in a typical enterprise application.

Spring enables you to enjoy the key benefits of J2EE while minimizing the complexity encountered by application code. The essence of Spring is that it provides enterprise services to Plain Old Java Objects (POJOs). This is particularly valuable in a Java EE environment, but application code delivered as POJOs is naturally reusable in a variety of runtime environments.

Spring allows assembly of an application by using various components. These components have no trouble finding each other, and they can be easily swapped according to the business requirements. The components can be in POJOs and deployed in the Spring container, which in turn manages these objects, which in Spring Framework are called beans.

Page Visitors: 2586