Showing posts with label backend. Show all posts
Showing posts with label backend. Show all posts

14 Feb 2014

Developing a Soap Service Using Apache Cxf and Jaxb annotations

  •  Advance:
In a passed post, you saw how to developan application using the “MethodTemplate” Design Pattern. Now we’re going to develop a Service tier for this Business tier developed in the past.
In this post, you can find a running application to see how the Service works, using a SOAP implementation built with the Apache cxf library and Jaxb Annotations

Rev: 6.

Also I would like to say, you can deploy this Service in an Application Server (I have selected Tomcat 7.0) and use SoapUI to send request to the Server (I have included a SoapUI Project in the SVN for that purpose)

  •  Explanation
We want to develop a Service Tier for an Existing Business Tier, but we want to reutilize all the code previously developed, also I don’t want to import the code as a jar or as an external Java Project downloaded in the workspace. For that purpose, we have published the Business Tier in the Maven Central Repository. Now you can download the project as a Maven Dependency and use it.

For the checkout of the code, you should know this example was developed as a Maven Project, under 1.7 JDK and Spring 3.0.

For this example I have selected Apache cxf because with a little set of Annotations you could develop a Service as follows

o API Tier
Object
Description
ManageVehicleRequest
This object, represent a request to consume the “manageVehicle” operation existing in the Vehicle Service.
ManageVehicleResponse
This object, represent a response from the Service Vehicle after the “manageVehicle” operation has been finished
VehicleService
The definition of our Service including all the operations we want to publish in our SOAP Architechture. In this case, we only have one operation (manageVehicle)

o SERVICE Tier
Object
Description
VehicleServiceImpl
This is only the implementation of our Service.

o CODE snapshots
VehicleService
@WebService(name = "VehicleService")
public interface VehicleService {

 @WebMethod
 String getVersion();

 @WebMethod
 ManageVehicleResponse manageVehicle(ManageVehicleRequest request);

}

As you can see, we only have to use two annotations, the first one, is only to declare our Interface as a Service (with a concrete name). The second annotation is used to indicate what methods must be published within the Service


ManageVehicleRequest
@XmlType(name = "ManageVehicleRequest")
@XmlSeeAlso({ EngineVehicleDTO.class, AnimalVehicleDTO.class })
public class ManageVehicleRequest implements Serializable {

 /**
  * 
  */
 private static final long serialVersionUID = 1144868850362615114L;

 private VehicleDTO vehicle;

 /**
  * @return the vehicle
  */
 public VehicleDTO getVehicle() {
  return vehicle;
 }

 /**
  * @param vehicle
  *            the vehicle to set
  */
 public void setVehicle(VehicleDTO vehicle) {
  this.vehicle = vehicle;
 }

}

This object will be used to pass the information from the outside to the Service. In this case we should include inside this object a VehicleDTO instance.

It’s considered as a good practice to use the @XmlType annotation to give a name to our object. If you don’t follow this tip, you are delegating in the framework the names for all the XML elements within of the namespace used by the Service. And maybe you would have errors at deployment time.

As you can see, VehicleDTO is a parent object of EngineVehicleDTO and AnimalVehicleDTO, our operation has to work with these child objects, this is the purpose followed by the @XmlSeeAlso annotation. This annotation says to the framework that at deployment time, these objects must be part of the WSDL. If you don’t use that annotation, you only could send instances from VehicleDTO.



ManageVehicleResponse
package gazpachito.examples.services.cxf.vehicle.api.response;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlType;

@XmlType(name = "ManageVehicleResponse")
public class ManageVehicleResponse implements Serializable {

 /**
  * 
  */
 private static final long serialVersionUID = -7879894326252286663L;

 private String errorMessage;

 /**
  * @return the errorMessage
  */
 public String getErrorMessage() {
  return errorMessage;
 }

 /**
  * @param errorMessage
  *            the errorMessage to set
  */
 public void setErrorMessage(String errorMessage) {
  this.errorMessage = errorMessage;
 }

}


