Tuesday, March 9, 2010

Introduction to Behaviour-Driven Development with Groovy


What's Behaviour-Driven Development ?

Behaviour-Driven Development (BDD) is an evolution in the thinking behind TestDrivenDevelopment and AcceptanceTestDrivenPlanning. It brings together strands from TestDrivenDevelopment and DomainDrivenDesign into an integrated whole, making the relationship between these two powerful approaches to software development more evident.

It aims to help focus development on the delivery of prioritised, verifiable business value by providing a common vocabulary (also referred to as a UbiquitousLanguage) that spans the divide between Business and Technology. It presents a framework of activity based on three core principles:
  1. Business and Technology should refer to the same system in the same way - ItsAllBehaviour

  2. Any system should have an identified, verifiable value to the business - WheresTheBusinessValue

  3. Up-front analysis, design and planning all have a diminishing return - EnoughIsEnough
BDD relies on the use of a very specific (and small) vocabulary to minimise miscommunication and to ensure that everyone – the business, developers, testers, analysts and managers – are not only on the same page but using the same words.

For people familiar with the concept of DomainDrivenDesign, you could consider BDD to be a UbiquitousLanguage for software development. It must be stressed that BDD is a rephrasing of existing good practice, it is not a radically new departure. Its aim is to bring together existing, well-established techniques under a common banner and with a consistent and unambiguous terminology. BDD is very much focused on “Getting the words right” and this focus is intended to produce a vocabulary that is accurate, accessible, descriptive and consistent.

What's Problem ?
Test Driven Development (TDD) has established itself as a useful--and at its best, profound--improvement in the software development process. It delivers a variety of benefits to its practitioners; some of them are related to testing, but the most important benefits are not.

Experienced practitioners, particularly those that have been involved in helping other developers learn the practice, note a life-cycle to TDD's learning and adoption:
  1. The developer starts writing unit tests around their code using a test framework like JUnit or NUnit.

  2. As the body of tests increases the developer begins to enjoy a strongly increased sense of confidence in their work.

  3. At some point the developer has the insight (or is shown) that writing the tests before writing the code, helps them to focus on writing only the code that they need.

  4. The developer also notices that when they return to some code that they haven't seen for a while, the tests serve to document how the code works.

  5. A point of revelation occurs when the developer realises that writing tests in this way helps them to “discover” the API to their code. TDD has now become a design process.

  6. Expertise in TDD begins to dawn at the point where the developer realizes that TDD is about defining behaviour rather than testing.

  7. Behaviour is about the interactions between components of the system and so the use of mocking is fundamental to advanced TDD.
We have observed this progression in many developers, but unfortunately while most, with a little help, find their way to step 4, many miss the big wins found at steps 5, 6 and 7.

We started wondering why this was, and wondering what we could do to help people get to the good stuff more quickly. Looking closely at this evolution in understanding, while step 1 may be considered to be related to testing, the rest really are not. For the remainder of the steps in this process, the test aspect is very much a secondary concern.

The issue at the heart of this learning process is the behaviour of the system. Developers gain confidence in the systems they build when the behaviour of that system is confirmed.

By writing tests in advance of code, the developer defines the behavioural intent of the system that they are developing. Tests that document the behavioural intent of the system are most valuable as documentation of that system. By specifying the behaviour of the code in tests, developers are able to best consider the interface from the perspective of the consumer of the service rather than as the producer – thinking more abstractly about the nature of the solution and so hiding technical detail.

This focus on behaviour ahead of testing is a focus on the real value in TDD, and in our experience is the mark of the genuinely experienced TDD practitioner.

It is not too surprising that it takes apprentice TDD practitioners a while to realize that TDD is not about testing when all of the nomenclature surrounding it is described in terms of testing. 

and what's solution ?

The aim of Behaviour Driven Development (BDD) is to address this shortcoming. By using terminology focused on the behavioural aspects of the system rather than testing, BDD attempts to help direct developers towards a focus on the real value to be found in TDD at its most successful.

BDD aims to bridge the gap between the differing views of computer systems held by Business users and Technologists. It is deeply rooted in the success of TDD and is influenced by ideas like Domain Driven Design.

