Thursday, October 10, 2013

Getting started with SOA

An important matter when we are thinking of SOA adoption is to know how to get started. At this stage many questions come to our minds and if we don't have someone with experience to show us the way, could be a big challange to understand the whole concept of SOA and apply it in real life. This article aims to give you a overall guideline showing how you can quickly get started.

The transition to SOA can be addressed in many different ways, it all depends on how mature is your company's IT, as well as the reasons for adopting SOA. A SOA adoption can be thought of as continuum with four broad levels, and each level you reach will bring you better business value.
  1. Implementing individual web services. In this level companies create web services from tasks in existing or new applications.
  2. Service oriented integration of business functions. In this level, companies integrate two or more applications using web services or other service oriented architectures.
  3. Enterprise wide IT transformation. In this level, companies can use SOA as their standard for exposing application functions; companies are able to use SOA to integrate to any application.
  4. On demand business transformation. In this level, companies are able to change their software and partners quickly in order to meet the changing needs of the business.
 Let's now detail each of the previous levels, showing ways of putting them in practice:

Level 1
  • Exposing functions of an existing application as web services.
  • Creating a new application using web services from another application.
  • Creating a new application that contains web services and uses those web services. 
Level 2
  • Analyzing two applications in order to determine what services are needed.
  • Choose SOA infrastructure and tools, creating standards, and so forth
At this level governance is becoming important.

Level 3 and 4 

When starting with enterprise wide IT transformation or on demand business transformation, governance and executive buy-in are critical. Starting at this level is usually part of a strategic transformation of business that involves analyzing the company's current state, the company's strategy, the company's IT systems, the trends in the company's industry, and technology trends.

Transitions that start at these top two levels frequently involve many steps and include steps to verify assumptions and validate decisions made in previous steps. These verifications can include reviews by experts, as well as testable prototypes for measuring quality of service factors such as performance and usability.

That's all folks, hope this article can help you to get started with SOA in your company!

Bye!


Source:
VW003 - Introducing the Value and Governance Model of Service-Oriented Architecture, IBM Corporation, 2007.


Friday, September 27, 2013

JAX-RS 2.0 Client API Generic Type Response Entity

Hi folks!

The last POST we learned how to use the new JAX-RS 2.0 Jersey API, you can read the introduction there. Today we will talk about the detail that was missing for reading JSON responses that uses a generic type.

The code below shows how to setup the WebTarget with the URI you want to request and then it is executed when you call the get() method. Note that this is not different from the first example.
 
Client orderClient = ClientBuilder.newClient();

WebTarget target = orderClient.target("http://localhost:8082/rest-client-api-example/resources/orders");
Response response = target
.request(MediaType.APPLICATION_JSON)
.get();
So, now we will see what really makes the difference using generics. The following line shows how a generic type should be read.

 List<order> orders = response.readEntity(new GenericType<List<Order>>() {});

It doesn't look good, but this anonymous class will do the trick. Remember that you need all the dependencies listed at my github to make this work properly.

This is it, I hope it helped!

Thursday, August 29, 2013

REST JAX-RS 2.0 Jersey Client API

Hello, everyone!

This post will show an example of how can you use the new JAX-RS 2.0 Client API from Jersey.

For this project we will use JBOSS AS 7.1 (Port 8082) with Maven and our plan is to consume a REST service asking for an "Order" passing an id as a parameter.

So let's get started!

This first line of code will give you a new instance of the client.
Client orderClient = ClientBuilder.newClient();

The next step is to make a GET request to a WebTarget (A resource target identified by the resource URI) asking for the "Order".
         WebTarget target  = orderClient
                                .target("http://localhost:8082/rest-client-api-example/resources/orders/{id}");
         Response response = target
                                .resolveTemplate("id", 1) // Resolves the {id} template
                                .request(MediaType.APPLICATION_JSON)
                                .get();
Note that you also could use another http method like post(), put() or any other you choose. After that you just have to check if the response is OK (Status code 200) and read the entity, if you are trying to read a List<Order> it will be a bit tricky  and I will be writing a post just for this case (The code for this is under github, check that out).
        
  if(response.getStatus() == Status.OK.getStatusCode()){
   Order order = (Order) response.readEntity(Order.class);
   
   System.out.println("Id: " + order.getId());
   System.out.println("Name: " + order.getName());
   System.out.println("Price: " + order.getPrice());
  }else{
   System.out.println(response.getStatus() + " " + response.getStatusInfo());
  }