This object will be used to return the information from the Service to the outside. In this case
we only just want to pass an error message, but in fact, we could return whatever you want, collections or a complex object maybe (with the exception of Maps)



VehicleServiceImpl
public class VehicleServiceImpl implements VehicleService {

 @Autowired
 private VehicleFacade vehicleFacadeImpl;

 @Override
 public String getVersion() {

  String version = ResourceBundle.getBundle("vehicle").getString(
    "vehicle.version");
  return version;
 }

 @Override
 public ManageVehicleResponse manageVehicle(ManageVehicleRequest request) {
  ManageVehicleResponse response = new ManageVehicleResponse();

  if (request != null && request.getVehicle() != null) {

   VehicleEnum template = null;

   if (request.getVehicle() instanceof AnimalVehicleDTO) {
    template = VehicleEnum.ANIMAL;
   } else if (request.getVehicle() instanceof EngineVehicleDTO) {
    template = VehicleEnum.ENGINE;
   }

   try {
    this.vehicleFacadeImpl.manageVehicle(request.getVehicle(),
      template);
   } catch (FacadeException e) {

    response.setErrorMessage(e.getMessage());
   }
  }
  return response;
 }

This is the implementation of our service. As you can see, I only have  used a Spring annotation to inject the facade developed in other post. And we only need to make an implementation for the two operations publisheds in the Interface VehicleService.

About the “getVersion” method, just return the version extracted from a properties file (using the ${project} variable inside this properties file). The “manageVehicle” method only validate the input from the outside before this information sent to Facade


  •    Conclusions

As you can see, using a little set of JAXB annotations, we can develop a WebService based in a SOAP Architecture. In this post I only have introduced enough annotations to show you how to develop a Service in an easy way, but you can use more JAXB annotations and different combinations between them to go further.

But this framework has a weakness. You have to write a little of XML in a configuration file to define the endpoint of all your Services (at least in the version chosen for this example). So you can’t forgive the configuration files and the configuration of the endpoint sometimes is a hard task.

18 Jan 2014

(Design Patterns) Method Template Example in Backend Side


  •  Advance:

I assume I don’t need to tell you what a Design Pattern is and how it works. I suppose if you’re reading this post it’s because you have knowledge about the commons Design Patterns (MVC or DAO for example).

Inside the set of Behaviour Patterns, we can find the “Method Template” Pattern (in Wikipedia we can find a good explanation about this Pattern, what is the main objective of the Pattern and how is the strategy that this Pattern follows)


But if you don’t want to read it I’ll resume to you. This pattern starts from an abstract idea but with the knowledge about how many steps an algorithm must follow. Starting from this abstract idea, you can develop your code in all the concrete levels as you need to develop your application.

Talking about code, the strongest point of this Pattern is the reusability when you know your application must follow the same steps for all your entities with little differences. It’s usual to use this pattern in addition with the FactoryPattern or the Service Locator Pattern (about Service Locator Pattern, a lot of people don’t consider it as a Pattern and they prefer talk about it as a AntiPattern  we should discuss about this in another post)

In this post you can find a running application just for seeing how the application works under this design pattern. You can check the code in this revision of the next SVN address:

Rev: 4

  • Explanation

My code talks about a Service, and this Service uses  a Facade for the management of Vehicles (only two kinds of vehicles because I only used two abstractions levels for my example). The Service is not implemented yet but just launching the Tests inside the application, you will see an example of this pattern, also you will understand how it works and the benefits this idea could give you in your future applications.

For the checkout of the code, you should know this example was developed as a MavenProject, under the 1.7 JDK using Spring 3 annotations.

About the application, the main idea is a Facade using a ServiceLocator to get an instance of an Interface. This interface is implemented by an Abstract Business class which defines the main steps of the algorithm to validate and to execute a vehicle. But at the end of these methods the Abstract Class calls to an abstract method named “methodConcrete”.

You can find two concrete implementations of the Abstract class; in this Concrete class (one for Engine Vehicles and another one for Animal Vehicles) you just can see we only have to develop the abstract “methodConcrete” defined in the Parent Class.

My code was built so fast so you can see the database is simulated by a HashMap and I use a Service Locator as a Factory. But this is just the beginning, in future post I will include improvements as a clean Spring FactoryBean and an embebed database using JPA annotations.