Its focus is on minimizing the hurdles between specification, design, implementation and confirmation of the behaviour of a system. Thus enabling the incremental delivery of business systems, and in particular in allowing teams new to agile development to quickly get up to speed using these extremely productive techniques.


Getting the words right
Behaviour Driven Development (BDD) grew out of a thought experiment based on Neuro Linguistic Programming (NLP) techniques. The idea is that the words you use influence the way you think about something.

As an example, when I was first getting to grips with TDD, I was pairing with an experienced agile coach, writing little test methods, then writing the code, and generally feeling good about life. Then I went ahead and wrote some code without a test. The coach, JR, asked me why I'd written the code. I answered: "we'll need it in a minute", to which JR replied "yes, we might". By using the word "might", he introduced the possibility that we might not. As it turned out, we didn't. - DanNorth

A coach introducing Test Driven Development (TDD) to sceptical (i.e. most) developers invariably runs into a familiar set of objections.

From programmers:
  • Why do I need to write tests? That's what testers do.
  • Writing all these tests slows me down, it's a waste of time.
  • I'm a good programmer! I don't need to write tests to prove my code works
And from testers:
  • Why are you getting programmers to write tests? We all know they can't – that's why you need testers.
  • Are you trying to take our jobs away?
  • You obviously don't understand testing or you wouldn't be asking programmers to write tests!
This last comment is particularly ironic. In fact, the testers take on a central and very important role in BDD.

The behaviour-centric vocabulary helps us to avoid these common misunderstandings and focus on BDD as a design and delivery process.

Concentrating on finding the right words led us to think about the process differently, for example, the fact that the words we use in BDD are very much focussed on the behaviour of the system led us to better understand the very close relationship between the stories we use to specify behaviour and the specifications we implement in BDD in place of tests. It also helped us gain further insight into some of the failure modes we have experienced in TDD projects. 

The BDD Process Model

A SubjectMatterExpert (typically a business user) works with a BusinessAnalyst to identify a business requirement. This is expressed as a story using the following template:

       As a Role
       I request a Feature
       To gain a Benefit
The speaker, who holds the Role, is the person who will gain the Benefit from the requested Feature.

This can also be paraphrased variously as ...

1. I want to achieve a specific Goal, and as a Role I should be able to accomplish this by performing Functionality.

2. A Role invokes Feature to cause a Benefit


BDD Example with Groovy

Easyb is a behavior driven development framework for the Java platform. By using a specification based Domain Specific Language, easyb aims to enable executable, yet readable documentation.


Example Stories with easyb








Example Specification with easyb



BDD On Java using JBehave

JBehave is a framework for Behaviour-Driven Development Behaviour-driven development (BDD) is an evolution of test-driven development (TDD) and acceptance-test driven design, and is intended to make these practices more accessible and intuitive to newcomers and experts alike.

It shifts the vocabulary from being test-based to behaviour-based, and positions itself as a design philosophy.

and here is another example with java using JBehave.



Source:
BDD - http://behaviour-driven.org/
Easyb - http://easyb.org/
JBehave -http://jbehave.org/

Monday, March 8, 2010

Challenges of Scaling Agile in Enterprises

When it comes to scaling agile to the enterprise, there are two classes of challenges that must be addressed. The first- the challenges inherent in agile itself – present limits of technology because of the fixed rule bases and assumptions built into the methods.

The second – those imposed by the enterprise – are impediments that likely exist within the enterprise that will otherwise prevent the successful application of the new methods. Both types of challenges must be successfully addressed in order for the enterprise to achieve the full benefits of agile.

Here is brief introduction some of the issues which should be consider for scaling agile in enterprise.

Small Team size
XP and Scrum recommend teams of 8 or fewer people including product owner/managers or other customer proxy, developers and testers. In many cases, teams decide that even that number is too large, and they may subdivide into components or feature team of three to five people. To an enterprise with 1000 practitioners to deploy, thinking in terms of managing literally hundreds of teams boggles the mind, and there arises the need to understand how to fit this new model into the existing organizational hierarchy.


