Title: Design pattern – Inversion of control and Dependency injection
Author: Shivprasad Koirala
Email: shiv_koirala@yahoo.com
Language: C#
Level: Beginner
Description: Design pattern – Inversion of control and Dependency injection
Design pattern – Inversion of control and Dependency injection
Introduction
The problem – tight coupling
Solution
Principles of IOC
Ways of implementing IOC
Implementing the DI
What’s wrong with DI FACTORY?
The container way
Implementation using Windsor
References
Other Interview question PDF's
Introduction
When we see around, architectures mainly discuss about loose coupling , scalability , performance etc etc. Many architecture forget one of the important aspects in software is making application globalized. Depending on project some application would not really want to have multi-language based websites , but i am sure many will. So in this article we will go through a series of FAQ which will give you a quick start on making application multi-language based.
Lately i have been writing and recording videos heavily on design patterns , UML and many architectural stuff you can visit http://www.questpond.com/ for design pattern and UML videos.
You can download by architecture interview question book from
http://www.questpond.com/softArchi.zip.zip
The problem – tight coupling
Before even we get in to abbreviation of IOC and DIP, let’s first understand the problem. Consider the below example we have a customer class which contains an address class object. The biggest issue with the code is tight coupling between classes. In other words the customer class depends on the address object. So for any reason address class changes it will lead to change and compiling of ‘ClsCustomer’ class also. So let’s put down problems with this approach:-
• The biggest problem is that customer class controls the creation of address object.
• Address class is directly referenced in the customer class which leads to tight coupling between address and customer objects.
• Customer class is aware of the address class type. So if we add new address types like home address, office address it will lead to changes in the customer class also as customer class is exposed to the actual address implementation.
Figure: - Problems of IOC
So if for any reason the address object is not able to create the whole customer class will fail in the constructor initialization itself.
Solution
Now that we know the issue, let’s understand the solution. The solution definitely revolves around shifting the object creation control from the customer class to some one else. The main problem roots from the customer class creating the address object. If we are able to shift this task / control of object creation from the customer class to some other entity we have solved our problem. In other sentence if we are able to invert this control to a third party we have found our solution. So the solution name is IOC (Inversion of control).
Principles of IOC
The basic principle of IOC stands on the base of Hollywood principle (response given to amateurs auditioning in Hollywood):-
Do not call us we will call you
Translating to bollywood (for struggling actors)
Aap Mauke ko mat bulao, mauka aap ke paas ayega – Hindi conversion ?
In other words it like address class saying to the customer class, do not create me I will create myself using some one else.
There are two principles of IOC:-
• Main classes aggregating other classes should not depend on the direct implementation of the aggregated classes. Both the classes should depend on abstraction. So the customer class should not depend directly on the address class. Both address and customer class should depend on an abstraction either using interface or abstract class.
• Abstraction should not depend on details, details should depend on abstraction.
Figure: - IOC framework
Figure ‘IOC framework’ shows how we can achieve this decoupling. The simplest way would be to expose a method which allows us to set the object. Let the address object creation be delegated to the IOC framework. IOC framework can be a class, client or some kind of IOC container. So it will be two step procedure IOC framework creates the address object and passes this reference to the customer class.
Ways of implementing IOC
Ok, now we know the problem, let’s try to understand the broader level solution. Let’s look at how we implement the solution for IOC. IOC is implemented using DI (Dependency injection). We have discussed on a broader level about how to inject the dependency in the previous sections. In this section we will dive deeper in to other ways of implementing DI.
Figure: - IOC and DI
Figure ‘IOC and DI’ shows how IOC and DI are organized. So we can say IOC is a principle while DI is a way of implementing IOC. In DI we have four broader ways of implementing the same:-
• Constructor way.
• Exposing setter and getter.
• Interface implementation
• Service locator
In the further sections we will walkthrough the same in more detail.
Constructor methodology
In this methodology we pass the object reference in the constructor itself. So when the client creates the object he passes the object in the constructor while the object is created. This methodology is not suited for client who can only use default constructors.
Figure: - Constructor based DI
Setter and getter
This is the most commonly used DI methodology. The dependent objects are exposed through set/get methods of classes. The bad point is because the objects are publicly exposed it breaks the encapsulation rule of object oriented programming.
Figure: - Getter and Setter
Interface based DI
In this methodology we implement an interface from the IOC framework. IOC framework will use the interface method to inject the object in the main class. You can see in figure ‘Interface based DI’ we have implemented an interface ‘IAddressDI’ which has a ‘setAddress’ method which sets the address object. This interface is then implemented in the customer class. External client / containers can then use the ‘setAddress’ method to inject the address object in the customer object.
Figure: - Interface based DI
Service locator
The other way to inject dependency is by using service locator. Your main class which will aggregate the child object will use the service locator to obtain instance of the address object. The service locator class does not create instances of the address object, it provides a methodology to register and find the services which will help in creating objects.
Figure: - Service locator
Implementing the DI
Now that we know the various types of DI to implement IOC. Its time to understand how we can actually implement these DI’s.
What’s wrong with DI FACTORY?
The first thing which clicks to mind is, can’t we achieve all the above things using factory. The main problem is all about one class doing the creational activity of its contained objects which leads to heavy coupling. Introducing factory can solve that to a great extent.
Here are the issues with factory which makes us force to think about some other solutions:-
• Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
• Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.
• Factories are custom: - They are very much custom to a particular implementation.
• Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.
The container way
A container is an abstraction responsible for object management, instantiation and configuration. So you can configure the objects using the container rather than writing client code like factory patterns to implement object management. There are many containers available which can help us manage dependency injection with ease. So rather than writing huge factory codes container identifies the object dependencies and creates and injects them in appropriate objects.
Figure: - Container in action
So you can think about container as a mid man who will register address and customer objects as separate entity and later the container creates the customer and address object and injects the address object in the customer. So you can visualize the high level of abstraction provided by containers.
What we will do is cover the customer and address example using one of the container Windsor container, you can get more details about the container at http://www.castleproject.org/
Implementation using Windsor
The first thing we do is create the address interface and create the concrete class from this interface. Interface will be an entity to use for injection rather than concrete objects, so that we deal with more abstraction rather than concrete implementation.
Figure: - Address interface
In the customer class we have passed the object through the constructor.
Figure: - Customer class
If we are said to write the client code. , it would be something as shown in figure ‘Client code’. In step 1 we create a concrete object and point the implementation to the interface IAddress. In step 2 we pass the interface object to customer class constructor while creating the object.
Figure: - Client code
Ok, now lets see how this will work if we use the Windsor container. Figure ‘Windsor container’ shows how it looks like. So step 1 creates the Windsor container object. Step 2 and 3 register the types and concrete objects in the container. Step 4 requests the container to create the customer object. In this step the container resolves and set the address object in the constructor. Step 5 releases the customer object.
Thứ Tư, 27 tháng 7, 2011
Thứ Sáu, 22 tháng 7, 2011
XML REST Web Services
Log in / create account
Openbravo.com
Partner Portal
Issues
Blogs
Forge
Exchange
University
Downloads
View source | Discuss this page | Page history | Printable version
ADVERTISEMENT
Accounting eLearning Courses
Toolbox
Main Page
Upload file
What links here
Recent changes
Help
Google Search
Participate
Communicate
Report a bug
Contribute
Talk to us now!
Partnerships
SourceForge.net Logo
Openbravo ERP at SourceForge
SourceForge.net Logo
Openbravo POS at SourceForge
ERP 2.50:Developers Guide/Concepts/XML REST Web Services
Languages:
English | Translate this article...
ERP 2.50:Developers Guide
ERP 2.50:Developers Guide/Fundamentals and Concepts
ERP 2.50:Developers Guide/Concepts/WebServices
ERP 2.50:Developers Guide/Concepts/XML REST Web Services
ERP 2.50:Developers Guide/Concepts/SOAP Web Services
ERP 2.50:Developers Guide/Concepts/JSON REST Web Services
Index
Contents
[hide]
1 Overview
2 Glossary
3 Why REST?
4 REST Webservice
5 Main REST Webservice
6 DAL REST Web service
7 Single Request and Response
8 Query Request and Response
9 Update/Create Request and Response
10 Remove Request and Response
11 Update multiple business objects Request and Response (Import)
12 Business Object to XML
13 DAL REST: Overview of return messages in XML
14 HTTP Return Codes
15 Login and Security
16 Database Transaction
17 Non-updatable fields: Client, Organisation etc.
18 XSD Schema Generation for REST approach
19 Error Handling
20 Simple XSLT templates
21 Test
22 Tips & tricks and trouble shooting
Overview
Openbravo ERP REST consists of a framework offering security and exception services and a data access REST web service implementation. The data access (DAL) REST web services provide a CRUD-like web service so that external applications can retrieve, update, create and delete business objects through standard HTTP requests.
Glossary
This document uses the term business object to denote an entity and its dependent information. A business object can be a simple entity such as a currency which just has basic primitive fields. On the other hand it can also be a structure of entities, for example an order header with its order line. A business object structure always has one business object which is the owner of all the business objects in that structure, for example for a sales order the sales order header business object is the owner of the complete structure. Another way of describing this is that the order lines depend on the order header, i.e. an order line can not exist without its order header and when an order header is removed also the order line should be removed.
Some background information related to REST:
The REST concept was first described by Roy Fielding:
Fieldings's Dissertation
An overview article on REST with a lot of links to other material:
Wikipedia on REST
A quick intro into an example REST approach:
How to Create a REST Protocol
Building Web Services the REST Way
Some links related to REST versus SOAP, there is a fair amount of articles on the web on this topic:
REST versus SOAP - the REST story
A RESTful approach to Web services
Why REST?
There are a number of reasons why a REST approach makes sense for a data centric service: a REST approach
favors identifying and addressing resources which fits to the data-centric nature of the provided apis (a resource corresponds to a business object)
has actions (POST, PUT, DELETE, GET) which correspond to standard CRUD actions
allows linking to specific business objects or to sets of business objects. This is a very powerfull feature of a REST approach and it allows for easy navigation between business objects.
is simple to develop and use, and very lightweight from an architectural point of view
REST Webservice
It is important to note that REST is not a standard but more an approach or architectural style. Openbravo ERP REST adheres to the REST approach:
resources (business objects) are identified by specific links which are stable over time
the GET action is side-effect free
all http actions: POST, PUT, DELETE, GET are supported
http response codes are used to specify results of actions
Main REST Webservice
A request is processed by the REST web service servlet (org.openbravo.service.web.BaseWebServiceServlet). This servlet uses the request URL to determine the type of request and how to handle it.
The REST web service servlet also handle login and authentication (see below).
A request (GET, POST, PUT) can consist of three parts:
the url path
the url parameters
the content of the request
A GET request will not have content and is completely controlled by the url path and its parameters.
A POST and PUT request will have content which is assumed to be a valid xml document.
The response of a REST call will be an XML document, containing the requested data, a result XML message or an error XML message.
DAL REST Web service
The DAL REST web service is an implementation of a REST web service in Openbravo ERP 2.50. It provides a CRUD-like web service so that external applications can retrieve, update, create and delete business objects through standard HTTP requests.
It provides the following functionality:
retrieve a single business object using a url which contains both the type as well as the id of the request business object
retrieve a list of business objects using just the type, for example http://demo.openbravo.com/openbravo/ws/dal/Country (User Name: Openbravo / Password: openbravo)
querying, filtering, paging and sorting of lists of business objects
updating of an existing business object or multiple business objects through xml and a http POST or PUT operation
creation of new business objects through a POST/PUT operation which submits a xml structure
export and import of data: xml files which contain a mix of different types of business objects and a mix of new and existing business objects
retrieval of a list of id and identifier values, for example to fill a listbox in an external user interface
delete operation using either a url pointing to a specific business object which needs to be removed or a XML document (in the content) which contains business objects (as full xml or as partial xml) which need to be removed.
The rest of this document will mainly focus on the functionality of the DAL REST web services.
Single Request and Response
A single request is a request which points to one unique business object. For example the url:
http://demo.openbravo.com/openbravo/ws/dal/Country/106 (User Name: Openbravo / Password: openbravo)
will return the xml for an instance of the Country business object with ID = 106 (Spain). The REST Webservice will retrieve this business object from the database, create XML for it and return the resulting XML. See below for a description of the XML.
Query Request and Response
A query url is used to retrieve a list of business objects. It can handle filter, sort and paging parameters. An example of a query url: for example:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.id='100'&orderBy=name&firstResult=5&maxResult=10
(User Name: Openbravo / Password: openbravo)
This url will return all Country objects which have ID = 100 (USD) as currency, sorted by the country name, the page starting at object 5 and 10 objects should be returned.
The REST query functionality should support the following parameters in the url:
where: a HQL whereclause
orderBy: an orderBy definition
firstResult and maxResult parameters for paging support
The user has two types of possible operations which can be performed by the query:
default when after the entity name there is no additional segment in the URL: this operation will query for the business objects and return (in XML) the properties of each of the business objects (this depends on security settings also).
count: this will return the number of business objects which are selectable according to the filter. This action is used for support of paged views.
The default query operation will return the business objects (with their child objects) as XML. See the business-object-to-xml section. If you only want to have the objects returned without children then you can pass the includeChildren parameter (as a URL parameter) with the value false.
Note: when doing querying with the whereclause any special characters should be url encoded, for example the % character when doing like has to be encoded with %25, like this:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=name like '%25Fr%25' (User Name: Openbravo / Password: openbravo)
Note: Notice that in this first example:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.id='100'&orderBy=name&firstResult=5&maxResult=10
is it also possible to query the server using the currency identifier returned. Nevertheless, for this case we must use the original name of the identifier, in the currency table it is ISO_CODE so the query would change to:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.iSOCode='USD'&orderBy=name&firstResult=5&maxResult=10
Note Notice that the where clause can also be used with more than one condition using the AND clause, e.g.
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.id='100'%20and%20hasRegions=true
Update/Create Request and Response
A business object can be updated/created through REST using the http POST or PUT command. The posted XML should adhere to the XML Schema generated by the REST Webservice (see below). With one exception, for update situations it is allowed to only include the changed properties in the XML.
The system will automatically check (by querying) if a business object is new or not. If no id is supplied then it will always be considered as new, if a id is supplied then a database query is done. If the id exists (for that type) in the database then the system will assume an update. If the id does not exist it is an insert, in which case the id (in the xml) is maintained.
If the update was successful a success response is returned ( ), if it fails an error XML response is send back.
Remove Request and Response
The DAL REST webservice also supports a delete or remove request. Delete requests use the http DELETE command. The Delete action can accept two types or urls:
a single URI pointing to the business object which needs to be removed, for example:
http://localhost:8080/openbravo/ws/dal/Product/1000004
a URI with a where parameter:
http://localhost:8080/openbravo/ws/dal/Product?where=name='C02'
In the second case it is possible to remove multiple objects in one http DELETE request.
Update multiple business objects Request and Response (Import)
The system also supports updating of multiple business objects which are passed in one file. The following aspects need to be taken into account:
the xml file can contain mixes of new and existing (to-be-updated) business objects
there maybe references to new business objects in the same xml file, these references use a unique id which does not need to in the database. This means that the import logic will internally (within the xml file) resolve object references before persisting the total xml file.
the xml file can contain mixes of different types of business objects
A XML file containing different types can be posted to the generic DAL web service url:
http://demo.openbravo.com/openbravo/ws/dal (User Name: Openbravo / Password: openbravo)
Business Object to XML
The XML response to a retrieval request consists of the data of the business object or business objects. The business object is translated to xml in the following way:
The entity name is used for the tag name of the business object element. The entity tag/element also has attributes for the id and the identifier.
The property name is used for the element name of each property. It depends on the security settings of the user which properties or information is returned (see security section).
Property values are xml-ised as follows:
Date value is exported according to the XML Schema datetime format
String value is exported as is (encoding is required)
Numeric value is exported using decimal point and no grouping
Reference (to another business object) is converted to an xml tag which contains the id, the entity name and the identifier value. This makes it possible for consumers of the XML to easily create hyperlinks to retrieve the data of the reference business object. The identifier can be used to generate a display of the reference.
Child objects (the list/one-to-many associations) are also exported and are embedded in the parent object (this is done recursively through the parent-child structure). You can disable/prevent the return of child objects by setting the (URL) parameter includeChildren to false.
The element used for the XML version of a reference is also used in case when lists of references need to be exported.
DAL REST: Overview of return messages in XML
The design discusses different functionalities. To summarize this section lists the set of return types which can be expected for different types of REST requests:
a request for a specific business object will return a XML document with this business object
a request (a query) for a list of business objects will return a XML document with the data of those business objects
a request (a query) for a list of identifiers will return a XML document with the only the id, entity name and the identifier of each business object
a query with a count parameter will only return a simple xml message with a count number (5 )
an update/insert request will return a success XML message ( ) if it succeeded, the return message will contain the id of the inserted record.
a query with a identifier parameter will return a list of identifier values (one for each business object)
If the requests fails then an error XML message is returned.
HTTP Return Codes
The REST Webservice uses the following error codes:
200 (OK): for successfull requests
400 (Bad Request): in case the uri could not be parsed or in case of invalid xml
401 (Unauthorized): is returned when a security exception occurs
404 (Not found): if the entityname does not exist or the if an individual business object is addressed, if the business object does not exist. Note that a 410 (Gone) response could also be applicable here but it is less know therefore the 404 is used.
409 (Conflict): is returned for a POST or PUT action, specifies that the data which was posted is out-of-date or invalid.
500 (Internal Server Error): if an unrecoverable application error occured.
Login and Security
The REST Webservice provides two methods for logging in:
login with login/password passed as request parameters (the parameters names are resp. l and p)
basic http authentication
The following aspects are of importance for security:
The login and context are stored in a session for performance reasons
If the caller/client is session-less (does not support cookies) then it is also possible to include login information in every request. This is less preferred from a performance point of view.
After a successfull login the REST web service action is run within the context of the user. The REST webservice uses the DAL security control mechanism to control read and write access.
Database Transaction
A REST web service request is basically the same as a normal HTTP request. This means that transaction handling is the same as for standard HTTP requests. If no exception occured then the transaction is committed at the end of the web service request (on the Openbravo server).
Non-updatable fields: Client, Organisation etc.
There are a number of properties for each business object which are not always changeable through the REST webservice:
Client and Organisation: a webservice update of a business object may not change the Client and Organisation information. In creation mode the client may not be set, the organisation may be specified, if not specified then it is set from the user information.
Update and Created audit fields: the update and created audit fields are not updatable/changeable through the webservice api.
XSD Schema Generation for REST approach
The DAL webservice generates a XSD schema on the basis of the runtime model. This XSD schema defines the xml which is generated by the REST web service. This definition is also used for the XML used to update Openbravo through REST web services.
For an Openbravo ERP instance running on http://demo.openbravo.com/openbravo the XSD can be retrieved through this request:
http://demo.openbravo.com/openbravo/ws/dal/schema (User Name: Openbravo / Password: openbravo)
Error Handling
When a request can not be processed and an error occurs then an error XML document and the relevant HTTP response code is returned. The error XML document contains the exception message.
The stacktrace and other more detailed information is not sent out on purpose (because of security reasons).
Simple XSLT templates
Openbravo ERP 2.50 has some simple XSLT templates to show how the XML can be processed and demonstrate that REST is a good approach for allowing navigation through data sets. The following URL shows the start URL for a DAL web service call using the XSLT templates:
http://demo.openbravo.com/openbravo/ws/dal/?template=types.xslt (User Name: Openbravo / Password: openbravo)
http://demo.openbravo.com/openbravo/ws/dal/Country/106?template=bo.xslt (User Name: Openbravo / Password: openbravo)
http://demo.openbravo.com/openbravo/ws/dal/Currency/100?template=bo.xslt (User Name: Openbravo / Password: openbravo)
The XSLT templates can be found in the org.openbravo.service.rest package.
Test
The REST Webservice functionality is tested using junit testcases. REST test cases can be found in the openbravo development project in the src-test folder and then in the org.openbravo.test.webservice package. The REST test cases give a first impression on how to do REST requests directly from Java incl. basic authentication.
Tips & tricks and trouble shooting
For trouble shooting and tips and tricks please see this link here. The tips and tricks section for example discuss a firefox plugin to make it easy to test REST webservices.
Languages:
English | Translate this article...
ERP 2.50:Developers Guide/Concepts/WebServices | ERP 2.50:Developers Guide/Concepts/SOAP Web Services
Category: Development ERP 2.50
This page has been accessed 12,370 times. This page was last modified on 14 June 2011, at 11:03. Content is available under Creative Commons Attribution-ShareAlike 2.5 Spain License.
To report an error or for administrative issues about this site go to Wiki Administration Page
Openbravo.com
Partner Portal
Issues
Blogs
Forge
Exchange
University
Downloads
View source | Discuss this page | Page history | Printable version
ADVERTISEMENT
Accounting eLearning Courses
Toolbox
Main Page
Upload file
What links here
Recent changes
Help
Google Search
Participate
Communicate
Report a bug
Contribute
Talk to us now!
Partnerships
SourceForge.net Logo
Openbravo ERP at SourceForge
SourceForge.net Logo
Openbravo POS at SourceForge
ERP 2.50:Developers Guide/Concepts/XML REST Web Services
Languages:
English | Translate this article...
ERP 2.50:Developers Guide
ERP 2.50:Developers Guide/Fundamentals and Concepts
ERP 2.50:Developers Guide/Concepts/WebServices
ERP 2.50:Developers Guide/Concepts/XML REST Web Services
ERP 2.50:Developers Guide/Concepts/SOAP Web Services
ERP 2.50:Developers Guide/Concepts/JSON REST Web Services
Index
Contents
[hide]
1 Overview
2 Glossary
3 Why REST?
4 REST Webservice
5 Main REST Webservice
6 DAL REST Web service
7 Single Request and Response
8 Query Request and Response
9 Update/Create Request and Response
10 Remove Request and Response
11 Update multiple business objects Request and Response (Import)
12 Business Object to XML
13 DAL REST: Overview of return messages in XML
14 HTTP Return Codes
15 Login and Security
16 Database Transaction
17 Non-updatable fields: Client, Organisation etc.
18 XSD Schema Generation for REST approach
19 Error Handling
20 Simple XSLT templates
21 Test
22 Tips & tricks and trouble shooting
Overview
Openbravo ERP REST consists of a framework offering security and exception services and a data access REST web service implementation. The data access (DAL) REST web services provide a CRUD-like web service so that external applications can retrieve, update, create and delete business objects through standard HTTP requests.
Glossary
This document uses the term business object to denote an entity and its dependent information. A business object can be a simple entity such as a currency which just has basic primitive fields. On the other hand it can also be a structure of entities, for example an order header with its order line. A business object structure always has one business object which is the owner of all the business objects in that structure, for example for a sales order the sales order header business object is the owner of the complete structure. Another way of describing this is that the order lines depend on the order header, i.e. an order line can not exist without its order header and when an order header is removed also the order line should be removed.
Some background information related to REST:
The REST concept was first described by Roy Fielding:
Fieldings's Dissertation
An overview article on REST with a lot of links to other material:
Wikipedia on REST
A quick intro into an example REST approach:
How to Create a REST Protocol
Building Web Services the REST Way
Some links related to REST versus SOAP, there is a fair amount of articles on the web on this topic:
REST versus SOAP - the REST story
A RESTful approach to Web services
Why REST?
There are a number of reasons why a REST approach makes sense for a data centric service: a REST approach
favors identifying and addressing resources which fits to the data-centric nature of the provided apis (a resource corresponds to a business object)
has actions (POST, PUT, DELETE, GET) which correspond to standard CRUD actions
allows linking to specific business objects or to sets of business objects. This is a very powerfull feature of a REST approach and it allows for easy navigation between business objects.
is simple to develop and use, and very lightweight from an architectural point of view
REST Webservice
It is important to note that REST is not a standard but more an approach or architectural style. Openbravo ERP REST adheres to the REST approach:
resources (business objects) are identified by specific links which are stable over time
the GET action is side-effect free
all http actions: POST, PUT, DELETE, GET are supported
http response codes are used to specify results of actions
Main REST Webservice
A request is processed by the REST web service servlet (org.openbravo.service.web.BaseWebServiceServlet). This servlet uses the request URL to determine the type of request and how to handle it.
The REST web service servlet also handle login and authentication (see below).
A request (GET, POST, PUT) can consist of three parts:
the url path
the url parameters
the content of the request
A GET request will not have content and is completely controlled by the url path and its parameters.
A POST and PUT request will have content which is assumed to be a valid xml document.
The response of a REST call will be an XML document, containing the requested data, a result XML message or an error XML message.
DAL REST Web service
The DAL REST web service is an implementation of a REST web service in Openbravo ERP 2.50. It provides a CRUD-like web service so that external applications can retrieve, update, create and delete business objects through standard HTTP requests.
It provides the following functionality:
retrieve a single business object using a url which contains both the type as well as the id of the request business object
retrieve a list of business objects using just the type, for example http://demo.openbravo.com/openbravo/ws/dal/Country (User Name: Openbravo / Password: openbravo)
querying, filtering, paging and sorting of lists of business objects
updating of an existing business object or multiple business objects through xml and a http POST or PUT operation
creation of new business objects through a POST/PUT operation which submits a xml structure
export and import of data: xml files which contain a mix of different types of business objects and a mix of new and existing business objects
retrieval of a list of id and identifier values, for example to fill a listbox in an external user interface
delete operation using either a url pointing to a specific business object which needs to be removed or a XML document (in the content) which contains business objects (as full xml or as partial xml) which need to be removed.
The rest of this document will mainly focus on the functionality of the DAL REST web services.
Single Request and Response
A single request is a request which points to one unique business object. For example the url:
http://demo.openbravo.com/openbravo/ws/dal/Country/106 (User Name: Openbravo / Password: openbravo)
will return the xml for an instance of the Country business object with ID = 106 (Spain). The REST Webservice will retrieve this business object from the database, create XML for it and return the resulting XML. See below for a description of the XML.
Query Request and Response
A query url is used to retrieve a list of business objects. It can handle filter, sort and paging parameters. An example of a query url: for example:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.id='100'&orderBy=name&firstResult=5&maxResult=10
(User Name: Openbravo / Password: openbravo)
This url will return all Country objects which have ID = 100 (USD) as currency, sorted by the country name, the page starting at object 5 and 10 objects should be returned.
The REST query functionality should support the following parameters in the url:
where: a HQL whereclause
orderBy: an orderBy definition
firstResult and maxResult parameters for paging support
The user has two types of possible operations which can be performed by the query:
default when after the entity name there is no additional segment in the URL: this operation will query for the business objects and return (in XML) the properties of each of the business objects (this depends on security settings also).
count: this will return the number of business objects which are selectable according to the filter. This action is used for support of paged views.
The default query operation will return the business objects (with their child objects) as XML. See the business-object-to-xml section. If you only want to have the objects returned without children then you can pass the includeChildren parameter (as a URL parameter) with the value false.
Note: when doing querying with the whereclause any special characters should be url encoded, for example the % character when doing like has to be encoded with %25, like this:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=name like '%25Fr%25' (User Name: Openbravo / Password: openbravo)
Note: Notice that in this first example:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.id='100'&orderBy=name&firstResult=5&maxResult=10
is it also possible to query the server using the currency identifier returned. Nevertheless, for this case we must use the original name of the identifier, in the currency table it is ISO_CODE so the query would change to:
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.iSOCode='USD'&orderBy=name&firstResult=5&maxResult=10
Note Notice that the where clause can also be used with more than one condition using the AND clause, e.g.
http://demo.openbravo.com/openbravo/ws/dal/Country?where=currency.id='100'%20and%20hasRegions=true
Update/Create Request and Response
A business object can be updated/created through REST using the http POST or PUT command. The posted XML should adhere to the XML Schema generated by the REST Webservice (see below). With one exception, for update situations it is allowed to only include the changed properties in the XML.
The system will automatically check (by querying) if a business object is new or not. If no id is supplied then it will always be considered as new, if a id is supplied then a database query is done. If the id exists (for that type) in the database then the system will assume an update. If the id does not exist it is an insert, in which case the id (in the xml) is maintained.
If the update was successful a success response is returned (
Remove Request and Response
The DAL REST webservice also supports a delete or remove request. Delete requests use the http DELETE command. The Delete action can accept two types or urls:
a single URI pointing to the business object which needs to be removed, for example:
http://localhost:8080/openbravo/ws/dal/Product/1000004
a URI with a where parameter:
http://localhost:8080/openbravo/ws/dal/Product?where=name='C02'
In the second case it is possible to remove multiple objects in one http DELETE request.
Update multiple business objects Request and Response (Import)
The system also supports updating of multiple business objects which are passed in one file. The following aspects need to be taken into account:
the xml file can contain mixes of new and existing (to-be-updated) business objects
there maybe references to new business objects in the same xml file, these references use a unique id which does not need to in the database. This means that the import logic will internally (within the xml file) resolve object references before persisting the total xml file.
the xml file can contain mixes of different types of business objects
A XML file containing different types can be posted to the generic DAL web service url:
http://demo.openbravo.com/openbravo/ws/dal (User Name: Openbravo / Password: openbravo)
Business Object to XML
The XML response to a retrieval request consists of the data of the business object or business objects. The business object is translated to xml in the following way:
The entity name is used for the tag name of the business object element. The entity tag/element also has attributes for the id and the identifier.
The property name is used for the element name of each property. It depends on the security settings of the user which properties or information is returned (see security section).
Property values are xml-ised as follows:
Date value is exported according to the XML Schema datetime format
String value is exported as is (encoding is required)
Numeric value is exported using decimal point and no grouping
Reference (to another business object) is converted to an xml tag which contains the id, the entity name and the identifier value. This makes it possible for consumers of the XML to easily create hyperlinks to retrieve the data of the reference business object. The identifier can be used to generate a display of the reference.
Child objects (the list/one-to-many associations) are also exported and are embedded in the parent object (this is done recursively through the parent-child structure). You can disable/prevent the return of child objects by setting the (URL) parameter includeChildren to false.
The element used for the XML version of a reference is also used in case when lists of references need to be exported.
DAL REST: Overview of return messages in XML
The design discusses different functionalities. To summarize this section lists the set of return types which can be expected for different types of REST requests:
a request for a specific business object will return a XML document with this business object
a request (a query) for a list of business objects will return a XML document with the data of those business objects
a request (a query) for a list of identifiers will return a XML document with the only the id, entity name and the identifier of each business object
a query with a count parameter will only return a simple xml message with a count number (
an update/insert request will return a success XML message (
a query with a identifier parameter will return a list of identifier values (one for each business object)
If the requests fails then an error XML message is returned.
HTTP Return Codes
The REST Webservice uses the following error codes:
200 (OK): for successfull requests
400 (Bad Request): in case the uri could not be parsed or in case of invalid xml
401 (Unauthorized): is returned when a security exception occurs
404 (Not found): if the entityname does not exist or the if an individual business object is addressed, if the business object does not exist. Note that a 410 (Gone) response could also be applicable here but it is less know therefore the 404 is used.
409 (Conflict): is returned for a POST or PUT action, specifies that the data which was posted is out-of-date or invalid.
500 (Internal Server Error): if an unrecoverable application error occured.
Login and Security
The REST Webservice provides two methods for logging in:
login with login/password passed as request parameters (the parameters names are resp. l and p)
basic http authentication
The following aspects are of importance for security:
The login and context are stored in a session for performance reasons
If the caller/client is session-less (does not support cookies) then it is also possible to include login information in every request. This is less preferred from a performance point of view.
After a successfull login the REST web service action is run within the context of the user. The REST webservice uses the DAL security control mechanism to control read and write access.
Database Transaction
A REST web service request is basically the same as a normal HTTP request. This means that transaction handling is the same as for standard HTTP requests. If no exception occured then the transaction is committed at the end of the web service request (on the Openbravo server).
Non-updatable fields: Client, Organisation etc.
There are a number of properties for each business object which are not always changeable through the REST webservice:
Client and Organisation: a webservice update of a business object may not change the Client and Organisation information. In creation mode the client may not be set, the organisation may be specified, if not specified then it is set from the user information.
Update and Created audit fields: the update and created audit fields are not updatable/changeable through the webservice api.
XSD Schema Generation for REST approach
The DAL webservice generates a XSD schema on the basis of the runtime model. This XSD schema defines the xml which is generated by the REST web service. This definition is also used for the XML used to update Openbravo through REST web services.
For an Openbravo ERP instance running on http://demo.openbravo.com/openbravo the XSD can be retrieved through this request:
http://demo.openbravo.com/openbravo/ws/dal/schema (User Name: Openbravo / Password: openbravo)
Error Handling
When a request can not be processed and an error occurs then an error XML document and the relevant HTTP response code is returned. The error XML document contains the exception message.
The stacktrace and other more detailed information is not sent out on purpose (because of security reasons).
Simple XSLT templates
Openbravo ERP 2.50 has some simple XSLT templates to show how the XML can be processed and demonstrate that REST is a good approach for allowing navigation through data sets. The following URL shows the start URL for a DAL web service call using the XSLT templates:
http://demo.openbravo.com/openbravo/ws/dal/?template=types.xslt (User Name: Openbravo / Password: openbravo)
http://demo.openbravo.com/openbravo/ws/dal/Country/106?template=bo.xslt (User Name: Openbravo / Password: openbravo)
http://demo.openbravo.com/openbravo/ws/dal/Currency/100?template=bo.xslt (User Name: Openbravo / Password: openbravo)
The XSLT templates can be found in the org.openbravo.service.rest package.
Test
The REST Webservice functionality is tested using junit testcases. REST test cases can be found in the openbravo development project in the src-test folder and then in the org.openbravo.test.webservice package. The REST test cases give a first impression on how to do REST requests directly from Java incl. basic authentication.
Tips & tricks and trouble shooting
For trouble shooting and tips and tricks please see this link here. The tips and tricks section for example discuss a firefox plugin to make it easy to test REST webservices.
Languages:
English | Translate this article...
ERP 2.50:Developers Guide/Concepts/WebServices | ERP 2.50:Developers Guide/Concepts/SOAP Web Services
Category: Development ERP 2.50
This page has been accessed 12,370 times. This page was last modified on 14 June 2011, at 11:03. Content is available under Creative Commons Attribution-ShareAlike 2.5 Spain License.
To report an error or for administrative issues about this site go to Wiki Administration Page
Why REST?
There are a number of reasons why a REST approach makes sense for a data centric service: a REST approach
favors identifying and addressing resources which fits to the data-centric nature of the provided apis (a resource corresponds to a business object)
has actions (POST, PUT, DELETE, GET) which correspond to standard CRUD actions
allows linking to specific business objects or to sets of business objects. This is a very powerfull feature of a REST approach and it allows for easy navigation between business objects.
is simple to develop and use, and very lightweight from an architectural point of view
favors identifying and addressing resources which fits to the data-centric nature of the provided apis (a resource corresponds to a business object)
has actions (POST, PUT, DELETE, GET) which correspond to standard CRUD actions
allows linking to specific business objects or to sets of business objects. This is a very powerfull feature of a REST approach and it allows for easy navigation between business objects.
is simple to develop and use, and very lightweight from an architectural point of view
Thứ Ba, 19 tháng 7, 2011
Phát triển các widget bằng Dojo 1.x
Các phương thức khuôn mẫu
Trong pha tạo widget, một vài phương thức sẽ được gọi, cho phép những người cài đặt thực hiện một số hành động trong các pha khởi tạo cụ thể. Các phương thức sau đây được gọi:
postMixInProperties: phương thức này được gọi sau khi tất cả các tham số của widget đã được thiết lập (được trộn) thành các thuộc tính của cá thể widget. Đây là thời điểm thích hợp để tiếp tục khởi tạo thuộc tính, nếu dựa trên các thuộc tính mà việc khởi tạo cá thể đối tượng sẽ cung cấp.
buildRendering: phương thức này được gọi vào thời điểm sinh ra biểu hiện của widget. Điểm móc nối này được triển khai trong lớp trộn dijit._Templated, lớp này cũng triển khai các khung sườn widget bằng các khuôn mẫu HTML. Những người triển khai có thể cung cấp cách thực hiện của mình nhằm tinh chỉnh công việc của lớp _Templated.
postCreate: phương thức này được gọi sau khi DOM của widget đã sẵn sàng và được chèn vào trang. Người triển khai có thể thao tác trên cấu trúc DOM của widget tại vị trí này. Các widget con chưa được khởi động.
startup: cơ hội cuối để thao tác trên widget. Vào lúc này thì các wiget con đã được khởi động.
uninitialize: được gọi sau khi widget đã bị hủy bỏ. Người triển khai có thể thực hiện một vài việc dọn dẹp làm sạch không được tự động hóa.
Các phương thức khuôn mẫu có thể do người triển khai cung cấp, và người triển khai phải nhớ rằng lớp cha mẹ bậc trên có thể đã triển khai thực hiện các phương thức khuôn mẫu của nó. Để đảm bảo việc khởi tạo chính xác tất cả các lớp trong chuỗi móc xích này, người triển khai phải mã hóa thủ công lời gọi phương thức của lớp bậc trên như được chỉ ra trong Liệt kê 11.
http://www.ibm.com/developerworks/vn/library/wa-aj-dojotool/index.html
Trong pha tạo widget, một vài phương thức sẽ được gọi, cho phép những người cài đặt thực hiện một số hành động trong các pha khởi tạo cụ thể. Các phương thức sau đây được gọi:
postMixInProperties: phương thức này được gọi sau khi tất cả các tham số của widget đã được thiết lập (được trộn) thành các thuộc tính của cá thể widget. Đây là thời điểm thích hợp để tiếp tục khởi tạo thuộc tính, nếu dựa trên các thuộc tính mà việc khởi tạo cá thể đối tượng sẽ cung cấp.
buildRendering: phương thức này được gọi vào thời điểm sinh ra biểu hiện của widget. Điểm móc nối này được triển khai trong lớp trộn dijit._Templated, lớp này cũng triển khai các khung sườn widget bằng các khuôn mẫu HTML. Những người triển khai có thể cung cấp cách thực hiện của mình nhằm tinh chỉnh công việc của lớp _Templated.
postCreate: phương thức này được gọi sau khi DOM của widget đã sẵn sàng và được chèn vào trang. Người triển khai có thể thao tác trên cấu trúc DOM của widget tại vị trí này. Các widget con chưa được khởi động.
startup: cơ hội cuối để thao tác trên widget. Vào lúc này thì các wiget con đã được khởi động.
uninitialize: được gọi sau khi widget đã bị hủy bỏ. Người triển khai có thể thực hiện một vài việc dọn dẹp làm sạch không được tự động hóa.
Các phương thức khuôn mẫu có thể do người triển khai cung cấp, và người triển khai phải nhớ rằng lớp cha mẹ bậc trên có thể đã triển khai thực hiện các phương thức khuôn mẫu của nó. Để đảm bảo việc khởi tạo chính xác tất cả các lớp trong chuỗi móc xích này, người triển khai phải mã hóa thủ công lời gọi phương thức của lớp bậc trên như được chỉ ra trong Liệt kê 11.
http://www.ibm.com/developerworks/vn/library/wa-aj-dojotool/index.html
Đăng ký:
Nhận xét (Atom)