    • API Tier



Object
Description

TemplateDTO
Data Transfer Object.
This object will be used as a template for all the Data Transfer Objects of my app. Will be used for the definition to make an Interface which use Generics.
VehicleDTO
Data Transfer Object.
This object will be used as a container of all the common attributes to define a Vehicle.
EngineVehicleDTO
Data Transfer Object.
This object will contain the concrete attributes for an engine vehicle.
AnimalVehicleDTO
Data Transfer Object.
This object will contain the concrete attributes for an engine vehicle
VehicleEnum
Enumeration.
This Enumeration will be used to select a template for working. In each label we can find an attribute called “service” used to locate the specific business bean.

    •  SERVICE Tier (Service Implementation not implemented)



Object
Description

VehicleFacade
Facade for a non-existing service. This facade uses a Service Locator object to find the concrete business bean to be used.

If any error appears, will throw a FacadeException

    • BUSINESS Tier


Object
Description

TemplateBusiness
BusinessObjectGeneric interface to define a generic API for all the objects which extend from TemplateDTO
AbstractVehicleBusinessImpl
BusinessObjectAbstract class which implement the TemplateBusiness and which define the main steps of the two operations, “validate” and “execute”.
EngineVehicleBusinessImpl
BusinessObjectConcrete Business class to define the concrete steps for the validation and execution of a Engine type vehicle
AnimalVehicleBusinessImpl
BusinessObjectConcrete Business class to define the concrete steps for the validation and execution of a Animal type vehicle

    • Code snapshots


VehicleFacadeImpl

@Override  
      public void manageVehicle(VehicleDTO vehicle, VehicleEnum template)  
                throws FacadeException {  
           if (template == null) {  
                throw new FacadeException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_TEMPLATE_NOT_INFORMED));  
           }  
           @SuppressWarnings("unchecked")  
           TemplateBusiness<TemplateDTO> templateBusiness = this.templateServiceLocator  
                     .getTemplate(template.getService());  
           try {  
                templateBusiness.validate(vehicle);  
                templateBusiness.execute(vehicle);  
           } catch (BusinessException b) {  
                throw new FacadeException(  
                          MessageUtils.getMessage(MessageUtils.ERROR_VEHICLE_WRONG),  
                          b);  
           }  
      } 

As you can see, using this pattern we can reutilize code a lot, because we don’t need different methods for each kind of vehicle. Just we can use only one method specifying the template to used.



AbstractVehicleBusinessImpl<T extends VehicleDTO>

 @Override  
      public void validate(VehicleDTO element) throws BusinessException {  
           if (element == null) {  
                throw new BusinessException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_VEHICLE_NOT_INFORMED));  
           }  
           if (StringUtils.isBlank(element.getName())) {  
                throw new BusinessException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_VEHICLE_NAME_ISEMPTY));  
           }  
           if (StringUtils.isBlank(element.getDescription())) {  
                throw new BusinessException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_VEHICLE_DESCRIPTION_ISEMPTY));  
           }  
           try {  
                this.validateConcrete(element);  
           } catch (ClassCastException c) {  
                throw new BusinessException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_ELEMENT_NOT_COMPATIBLE));  
           }  
      }  
      @Override  
      public void execute(VehicleDTO element) throws BusinessException {  
           if (element.getIdVehicle() != null  
                     && storedVehicles.containsKey(element.getIdVehicle())) {  
                throw new BusinessException(  
                          MessageUtils.getMessage(MessageUtils.ERROR_ELEMENT_EXIST));  
           }  
           List<Integer> keysStored = new ArrayList<Integer>(  
                     this.storedVehicles.keySet());  
           Collections.sort(keysStored, new Comparator<Integer>() {  
                @Override  
                public int compare(Integer o1, Integer o2) {  
                     return o1.compareTo(o2);  
                }  
           });  
           element.setIdVehicle(keysStored.get(keysStored.size() - 1) + 1);  
           try {  
                this.executeConcrete(element);  
           } catch (ClassCastException c) {  
                throw new BusinessException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_ELEMENT_NOT_COMPATIBLE));  
           }  
      }  