Customer is Integral to Team
XP Success in particular in a number of IT like environments where the customer was literally down the hall the business analyst who worked with that department was willing and able to participate in the fine grained, detailed review that stories and customer written acceptance tests require.

for many enterprises however, this is not the case, the customer maybe be remote or may not have the skills or time available to participate in such a manner. Or perhaps the enterprise is a large ISV where the application has tens of thousand of users and where there is no single customer to satisfy. Every customer is different, and the larger ones speak loudly indeed, and the information flow is attenuated through many groups before it reaches the team.


Collocation
Much of the productivity of agile comes from the paring contexts, daily stand up, visual signaling of stories and status, and constant informal communication that characterizes these methods. Developers, product owners, and testers are together, not separated by time zones and language barriers.

At scale, collocation is impractical even for large teams in the same building and other mechanisms must be devised. Moreover it is likely that many team members are in different countries and different time zones and perhaps even speak different languages.


Architecture Emerges
Agile and more specifically, XP trades off the ability to refactor code quickly with the cost and investment necessary to create a more forward looking architecture, some architectural runway, that coordinate the efforts of distributed teams.

With the large scale systems however, the refactor cost curve may not be the case, because hundreds of person years may be necessary to get even a first release deployed. Since agile generally does not coach how to approach architecting larger scale systems, that apparent limitation is often a real impediment for agile adoption.


Lack of requirements analysis and documented Specifications
Agile practice of working on a few stories at a time is a wonderfully focusing mechanism for the team. But in larger system, what drive these stories into existence? Who says these stories are the right stories? Will the summation of all these stories actually meet our customer needs?


Culture and Physical Environment
Effective agile environments look and sound different. Most team members work in an open or nearly open environment and often their manager and supervisors have left their offices and joined the team at those tables. Also the process does not look very efficient because there is a certain informality to stories posted on walls, whiteboards shoved hither and you, and teams of people seeming to do far more talking than coding.


Existing Formalized Policies and Procedures
As organization grow, they tend to put in infrastructure to control and measure project, program, human resource and other assets, these include all of the procedure, policies that organization use. And this is part of organization culture and knowledge base which is gained in past project.


Management Style – Fixed Schedule, Fixed functionality Mandates
If a mandate comes to team to deliver functionality X in period of Y with resources Z, then by definition it does not meet agile fixed time, variable scope mantra. And the teams will be discouraged right out of the starting gate.

This mode of management is routine in our industry and most likely, this imprediment will have to be addressed head on. It’s true that the teams would like to be able to predict exactly when they can deliver what functionality, but they know they can not, and it seems inherently silly to them when management just says, “Make it be so”.


People Organized by Discipline rather than Product line
The word Organization in itself can be a root cause of impediments to agile, for the enterprise is surely organized in some fashion already, and most likely it is organized along functional (product management, architecture, developers) rather than product or business application lines. In agile, teams quickly reorganize to assure they have a full complement of the resources necessary to define/build/test and deliver a component of feature.

This require dedicated (not heavy multiplexed) resources for the project, or else the team will fail to meet its commitment to the iteration. Reorganization typically requires redefinition of what makes a team a team in the enterprise.


High Degree of Distribution
The enterprise is an enterprise because it has grown with its successes. For most enterprises, success often involves acquisitions of teams or product lines or existing IT organization along the way. Rarely are these teams collocated and the large the enterprise, the less likely they are to be together in one place.

Moreover, raw size alone prevents pure collocation because there is no way physically to collocation even 100 people in one workspace, so the problem of distributed teams is endemic to agile at scale.


Source: Scaling Software Agility Best Practices for Large Enterprises by Dean Leffingwell

Saturday, March 6, 2010

J2EE 6 - Bean Validation

Validating data is a common task that occurs throughout an application. For example, in the presentation layer of an application, you might want to validate that the number of characters a user enters in a text field is at most 20 characters or that the number a user enters in a numeric field is positive. If you set those constraints, you probably want the same data to be validated before it's used in the business logic of the application and when the data is stored in a database.

Developers often code the same validation logic in multiple layers of an application, something that's time consuming and error-prone. Or they put the validation logic in their data model, cluttering it with what is essentially metadata.

