Search This Blog

Friday, October 30, 2015

EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535

Session ID: CON7535
Session Title: EJB 3.2/JPA 2.1 Best Practice with life examples (Download Link)
Session Type: Conference Session
Session Abstract:
This session’s speaker, an architect, discusses lessons learned from using JPA and EJB to support a high-volume, high-performance applications. These best practices don't only involve JPA/EJB but also its integration with other Java EE 7 technologies. They also include coding best practices, testing and production practices. The presentation focuses primarily on some Key concepts such as persistence context, lazy loading, caching, flushing, dirty checking, transaction and connection demarcation. This is a fast-paced presentation with many code samples. Categories covered include configuration, JPA, concurrency, performance tuning, exception handling and many more.




Sunday, September 13, 2015

What's the difference between text/xml vs application/xml for webservice response?

XML has two MIME types, application/xml and text/xml. These are often used interchangeably, but there is a subtle difference which is why application/xml is generally recommended over the latter.


Let me explain why: according to the standard, text/*-MIME types have a us-ascii character set unless otherwise specified in the HTTP headers. This effectively means that any encoding defined in the XML prolog (e.g. <?xml version=”1.0” encoding=”UTF-8”?>) is ignored. This is of course not the expected and desired behavior.



To further complicate matters, most/all browser implementations actually implement nonstandard behavior for text/xml because they process the encoding as if it were application/xml.


application/xml is generally the preferred mime type. For text/xml it appears the encoding will generally be treated as us ascii regardless of what is specified in the XML document header (unless otherwise specified in the HTTP headers).


From the RFC (3023), under section 3, XML Media Types:

If an XML document -- that is, the unprocessed, source XML document -- is readable by casual users, text/xml is preferable to application/xml. MIME user agents (and web user agents) that do not have explicit support for text/xml will treat it as text/plain, for example, by displaying the XML MIME entity as plain text. Application/xml is preferable when the XML MIME entity is unreadable by casual users.

So, text/* has encoding issues, and is not implemented by browsers in a standards-compliant manner, which is why using application/* is recommended.

RESTfull valid return types!

Valid return types is general includes:

  • void
  • byte[] 
  • String
  • Application-Supplied JAXB classes and javax.xml.bunding.JAXBElement
  • MultivaluedMap<String,String>
  • Response, which can set status property
  • GenericEntity

RESTfull @QueryParam and @PathParam, What it Can be and Can't be!


  • All primitive types except char.
  • All wrapper classes of primitive types except Character.
  • Any class with the static method named valueOf(String) that accepts a single String argument.
  • Any class with constructorthat takes a single String as a parameter
  • List<T>, Set<T>, SortedSet<T>, where T matches the already listed criteria. Sometimes parameters many contain more than one value for the same name. If this is the case, this types may be used to obtain all values.

DefaultValue annotation may be used to supply a default value for parameters

Tuesday, August 04, 2015

Share your knowledge during my JavaOne 2015 Conference Session : EJB 3.2/JPA 2.1 Best Practices ...


My session below on which I'm a speaker at JavaOne 2015 San-Francisco, CA, USA accepted.



I would like to make it interactive and need you all to share your experience and hot issues you face while using EJB, JPA, Hibernate, CDI. 
Your interactive comment is highly appreciated.

Conference: JavaOne
Session Type: Conference Session
Session ID: CON7535
Session Title: EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples



Thanks for being a part of this success.

Ahmad Gohar
https://about.me/ansgohar


Thursday, July 16, 2015

iBATIS, Hibernate, JPA; What to use

iBATIS, Hibernate, and JPA are three different mechanisms for persisting data in a relational database. Each has its own advantages and limitations. iBATIS does not provide a complete ORM solution, and does not provide any direct mapping of objects and relational models. However, iBATIS provides you with complete control over queries. Hibernate provides a complete ORM solution, but offers you no control over the queries. Hibernate is very popular and a large and active community provides support for new users. JPA also provides a complete ORM solution, and provides support for object-oriented programming features like inheritance and polymorphism, but its performance depends on the persistence provider.

The choice of a particular persistence mechanism is a matter of weighing all of the features discussed in the comparison section of this article. For most developers the decision will be made based on whether you require complete control over SQL for your application, need to auto-generate SQL, or just want an easy-to-program complete ORM solution.


Key Features: 
  • iBATIS
  1. Maps the ResultSet from JDBC API to your POJO Objets.
  2. Makes use of SQL which could be database dependent
  3. Works very well for stored procedures, works very well for reporting applications, etc
  4. Simpler, Faster development time
  5. Flexible
  6. Enables the data model and the object model to be independent of each other.
  • Hibernate:
  1. Maps your Java POJO objects to the Database tables
  2. Makes use of HQL which is relatively independent of databases and it is easier to change db in Hibernate.
  3. If you are using stored procedures, well you can do it in Hibernate but it is little difficult in comparison of iBATIS
  4. Generates SQL for you which means you don't spend time on SQL
  5. Provides much more advance cache
  6. Highly scalable
  7. HQL also supports many advanced features of pagination and dynamic profiling that SQL has never supported.
  • JPA:
  1. JPA uses metadata annotations and/or XML descriptor files to configure the mapping between Java objects in the application domain and tables in the relational database.
  2. Defines a SQL-like query language, JPQL (Java Persistence Query Language), which is different from EJB-QL (EJB Query Language), the language used by entity beans.
  3. Is the standard object-relational mapping and persistence management interface for the Java EE 5 platform
  4. Entity Class Annotation (@Entity, @Table, @Column, @NamedQuery)
  5. JPA also supports SQL through the createNativeQuery() method of the EntityManager.
  6. Hibernate is one of the most popular frameworks that implements JPA.

When TO/NOT TO Use:
  • Use iBATIS if:
  1. You need complete control of the SQL or the SQL queries need to be fine-tuned.
  2. your environment is driven by relational data model.
  3. you have to work existing and complex schema's.
  • Use Hibernate if:
    1. Your environment is driven by object model and wants generates SQL automatically.
  • Not to use JPA :
  1. Caching, which is not clearly defined in JPA but is well supported by Hibernate.
  2. JPA is defined to work with relational databases only. If your persistence solution needs to be extended to other types of data stores, like XML databases, then JPA is not the answer to your persistence problem.

Persistence solutions compared

FeaturesiBATISHibernateJPA
SimplicityBestGoodGood
Complete ORM solutionAverageBestBest
Adaptability to data model changesGoodAverageAverage
ComplexityBestAverageAverage
Dependence on SQLGoodAverageAverage
PerformanceBestBestN/A *
Portability across different relational databasesAverageBestN/A *
Portability to non-Java platformsBestGoodNot Supported
Community support and documentationAverageGoodGood
* The features supported by JPA are dependent on the persistence provider and the end result may vary accordingly.




Thursday, July 09, 2015

Web ٍٍServices Development Patterns

Which approach is best for you?
Web services have become a standard way of implementing Service Oriented Architectures. Developers have used many patterns of developing these Web services, but these patterns have not been well-defined or discussed. This article describes these development patterns and discusses their advantages and disadvantages in terms of tooling support and results. The analysis is based on real-world experience in developing customer solutions.

Since a WSDL document is so important, the development patterns described in this article center around how WSDL documents are created and manipulated. Once a WSDL document is created, you can use Web service development tools to help you generate the necessary deploy-time and run-time artifacts defined by JAX-RPC. Keep in mind that the WSDL document is the key to Web services development, this article considers WSDL the top level of development because it is a meta-language that describes an interface in abstract, implementation-independent terms. Code is considered the bottom level of development because it can be mostly generated, deployed and executed. Given this terminology, this article identifies and describes three development patterns:
  1. Bottom-up pattern: Start with Java to produce WSDL.
  2. Top-down pattern: Start with WSDL to produce Java.
  3. Round-trip pattern: Start with WSDL to produce Java, which is then used to produce WSDL, which is then used to produce Java.

These patterns are described in the following sections, including the advantages and disadvantages of each. The advantages and disadvantages are derived from experience in developing actual customer solutions involving business integration and modernization.

Conclusion
Developers have been implementing Web services for some time now, but few have practiced rigorous development approaches. This article described three development patterns that you can use to develop Web services based on the currently available tools.
The bottom-up pattern is the best approach for exposing existing function as a Web service. The top-down pattern offers the most flexibility and reusability, and is rapidly approaching the status of a best practice when developing new Web services. The round-trip pattern can be used as an aide when one of the better methods cannot be used. However, based on our observations in actual customer engagements, our recommendation is to start with a top-down approach to guarantee the best standards-based and evolving interface. Use a bottom-up approach secondarily if existing function needs to be quickly exposed. Finally, avoid round-trip approaches altogether due to the problems with the inconsistencies and development drawbacks in the approach.

Web ٍٍServices Round-trip development

The two primary methods of Web services development are top-down and bottom-up. Some developers have also used a third method, primarily because of shortcomings or defects in tools, and a lack of thorough understanding of Web services tools and technologies. In what is called round-trip development, the developer uses part of the top-down process followed by parts of the bottom-up process. First, Steps 1-3a of the top-down method are used, primarily to produce the so-called DTOs (possibly based on standards-based XSDs). The DTOs are used in the interface of a POJO or EJB, which is created manually, offering public methods corresponding to the portType operations defined in the WSDL document. Then, Steps 2-4 of the bottom-up method are used. Step 3b from top-down is skipped because the WSDL from Step 3 of bottom-up is used for the client-side.

  • Evaluation of the round-trip approach
The advantages of the round-trip approach are:
The primary advantage of the approach is that it you can use it to circumvent tooling problems, or to compensate for insufficient knowledge of Web services tools and technologies. This approach allows customization of an existing schema and Web service via code changes rather than schema changes. You can also use it if the tooling does not support implementation of the service in the desired form, such as an EJB.

The disadvantages of the round-trip approach are:
Some Java base types do not round-trip to schema types very well, which can cause additional rework.
The additional steps required for round-trip unnecessarily complicate the development process.
The WSDL produced is much less reusable than the original WSDL and its imported schema.
The namespaces of the data types from the original WSDL and the final output WSDL may become different because of the namespace to package mapping and package to namespace mapping. This must be carefully managed by the server-side developer.

Web ٍٍServices Top-down development

In top-down development, both client-side and server-side developers use WSDL (the top) to produce the artifacts (the bottom) necessary for their respective environments. Top-down development is an increasingly common practice for at least two important reasons. First, in many cases, the WSDL describing a service is available publicly in some registry (like a UDDI). With the tools available today, the server-side developer can start with the WSDL to define new implementations of the portType defined by the WSDL, and the client-side developer can start with the same WSDL to develop a client of the service. Second and even more important is the industry trend towards defining interoperable data standards using XML Schema Definitions (XSD). These industry standard data types defined using XSDs can be ideal for defining new Web services interfaces. Therefore, the top-down development pattern starts by identifying or developing XML schema relevant to the domain of the Web service, and then creating a WSDL for the Web service. Development of both the client and server side can then begin in parallel. The top-down development pattern encompasses the following development steps :
  1. 1.     Identify or create an XML schema relevant to the problem domain that describes the input and output data types for Web services operations. The data types should be defined in one or more schema (.xsd) files. You can use standard schema development tools to create or modify the necessary schema. 
    2.     Create a new WSDL file that contains a types element that imports (not includes) the schema files from Step 1 and contains a portType that in turn contains operation elements referencing the data types defined in the imported schema as input and output parameters. The recommended style for creating this WSDL is wrapped-document literal to be WS-I compliant and for maximum interoperability with .NET environments. Sophisticated enterprise application development tools like the WebSphere Studio family include WSDL editors that provide tremendous assistance when creating WSDL documents.
    3.     Generate the provider-side and requester-side JAX-RPC artifacts. Note that these steps, described below, can be done in parallel by two different and independent teams. The implementation platform on each side can also be different.
    3.1. Use a Web services tool to generate the provider-side artifacts. A spectrum of tools exists, ranging from the command line driven WSDL2Java from Apache Axis or WebSphere Application Server to the Web service wizard in the WebSphere Studio family. The tools generate a Java class (a DTO) for every complex type defined in the WSDL types element. They also generate either a POJO or a stateless session EJB skeleton service implementation that has a method for each operation included in the portType. The tools may also generate any other provider-side artifacts required by JAX-RPC to deploy the implementation as a Web service in an application server. Examples of these artifacts include the webservices.xml file. There may also be other application server dependent metadata files generated by the tools. After running the tool, the serer-side developer must implement the appropriate business logic to fulfill the semantics of the operations in the service definition. 
    3.2.    Use a Web services tool to generate the DTOs, SEI, and client stub implementation for the service requester from the WSDL. This procedure is exactly the same as Step 4 in the bottom-up pattern described above. As before, the client-side developer must use the stub to invoke the service from the client-side business logic. 


  • Evaluation of the top-down approach

The advantages of the top-down approach are:
It supports the use of existing standards-based XSD types. See Listings 4 and 5 above for an example.
When new schema types are developed for the current service, they can be easily reused for other services by simply importing the newly developed XSD into the other services.
It allows for parallel and independent development of client-side and server-side.
Incremental changes to the service are best managed by changing the WSDL itself. Since the WSDL is the common interface (or contract) for both the client-side and server-side, these changes can be easily managed so they don't affect interoperability with existing requesters or providers.
The tools will use the namespaces defined in the WSDL to determine the package names of the generated JavaBeans (or DTOs). Most of the tools support namespace to package name mappings. The advantage with starting from WSDL is that both the client-side and server-side can use different package name mappings without affecting the access of the service.

The disadvantages of the top-down approach are:
It requires knowledge of WSDL and XSD because both must be manually generated or manipulated. Even the sophisticated tools that exist today to generate WSDL and XSD require detailed knowledge of the structure of WSDL and XSD to ensure proper compliance with standards and optimal performance.

Tools support for the top-down approach has generally been more limited than the support for bottom-up, but that support is improving. For example, many tools do not properly handle WSDL files that import schemas instead of embedding them; and fully automated support for producing wrapped-document literal WSDL is lacking. The most common problem with importing schemas is that the XSDs must exist in the same directory as the WSDL file and relative path names don't always work.
It's important to note that you can use the bottom-up process to produce the WSDL that drives the top-down process. For example, you can create the WSDL published in a UDDI registry using the bottom-up process. We recommend that when doing this, you use tools to separate the schema in the WSDL types element from the rest of the definition so the schema can be reused. The key point in any top-down approach is that once the WSDL is produced (either manually or generated from code), it becomes the master interface that is used by both the requester and provider from that point on.

Web ٍٍServices Bottom-up development

The first generation of Web services tools for Java was targeted at exposing existing code as Web services. This approach is called bottom-up because the starting point is code that is being abstracted into an interface definition and subsequently exposed as a Web service implementing that interface. This pattern is familiar to many Web services practitioners and is well-supported by even the latest generations of Web services tools. The bottom-up development pattern encompasses the following development steps:-
  1. Identify or create JavaBeans that represent the data types of the input and output parameters of a service interface. These can be existing or new JavaBeans. Because these JavaBeans are used to transfer data to and from the service, they are sometimes termed Data Transfer Objects (DTOs). Note that only the attributes that follow the JavaBean pattern (such attributes have a getter method and a setter method) are exposed in the Web service interface. You can use standard Java development tools to create or modify the required JavaBeans. 
  2. Identify or create a Java class, either a Plain Old Java Object (POJO) or a Stateless Session EJB, that becomes the Web service implementation. The Java class must include the methods to be exposed in the Web service interface. These methods must use the DTOs from Step 1 as the input and output arguments. Note that the methods implementing the business logic exposed in the Web service must be marked as public. Again, you can use standard Java development tools to create or modify the Java class, as necessary. This class does not have to adhere to the rules for a JavaBean. The class may throw any exceptions in the exposed methods, as necessary.
  3. Use a Web services tool to generate the Web service implementation from the Java class. There are several candidate tools of varying levels of sophistication, in that they may produce all or only some of the artifacts required by JAX-RPC to deploy and use the Web service. These tools all generate a WSDL document based on the signature of the Java class from Step 2. The tools create a complex type definition embedded in the WSDL types element for each data type (JavaBean) used in the public methods in the Java class. They also create an operation element in the portType for each public method in the Java class. The tools may also generate any other provider-side artifacts required to deploy the implementation as a Web service in an application server.
  4. Use a Web services tool to generate the artifacts for the Web service requester using the WSDL generated in Step 3. The tools generate a Java class (DTO) for every complex type defined in the WSDL types element, a service endpoint interface (SEI) that has a method for each operation included in the portType, and a stub that implements the SEI that a client can use to send requests to and receive responses from a Web service implementation. The tools may generate other artifacts, depending on the nature of the requester (J2EE container or not) and the tool itself. The same tools that generate the provider implementation will typically have a requester version as well. Therefore, the same range of tools exists from the command line driven WSDL2Java from Apache Axis or Application Server to the Web service wizard in the WebSphere Studio Application Developer. 

  • Evaluation of the bottom-up approach

The advantages of the bottom-up approach are:
It is a quick way to expose legacy implementations as Web services.
It requires little or no knowledge of WSDL or XML because the WSDL document is generated by the tools.
It has excellent tools support. In fact the sophisticated tools do all the work to create a deployable, executable Web service implementation on the provider side and all the work to allow a request to access the implementation on the requester side.

The disadvantages of the bottom-up approach are:
The generated schema defining the data types in the WSDL document derives only from the Java classes from the provider's environment and not from any standards-based schema (see Listing 3 above).
The provider-side data types may not be simple DTOs, in that they include additional business logic. Such logic can't be reconstructed on the requester side.
The generated schema is embedded in the WSDL, which makes reuse of the schema, perhaps in the definition of other Web services, more difficult. It is possible, of course, to extract the schema from the original WSDL document.
The development of the server-side Web service implementation and the client-side Web service requester can't proceed in parallel. The server-side skeleton and DTOs have to be developed before a WSDL can be generated that can be used to generate the client-side stubs and DTOs.
Incremental changes to the interface are more difficult to manage. For example, if the interface of the class that implements the service is changed and the WSDL is regenerated, more significant changes could occur in the WSDL, thus causing interoperability with existing clients to fail. The basic problem is that, on the server-side, the class implementing the service is deemed the master interface and, on the client-side, the WSDL provided by the server-side is the master interface. These two different masters can cause the interfaces to become out of sync and difficult to debug and fix.
The namespaces of the embedded schema types are typically generated from the Java package names of the server-side JavaBeans. Therefore, if the package names are changed, the namespace will be changed, which means the types are no longer compatible. Most of the tools allow a package to namespace mapping, but this must be explicitly set during the execution of the tool.


Sunday, June 21, 2015

Web Service Life-cycle


  1. A web service provider creates and deploys a web service.
  2. A web service consists of a service or application function and the web service infrastructure that make it accessible to remote clients.
  3. The web service provider then publish information about a web service in a service registry or makes it available to client directly.
  4. Published information might include a description of the service, the service interface definition,and the service instance location. A service provider can also associate a service with a variety of taxonomies or classification schemas to facilitate locating service that satisfy a particular criteria. Alternatively, the provider can place the service in accessible location and provide instructions for accessing the service directly to any potential requests.
  5. Web service requests search a service registry or some well-known location for service that meet their needs. If using a service registry, the requester could use a query mechanism provided by registry browser.
  6. After locating an appropriate service, a service requester retrieves information about the service, such as the service location and interface description.
  7. The web service requester creates a web service client.
  8. A web service client invokes the web service at the location specified in the service description, passing the required parameters cin a XML-based message. The service executes using the parameters contained in the incoming message, and returns the processing results to the client in an XML-based response message. Both the client and the service components contains logic to generate and process the XML-based messages. 



Wednesday, February 11, 2015

What do “branch”, “tag” and “trunk” mean in SVN repositories?

I know I come after the battle, but I still would like to present my view of those concepts (under a community owned answer so I am not here for the karma ;)
  • Trunk:
The main development area. This is where your next major release of the code lives, and generally has all the newest features.
The trunk directory contains the most current, approved, and merged body of work. Contrary to what many have confessed, my trunk is only for clean, neat, approved work, and not a development area, but rather a release area.
At some given point in time when the trunk seems all ready to release, then it is tagged and released.
  • Branches:
Every time you release a major version, it gets a branch created. This allows you to do bug fixes and make a new release without having to release the newest - possibly unfinished or untested - features.
The branches directory contains experiments and ongoing work. Work under a branch stays there until is approved to be merged into the trunk. For me, this is the area where all the work is done.
For example: I can have an iteration-5 branch for a fifth round of development on the product, maybe a prototype-9 branch for a ninth round of experimenting, and so on.

  • Tags:
Every time you release a version (final release, release candidates (RC), and betas) you make a tag for it. This gives you a point-in-time copy of the code as it was at that state, allowing you to go back and reproduce any bugs if necessary in a past version, or re-release a past version exactly as it was. Branches and tags in SVN are lightweight - on the server, it does not make a full copy of the files, just a marker saying "these files were copied at this revision" that only takes up a few bytes. With this in mind, you should never be concerned about creating a tag for any released code. As I said earlier, tags are often omitted and instead, a changelog or other document clarifies the revision number when a release is made.
The tags directory contains snapshots of approved branches and trunk releases. Whenever a branch is approved to merge into the trunk, or a release is made of the trunk, a snapshot of the approved branch or trunk release is made under tags.







I suppose with tags I can jump back and forth through time to points interest quite easily.