So if the service is running and everything is ok, you will get the Order correctly from the server and it will be printed in the console.

The full example with maven configuration and code is under https://github.com/ivanjunckes/rest-client-api-example repository, be free to fork it. There you also will find the REST service and the client implementation.

See you next time! Thanks.

Tuesday, July 30, 2013

SOA Life Cycle


Hello everyone, this article will show how SOA Life Cycle works and what happens in each one of the stages.

Model

The first step in a service-oriented architecture project has little to do with technology and everything to do with your business. The first step is to establish what these business activities or processes actually are.

In the model phase you start by gathering business requirements and then you design and optimize their desired business process.

By simulating, or modeling, your business processes before you write a line of code, you gain a much deeper understanding of them before looking for trying to build software that helps you carry them out.
 
Assemble

After business processes are modeled and optimized, developers can implement them by building new services or by reusing existing services, and then assembling them to form composite applications. The assemble phase is about finding functionality that already exists and service-enabling it.

Deploy

When they are modeled and assembled, the assets that make up your SOA are deployed into a secure and integrated environment. The deployment needs to meet the performance and availability needs of your business.

Manage

The deployed system must be managed and monitored, both from an IT and business perspective. Information gathered during the manage step is used to gain real-time insight into business processes, enabling better business decisions and feeding information back into the life cycle for continuous process improvement. You deal with issues such as quality of service, security, and general system administration.

In this step, you monitor and optimize the system, finding and correcting inefficiencies and problems.
Because SOA is an iterative process, the completion of this step is the start of a new model phase.


Source:
http://pic.dhe.ibm.com/infocenter/esbsoa/wesbv7r5/index.jsp?topic=%2Fcom.ibm.websphere.wbpm.scenarios.esb1.doc%2Ftopics%2Fcwesb_security.html
VW003 - Introducing the Value and Governance Model of Service-Oriented Architecture, IBM Corporation, 2007.

Monday, July 22, 2013

What is Service Oriented Architecture (SOA)?

This article will give you an introduction about what is Service Oriented Architecture (SOA) and the different roles that interact with this.

Let's start, describing a Service:

From a business view, a service is what is needed to support the business process. Think about what your company does on a day to day basis and break those business processes up into repeatable business tasks or components.

What is a Service?

A repeatable business task.


A service is an application component deployed on a network-accessible platform hosted by the service provider. Its interface is described by a service description to be invoked by or to interact with a service requester.

Services are functions or operations accessible across a network with:
  • Well-defined interfaces.
  • Well-defined quality of service capabilities.
  • Well-known endpoints. An endpoint is a destination on the network that receives service requests.
Service providers
  • Offer services with published interfaces, policies and endpoints.
Service consumers
  • Use services and access them securely and reliably.
Service mediators, handlers and intermediaries
  • Provide extensible discovery, selection, metering, monitoring, logging, and more qualities of service.

Describing the SOA architectural style

You can adopt the architectural style that SOA supports by:
  • Breaking business processes up into repeatable business tasks or components.
  • Assembling the solution by snapping components together.
  • Becoming service-oriented.

What is a Service Orientation?

Building on the definition of a service, service orientation is a way of integrating your business as linked services and, more importantly, the outcomes that they bring.

What is SOA?


SOA is the IT architectural style that supports the service orientation thought process and makes it a reality.

Services are repeatable business tasks. Business processes are a series of services snapped together like building blocks. SOA is an architectural style that makes this possible.

SOA helps make building and adjusting composite applications fast and easy.


SOA in different Roles

Business Managers

SOA provides business managers with capabilities to expose a set of services to clients and partner organizations.

Business Architects

SOA is an architectural style that requires a service provider, requester, and a service description. It addresses characteristics such as loose coupling, reuse, and simple and composite implementations.

Implementation

SOA is a programming model complete with standards, tools, methods, and technologies such as Web Services.

Operations

SOA is a set of agreements among service requesters and service providers that specify the quality of service and identify key business IT metrics.

In the next articles we will continue to talk about SOA.