Bean Validation, JSR 303 makes validation simpler and reduces the duplication, errors, and clutter that characterizes the way validation is often handled in enterprise applications. Bean Validation affords a standard framework for validation, in which the same set of validations can be shared by all the layers of an application.

Specifically, Bean Validation offers a framework for validating Java classes written according to JavaBeans conventions. You use annotations to specify constraints on a JavaBean — you can annotate a JavaBean class, field, or property.


You can also extend or override these constraints through XML descriptors. A validator class then validates each constraint. You specify which validator class to use for a given type of constraint.

Here, for example, is part of a class that declares some constraints through Bean Validation annotations:



The @NotNull annotation specifies that the annotated element, addressline1, must not be null. The @Size annotation specifies that the annotated elements, addressline1 and addressline2, must not be longer than the specified maximum, 30 characters.
When an Address object is validated, the addressline1 value is passed to a validator class that is defined for the @NotNull constraint as well as to a validator class defined for the @Size constraint. The addressline2 value is also passed to the validator class for the @Size constraint. The pertinent validator classes perform the validations.

Both the @NotNull and @Size constraints are built into the Bean Validation framework so you do not need to define validator classes for them. However, you can add your own constraints to the built-in constraints, in which case, you need to define validator classes. For example, you can define a constraint named @ZipCode as follows:



Then you can specify the @ZipCode constraint on a class, field, or property just like any other constraint. Here is an example:



When an Address object is validated, the zipCode value is passed to the ZipcodeValidator class for validation. Notice that the constraint definition includes another constraint: @Size(min=5, max=5).

This means that an element annotated by the @ZipCode annotation must be exactly 5 characters in length. The element is validated against this constraint in addition to the primary constraint check that ZipcodeValidator performs.

Bean Validation allows you to create a constraint that is composed of other constraints. In fact, any composing constraint can itself be composed of constraints. Notice too that the constraint definition specifies an error message to be returned if the constraint fails the validation check. Here, the error message is "Wrong zipcode".


You can also use Bean Validation to validate an entire object graph in a straightforward way. An object graph is an object composed of other objects. If you specify the @Valid annotation on the root object of an object graph, it directs the pertinent validator to recursively validate the associated objects in the object graph. Consider the following example:



When an Order object is validated, the Address object and the associated objects in its object graph are validated too.

To meet the objective of sharing the same set of validations across all the layers of an application, Bean Validation is integrated across the Java EE 6 platform.

For example, presentation-layer technologies such as JSF and enterprise-layer technologies such as JPA have access to the constraint definitions and validators available through the Bean Validation framework. You no longer need to specify constraints in multiple places and in multiple ways across the layers of an application.


Source: java.sun.com - J2EE 6 Overview

J2EE 6 - Contexts and Dependency Injection

Contexts and Dependency Injection for the Java EE Platform (CDI), JSR 299 is a technology that supplies a powerful set of services to Java EE components. These services allow Java EE components, including EJB session beans and JavaServer Faces (JSF) managed beans, to be bound to lifecycle contexts, to be injected, and to interact in a loosely coupled way by firing and observing events. Perhaps most significantly, CDI unifies and simplifies the EJB and JSF programming models. It allows enterprise beans to replace JSF managed beans in a JSF application.
In essence, CDI helps bridge what was a major gap between the web tier of the Java EE platform and the enterprise tier. The enterprise tier, through technologies such as EJB and JPA, has strong support for transactional resources.

For example, using EJB and JPA you can easily build an application that interacts with a database, commits or rolls back transactions on the data, and persists the data. The web tier, by comparison, is focused on presentation. Web tier technologies such as JSF and JavaServer Pages (JSP pages) render the user interface and display its content, but have no integrated facilities for handling transactional resources.

Through its services, CDI brings transactional support to the web tier. This can make it a lot easier to access transactional resources in web applications. For example, CDI makes it a lot easier to build a Java EE web application that accesses a database with persistence provided by JPA.

Let's look at some key parts of a web application that uses CDI services. The application, which processes user login and user logout requests, includes both JSF and EJB components. Here is the code for an input form on a JSF page that displays a login prompt for the web application:



As you can see from the code, the login prompt displays fields for a user to enter a user name and password. It also displays a Login button and a Logout button. Notice the unified expression language (EL) expressions such as #{credentials.username} and #{login.login}. These expressions refer to beans, named credentials and login.

Note that CDI builds on a new concept introduced in Java EE 6 called managed beans, which is designed to unify all of the various types of beans in Java EE 6. A managed bean is a Java class that is treated as a managed component by the Java EE container. Optionally, you can give it a name in the same namespace as that used by EJB components.

A managed bean can also rely on a small number of container-provided services, mostly related to lifecycle management and resource injection. Other Java EE technologies such as JSF, EJB, and CDI build on this basic definition of a managed bean by adding services. So for example, a JSF managed bean adds lifecycle scopes, an EJB session bean adds services such as support for transactions, and CDI adds services such as dependency injection. In CDI a managed bean or simply a bean is a Java EE component that can be injected into other components, associated with a context, or reached through EL expressions.

You declare a managed bean by annotating its class with the javax.annotation.ManagedBean annotation or by using one of several CDI annotations such as a scope annotation or a qualifier annotation. The annotation-based programming model makes it possible for a bean to begin as a POJO and later become another type of Java EE component such as an EJB component — perhaps to take advantage of more advanced functionality, such as transactional and security annotations or the instance pooling facility offered by EJB containers.


For example, you can turn a POJO into a stateful session bean by adding a @Stateful annotation to the object. Clients that use CDI to access a bean are unaffected by the bean's transition from POJO to EJB.

Any bean can be bound to a lifecycle context, can be injected, and can interact with other beans in a loosely coupled way by firing and observing events. In addition, a bean may be called directly from Java code, or as in this example, it may be invoked in a unified EL expression. This enables a JSF page to directly access a bean, even a bean that is implemented as an EJB component such as a session bean.

In this application, a bean named Credentials has a lifecycle that is bound to the JSF request. The Credentials bean is implemented as a JavaBean as follows:



To request CDI services, you annotate a Java EE component with CDI annotations. The @Model annotation is a CDI annotation that identifies the Credentials bean as a model object in an Model-View-Controller (MVC) architecture. The annotation, which is built into CDI, is a stereotype annotation. A stereotype annotation marks a class as fulfilling a specific role within the application.

The application also includes a Login bean whose lifecycle is bound to the HTTP session. The Login bean is implemented as an EJB stateful session bean, as follows:





The @Stateful annotation is an EJB annotation that specifies that this bean is an EJB stateful session bean. The @TransactionAttribute and @RolesAllowed annotations are also EJB annotations. They declare the EJB transaction demarcation and security attributes of the annotated methods.


The @SessionScoped annotation is a CDI annotation that specifies a scope for the bean. All beans have a scope that determines the lifecycle of its instances and the instances of the bean that are made visible to instances of other beans. This is an important feature because components such as EJB components do not have a well-defined scope.

In particular, EJB components are not aware of the request, session, and application contexts of web tier components such as JSF managed beans, and do not have access to the state associated with those contexts. In addition, the lifecycle of a stateful EJB component cannot be scoped to a web-tier context.

By contrast, scoped objects in CDI exist in a well-defined lifecycle context that is managed by the Java EE container. Scoped objects may be automatically created when needed and then automatically destroyed when the context in which they were created ends.

Significantly, the state of a scoped object is automatically shared by clients that execute in the same context. This means that clients such as other beans that execute in the same context as a scoped object see the same instance of the object. But clients in a different context see a different instance.

The @SessionScoped annotation specifies that the scope type for the Login bean is session scope. Objects that are not associated with any of the usual scopes, but instead exist for the exclusive benefit of an object that triggered their creation, are said to be dependents of their owner. The lifecycle of these dependent objects is tied to that of the owner. In particular, a dependent object is destroyed whenever the owner is destroyed.


Beans typically acquire references to other beans through dependency injection. The dependency injection mechanism is completely type safe. CDI uses the annotations specified in JSR 330: Dependency Injection for Java for dependency injection.

One of those annotations, @Inject, identifies a point at which a dependency on a Java class or interface can be injected. The container then provides the needed resource. In this example, the Login bean specifies two injection points. The first use of the @Inject annotation in the example injects a dependency on the Credentials bean.