In this abstract class we’re reutilizing code so much because we validate the common attributes to all the differents kinds of vehicles. When we’re executing the “execute” method, we can see we have the common business logic (validate if an id exists in the system) in this abstract class delegating the concrete business logic (or validations) in all the objects which extend from this abstract class



EngineVehicleBusinessImpl

 @Override  
      public void validateConcrete(VehicleDTO vehicle) throws BusinessException {  
           // TODO Auto-generated method stub  
           EngineVehicleDTO engineVehicle = (EngineVehicleDTO) vehicle;  
           if (engineVehicle.getcV() == null  
                     || engineVehicle.getcV().compareTo(BigDecimal.ZERO) < 0  
                     || engineVehicle.getcV().compareTo(BigDecimal.ZERO) == 0) {  
                throw new BusinessException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_ENGINE_POWER_INCORRECT));  
           }  
      }  
      @Override  
      public void executeConcrete(VehicleDTO vehicle) {  
           EngineVehicleDTO engineVehicle = (EngineVehicleDTO) vehicle;  
           super.getStoredVehicles().put(engineVehicle.getIdVehicle(),  
                     engineVehicle);  
      }  

Here we have all the concrete steps for an Engine vehicle. You can see we only have to put in these methods all the things relative to the management of our concrete DTO (in the case of validation), and in the execute we only need to put steps related to the store of the vehicle in the place defined for it. But really all the logic is defined in a high level abstract template. Reaching this point, maybe we could introduce new abstraction levels following the same idea presented in this example. The JVM at runtime will know what concrete object must be used, because all of them are part of the same object family.



AnimalVehicleBusinessImpl

 @Override  
      public void validateConcrete(VehicleDTO vehicle) throws BusinessException {  
           // TODO Auto-generated method stub  
           AnimalVehicleDTO animal = (AnimalVehicleDTO) vehicle;  
           if (animal.getKindVehicle() == null) {  
                throw new BusinessException(  
                          MessageUtils  
                                    .getMessage(MessageUtils.ERROR_ANIMAL_NOT_INFORMED));  
           }  
      }  
      @Override  
      public void executeConcrete(VehicleDTO vehicle) {  
           AnimalVehicleDTO animal = (AnimalVehicleDTO) vehicle;  
           super.getStoredVehicles().put(animal.getIdVehicle(), animal);  
      }  

Here we have all the concrete steps for an Animal vehicle. You can see we only have to put in these methods all the things relative to the management of our concrete DTO (in the case of validation), and in the execute we only need to put steps related to the store of the vehicle in the place defined for it. But really all the logic is defined in a high level abstract template. Reaching this point, maybe we could introduce new abstraction levels following the same idea presented in this example. The JVM at runtime will know what concrete object must be used, because all of them are part of the same object family.

  • Conclusions

You can get conclusions by your own, the main idea all the benefits of this pattern was explained all around the post. Using this idea you make your code reusable, and you can introduce concrete objects in the application, which start from an abstract idea. That concept of abstraction gives you freedom to model at your interest, but I should advice maybe it’s not a good idea to introduce so many levels.

From my point of view, the weakness of this pattern would be:

  1. Excessive coupling between the concrete elements and the high levels object, because all of them must be part of the same family.
  2. Depending about how many levels you need to introduce in the family, the debug from the top level to the concrete level sometimes is hard to follow (is not easy to debug)
  3. If you introduce a new method in one of the high level objects, you should introduce the expected behaviour in the low levels objects. In other words, the pattern doesn’t have enough scalability.