Source: VW003 - Introducing the Value and Governance Model of Service-Oriented Architecture, IBM Corporation, 2007.

Tuesday, July 16, 2013

REST - Pagination

Pagination is essential when retrieving information from webservices. Sometimes, we have scenarios like mobile applications where a large amount of data can bring problems.  This article aims to show how Facebook API deals with this, and also display an example of query string pagination using JAX-RS (Jersey) and JPA (Hibernate).

The Facebook's platform supports three types of pagination using query string: 

Cursor-based
  • before - This is the cursor that points to the start of the page of data that has been returned.
  • after - This is the cursor that points to the end of the page of data that has been returned.
  • limit - This is the number of individual objects that are returned in each page.

Time-based
  • until - A Unix timestamp or strtotime data value that points to the end of the range of time-based data.
  • since - A Unix timestamp or strtotime data value that points to the start of the range of time-based data.
  • limit - This is the number of individual objects that are returned in each page.

Offset-based
  • offset - This offsets the start of each page by the number specified.
  • limit - This is the number of individual objects that are returned in each page.
Example
This example will stick to the Offset-based pagination, but you can choose the one that fits your requirements.

@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public List<Order> getOrders(
 @QueryParam("offset") Integer offset, 
 @QueryParam("limit") Integer limit){
  
 Query q = _em.createQuery("from Order");
 if(offset != null){
  q.setFirstResult(offset);
 }
 
 if(limit != null){
  q.setMaxResults(limit);
 }
 return (List<Order>) q.getResultList();
}

The URL to access this would be:
/** 
* This URL would return the limit of 20 orders starting from order number 20.
**/
http://www.ivanjunckes.com/resources/orders?offset=20&limit=20

The previous code shows a good path for doing pagination with REST and JAVA. However, there are some other ways of doing pagination, but this is a topic for another article.

See you later!

Source:
https://developers.facebook.com/docs/reference/api/pagination/

Tuesday, June 25, 2013

REST - Resource Naming

REST can help a lot when we talk about integration, however not used correctly, it could bring future problems. This article will talk about some of the best practices for creating a REST API.

Use nouns instead of verbs

Keep the URI simple and intuitive. This will leave the API with a easier understanding and better to work with. A good way to test if the API was written correctly is making sure it has only 2 base URIs. For example:

This will return a collection of orders.
 /orders 
This can be used to GET (READ), POST (CREATE), PUT (UPDATE) or DELETE depending on the HTTP verb chosen.
/orders/{orderId}
This would return a collection of items from that particular order.
/orders/{orderId}/items
Using URIs with a non consistent pattern (using verbs) could end up causing a bigger effort for developers to understand and use the API.
/getAllOrders
/getOrderItems

Plural nouns

Being consistent, establishing patterns, when designing a API is very important. Another common guideline is using plural nouns. Observe that finding resources in REST can be compared to search for documents in a disk.
/documents       //(this would bring a list of documents)
/orders          //(this would bring a list of orders)
The difference between these two is that in REST, when getting a particular resource, id should be passed to use the resource, differently from the file system that file name would do it.

Concrete names rather than abstract

Sometimes developers look for a higher level of abstraction. Which sometimes bring less value for the API. Check out the next example:

Higher level of abstraction
/items
/assets

Lower level of abstraction
/blogs 
/videos
/articles

Using a higher level of abstraction, in this case, will not bring as much value for developers dealing with the api, while the lower level should allow the user to have a better understanding of the resources. This level, of course, should be defined accordingly to each cenario.

Also expose a manageable number of resources. Aim for concrete naming and to keep the number of resources between 12 and 24.

This is it for today, we will continue to talk about REST best practices in the next articles. Remember intuitive API uses plural rather than singular nouns and concrete rather than abstract names.

Source:
Web API Design - Brian Mulloy
http://apiux.com/2013/04/03/url-design-restful-web-services/

Monday, June 17, 2013

What is REST?


REST (Representational State Transfer) has become popular these days because of the high need for integration what consequently makes it very important for every developer to know and understand. This article aims to give you a guidance in what rest is and how can you use it to improve your applications.

REST describes an architectural style of networked systems such as web applications. It was first introduced in 2000 in a Ph.D dissertation by Roy Fielding, one of the principal authors of the HTTP specification. REST refers to a collection of architecture constraints and principles, which some will be shown next.