In response, the container will inject the Credentials bean into any instance of Login created within this context. The second @Inject annotation injects a dependency on the JPA EntityManager. The container will inject the EntityManager to manage the persistence context.
The @Produces annotation identifies the getCurrentUser() method as a producer method. A producer method is called whenever another bean in the system needs an injected object of the specified type. In this case, the injected object is the currently logged-in user, which is injected by the qualifier annotation @LoggedIn.

A qualifier identifies a specific implementation of a Java class or interface to be injected. In order to use a qualifier annotation, you first need to define its type as a qualifier. You use the @Qualifier annotation, another JSR 330 annotation, to do that. For example:



Let's return to the login prompt discussed earlier. When a user responds to the prompt and clicks the Submit button, CDI technology goes into action.

The Java EE container automatically instantiates a contextual instance of the Credentials bean and the Login bean. An instance of a bean that is bound to a context is called a contextual instance. JSF assigns the user name and password the user entered to the Credentials bean contextual instance. Next, JSF calls the login() method in the Login bean contextual instance.

This instance continues to exist for and is available to other requests in the same HTTP session, and provides the User object that represents the current user to any other bean that requires it.

This example demonstrates only some of the features in this powerful technology. Another feature enables beans to produce or consume events. Yet another lets you define interceptors that bind additional function across all bean types, or define decorators that apply the additional function to a specific bean type.


Source: java.sun.com - J2EE 6 Overview

Friday, March 5, 2010

J2EE 6 - Java API for RESTful Web Services (JAX-RS)

Java API for RESTful Web Services (JAX-RS), JSR 311 enables you to rapidly build lightweight web services that conform to the Representational State Transfer (REST) style of software architecture. An important concept in REST is the existence of resources, each of which can be referred to with a global identifier, that is, a URI. In particular, data and functionality are considered resources that can be identified and accessed through URIs. To manipulate these resources, components of the network, clients and servers, communicate through a standardized interface such as HTTP and a small, fixed set of verbs — GET, PUT, POST, and DELETE — and exchange representations of these resources.
RESTful web services are web services built according to the REST architectural style. Building web services with the RESTful approach has emerged as a popular alternative to using SOAP-based technologies thanks to REST's lightweight nature and the ability to transmit data directly over HTTP.

JAX-RS furnishes a standardized API for building RESTful web services in Java. The API contributes a set of annotations and associated classes and interfaces. Applying the annotations to POJOs enables you to expose web resources. This approach makes it simple to create RESTful web services in Java.
The specification for the initial release of the technology, JAX-RS 1.0, was finalized in October 2008 and a reference implementation named Jersey is also available. Java EE 6 includes the latest release of the technology, JAX-RS 1.1, which is a maintenance release that aligns JAX-RS with new features in Java EE 6. Let's take a look at a RESTful web service that uses JAX-RS.



In this example, the ItemsResource class is a web service that manages a set of items. The imports in the class are for JAX-RS 1.1 annotations, classes, and interfaces.

The @Path annotation specifies a relative path for the resource, in this case "items". The URI for the class resource is based on the application context. So if the application context for this example is http://example.com, the URI for the class resource is http://example.com/items.

This means that if a client directs a request to the URI http://example.com/items, the ItemsResource class will serve it. The @GET annotation specifies that the annotated method, here the listItems() method, handles HTTP GET requests. When a client directs an HTTP GET request to the URI for the ItemsResource resource, the JAX-RS runtime invokes the listItems() method to handle the GET request.

Notice the @Produces annotation. It specifies the MIME media types that the methods in the resource can produce and return to the client. In the ItemsResource example, the @Produces annotation specifies MediaType.APPLICATION_XML. The MediaType class is an abstraction of a MIME media type. Constants supplied to the class identify the particular media type to be abstracted. The MediaType.APPLICATION_XML specification is an abstraction of the MIME media type for XML content, "application/xml".


Annotations such as @Produces suggest some of the content type translation that JAX-RS handles automatically. For example, the listItems() method returns a Java object of type Items. JAX-RS automatically translates that Java type to the "application/xml" MIME type to be used in the HTTP response to the client. Note that the translation is automatic only if the returned type is supported by default.

For instance, if Items is a JAXB-annotated bean, then the translation would be automatic. However, if Items is a POJO, you would need to implement a MessageBodyReader to handle the serialization. You can also specify a @Produces annotation on a method. In that case, the MIME type you specify on the method overrides the MIME types in any @Produces annotation that you specify on the class. For example, you could specify a @Produces annotation for the listItems() method as follows:



JAX-RS would then translate the Items Java type to the "text/plain" MIME type, which represents plain text, and return content of that type in the HTTP response to the client.
The @POST annotation specifies that the annotated method, in this case, the create() method, responds to HTTP POST requests. In this example, the method creates a new item, perhaps in a database, and then returns a response indicating that it created the new item. When a client directs an = HTTP POST request to the URI for the ItemsResource resource, the JAX-RS runtime = invokes the create() method to handle the POST request.
Notice that the @Consumes annotation is specified on the create() method. The annotation specifies the MIME media types that the methods in the resource can accept from the client. As is the case for the @Produces annotation, if you specify @Consumes on a class, it applies to all the methods in the class. If you specify @Consumes on a method, it overrides the MIME type in any @Consumes annotation that you specify for the class.

In the example, the @Consumes annotation specifies that the create() method can accept XML content, that is, the MIME type "application/xml". Here the type translation is from MIME type to Java type. When a client submits XML content in a POST request to the URI for the ItemsResource class, JAX-RS invokes the create() method and automatically translates the incoming XML to the Item Java type required for the method's argument.

JAX-RS also includes a number of utility classes and interfaces that further simplify actions related to building and using RESTful web services in Java. You've already seen one of them: MediaType, a class for abstracting MIME media types. Some others are:
  • UriInfo, an interface for accessing URI information. In this example, the @Context annotation injects the UriInfo interface into the uriInfo field of the ItemsResource class.
  • UriBuilder, a class for building URIs from their components
  • Response, a class represents an HTTP response
  • Response.ResponseBuilder, a class that builds Response objects, in accordance with the well-known Builder Pattern
These classes and interfaces are used in the following statements in the example:



The first statement builds a URI for the new item. The getRequestUriBuilder() method is a UriInfo method that creates a UriBuilder object. The path()  and build() methods are UriBuilder methods that together construct the URI for the new item.
The second statement creates a Response object for the new item to be returned to the client. The created method is a Response method that creates a Response.ResponseBuilder object. The build() method is a Response.ResponseBuilder method that creates the Response object for the new item. This object delivers metadata to the JAX-RS runtime to construct the HTTP response.


These utility classes and interfaces hide a lot of the complexity of HTTP programming — another reason why using JAX-RS is a simple way to build RESTful web services. However, this simplicity also extends beyond web services. JAX-RS can simplify the development of many types of HTTP-aware web applications. For example, if you need to build a web application that examines HTTP headers, you can probably code it in a much simpler way by using JAX-RS rather than other approaches.

JAX-RS has other convenient features. For example, JAX-RS includes a number of parameter-based annotations to extract information from a request. One of these is @QueryParam, with which you can extract query parameters from the Query component of a request URL. Some other parameter-based annotations are @MatrixParam, which extracts information from URL path segments,@HeaderParam, which extracts information from HTTP headers, and  @CookieParam which extracts information from the cookies declared in cookie related HTTP headers.


Source: java.sun.com - J2EE 6 Overview

Introduction to Database Marketing

The purpose of marketing is to enable the firm to enhance customer value. In today’s competitive, information-intensive, ROI-oriented business environment, database marketing has emerged as an invaluable approach for achieving this purpose. The applications of database marketing are numerous and growing exponentially. Here are a few examples:

• “Internet Portal, Inc.” determines which of its customers will be most receptive to targeted efforts to increase their usage of the portal. Perhaps more importantly, it determines which customers will not be receptive to these efforts.

• “XYZ Bank” decides which of its many financial products should be marketed to which of its current customers.

• “ABC Wireless” develops the ability to predict which customers are most likely to leave when their contract runs out, and designs a “churn management program” to encourage them to stay.