Uniform Interface

The central feature that distinguishes the REST architectural style from other network based styles is its emphasis on a uniform interface between components. Components can be origin servers, gateways, proxies or user agents (browsers).

The term uniform interface is used to describe how a (small) number of verbs with well-defined and widely accepted semantics are sufficient to meet the requirements of most distributed applications. A collection of verbs is used for communication between systems. You can check the example below which uses these verbs.



REST is defined by four interface constraints: identification of resources, manipulation of resources through representations, self-descriptive messages, and, hypermedia as the engine of application state.

Identification of resources

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a collection of other resources or even a person. REST uses a URI (unique resource identifier) to identify the particular resource involved in a interaction between components, as you saw on the previous example where a order is identified by /order/{orderId}. 

Representations

REST components perform actions on a resource by using a representation to capture the current or intended state of that resource. Representations consists of data or metadata describing the data. The response should include both, representation metadata and resource metadata. This data format of a representation is known as media type. A resource can be provided in multiple media types and you can choose the one that best fits the application.

You could ask the server to give you a "order" with the media type application/json, for example, because your client is mobile so you need less data. Or maybe you have an external client that needs to read another format like XML, then he just have to ask the server for an application/xml and it will give you the data you want.

Stateless

This is an important principle of REST which requires that every interaction between components must be stateless. It means that every response must have all the information for that request to be fully understood. The right way of controlling state in REST is using HATEOAS. 

Hypermedia as the engine of application state (HATEOAS)

REST concentrates all the control state into the representations received in response to interactions. The goal is to improve server scalability by eliminating any need for the server to maintain an awareness of the client state beyond the current request. On the example below you can see that the order already gives you the link within payment for the next transaction step maintaining the transaction control on the client-side.


Self-descriptive messages

Another constraint of REST is that messages should be self-descriptive and with all information needed for the task to be completed.

Well, that’s it. Now you have a guidance in how REST works. We’ll continue to talk about it in further articles.

See you later!

Source:

Roy Thomas Fielding dissertation, 2000.
REST in Practice book, 2010.

Wednesday, June 5, 2013

Restful project with Maven Archetype and Jersey

Hi everyone, this is my first post and hope you like it.

Today we will talk about building a Restful project using maven and jersey libraries. For this to be possible maven archetype, a tool to build projects out of templates, will be used.

In this tutorial we will be using command line maven, you can download and follow the installation intructions on http://maven.apache.org/download.cgi.


After installation follow the steps below:

1 - Go to your workspace and type:

mvn archetype:generate -DarchetypeCatalog=http://download.java.net/maven/2

2 - Archetypes will be downloaded from the catalog. After downloading you'll see this message "Choose a number or apply a filter", type 3.

3 - After selecting rest archetype, you will fill the project configuration information according to the example below:
groupId - br.com.restful (Identifies your project uniquely between all your projects)
artifactId - blog-restful-webapp (Represents the war name without version)
version - 1.0 (Identifies the project version)
package - br.com.restful (Represent the package structure)

4 - Next, a confirmation message will show up, just type Y and your project will be created.

5 - After the project have been created, type: 

cd PROJECT_NAME
mvn clean install (Clean and build)

6 - The result of previous step should be BUILD SUCCESS, which means that now you already have your rest project fully configured, compiling and ready to be executed.

After doing all these steps you will have import the project into your IDE. In this example eclipse will take place, but be free to use your prefered IDE since maven is IDE agnostic.
Open eclipse and click with the mouse right button on Project Explorer -> Import -> Existing Maven Projects, select your project and click Finish.


 

Now you can take a look on the class created by the template in br.com.restful.MyResource.




Next, click on the mouse right button over the project and run on your server. In this example we used Tomcat 6.


A page like this should appear.


To access the GET method you just have to access the link:
http://localhost:8080/blog-restful-webapp/webresources/myresource, remember that port should be set accordingly to the server configuration. On this case we used tomcat default port which is 8080.



The template initial configuration establishes that all rest services stays below webresources. This could be easily changed but this is a subject for other post.


Hope you enjoyed it and see you later.

Source:
http://docs.oracle.com/cd/E19226-01/820-7627/giqdq/