• UK Retailer Tesco develops thousands of customized promotion packages it mails to its 14 million customers (Rohwedder 2006).

• Best Buy has identified the major segments of customers who visit its stores. It then (1) tailors its store in a particular locality to fit the representation of the segments in that locality, and (2) trains its store personnel to recognize which segment a particular customer belongs to, so the customer can be serviced appropriately (Boyle 2006).
• Catalogers routinely use “predictive models” to decide which customers should receive which catalogs.

• “E-tailer Z” uses “recommendation engines” to customize which products it “cross-sells” to which customers.

• Dell Computer uses data analyses of prospects to improve its customer acquisition rate (Direct Marketing Association 2006). 

These are but a few examples of database marketing in action. The common theme is that all of them are based on analyzing customer data and implementing the results.

Database marketing is the use of customer databases to enhance marketing productivity through more effective acquisition, retention, and development of customers.

Each phrase in this definition is carefully chosen. First, database marketing is fundamentally about using of customer databases. The “customer” can be either current customers or potential customers. Firms have data on their current customers’ purchase behavior and demographic and psychographic information, as well as the firm’s previous marketing efforts extended to these customers and their response to them.

For potential customers prospects firms may be able to obtain data on customer demographics and psychographics, as well as purchase history data, although obviously not in the same depth as available for their current customers.

Second, database marketing is about marketing productivity. In today’s results-oriented businesses, senior management often asks the simple question, “Do our marketing efforts pay off?” Database marketing attempts to quantify that effectiveness and improve it. It does this through effective targeting.

The retail pioneer John Wannamaker is credited with saying, “I know half of my advertising doesn’t work; I just don’t know which half.” Thinking more broadly, in terms of marketing rather than advertising, database marketing identifies which half of the firm’s marketing efforts is wasted. It does this by learning which customers respond to marketing and which ones do not. The responsive customers are the ones who are then targeted.

Third, database marketing is about managing customers. Customers must be acquired, retained, and developed. Acquiring customers means getting an individual who currently does not do business with the company to start doing business with the company. Retention means ensuring the current customer keeps doing business with the company. Development means enhancing the volume of business the retained customer does with the company.

For now, the important point is to recognize that database marketing is concerned with all three elements of customer equity. The Dell example above involves customer acquisition. The ABC Telecom example involves customer retention. The XYZ Bank, Tesco, and E-tailer Z examples involve customer development.

Why Is Database Marketing BecomingMore Important?

The indications are that the database marketing industry is huge and increasing. The question is, why? We hypothesize five major classes of reasons:

Information technology: Companies now have the ability to store and manipulate terabytes of data. While the software to do so is expensive, the capabilities are dramatic.

Growth of the Internet: The Internet is a data-collection “machine.” Many companies that previously could not collect and organize data on their customers can now do so through the Internet.

Lower productivity of mass marketing: While there are no good statistics on this, there is the belief that mass advertising and non-customized marketing efforts are eliciting poorer response, while costs are increasing and margins are declining.

One can write the profitability of a marketing campaign as Π = Npm−Nc, where N is the number of customers reached by the campaign, p is the percentage that respond, m is the contribution margin when they respond, and c is the cost of contact per customer. For a campaign to be profitability, we need p > c/m. Unfortunately, all three of these terms are moving in the wrong direction. Response is lower (p), costs are higher (c), and margins are lower (m). Database marketing targets customers for whom response is maximal, helping the profit equation to remain in the black.

Marketing accountability: Results-oriented senior managers are requiring all business functions to justify their existence, including marketing. No longer is it taken on faith that “marketing works” or “marketing is a cost of doing business.” The demands of senior managers for proven results feed directly into database marketing’s emphasis on analyzing data and measuring results.

Increasing interest in customer relationships: Companies are more concerned than ever about their relationship with the customer. They see their products commoditizing and customer loyalty wilting away. Database marketing is a systematic way to improve customer relationships.

Establishing a competitive advantage: Companies are always trying to determine what will be their source of competitive advantage. Perhaps that source lies in the data they have on their own customers, which allows them to service those customers better through database marketing.


Source: Database Marketing Analyzing and Managing Customers - Springer