JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

How to delete a cookie on server in a J2EE application

September 25, 2008 by Krishna Srinivasan Leave a Comment

There is no direct method offered by servlet API to delete a cookie on server side. This is how you can go about doing it.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3
  1. Loop through the cookies in the request object to locate the one that you want to delete.
    [code lang=”java”]for (Cookie cookie: request.getCookies()) {
    if (USER_COOKIE_NAME.equals(cookie.getName())) {
    return cookie;
    }
    }[/code]
  2. Set the maxAge property of the cookie to 0. This results in cookie expiring with immediate effect as soon as the client receives the response.
  3. Optionally, set the value property to empty string. This is not really required since the cookie is about to be expired. However, this adds a sense of a clean and complete erasure if the cookie being deleted carries some critical, secure data.
  4. Add this cookie to response. The cookie will be gone once the response is sent back to client!
    [code lang=”java”]view plaincopy to clipboardprint
    cookie.setMaxAge(0);
    cookie.setValue("");
    response.addCookie(cookie);[/code]

 

Filed Under: Java EE Tagged With: Servlets

New Features in JSP 2.0

September 19, 2008 by Krishna Srinivasan Leave a Comment

New Features in JSP 2.0

JSP 2.0 is released with new promises. JSP 2.0 is an upgrade to JSP 1.2 with several new and interesting features. These features makes the life of web application developers and designers easier.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

The JavaServer Pages 2.0 Specification is fully backwards compatible with version 1.2. JSP 2.0 allows the developer to write script-free code without without declarations, scriptlets and expressions.

JSP 2.0 is released with the objective of making the life of Developers easy. Here is the new features of JSP 2.0:

  • Simple Expression Language (EL)
  • JSP Fragments
  • Simple Tag Handlers
  • Easy tags creation with .tag files
  • Easy Header and Footer template using the prelude and coda includes

With JSP 2.0 web develop has become easily and it also helps easily maintaining dynamic Web pages. Despite the fact the word “Java” appears in JavaServer Pages, with JSP 2.0 the developer can develop pages without learning Java programming language. Learning and using the features of JSP 2.0 is also very easy.

JSP 2.0 Features description is given below:

Simple Expression Language(EL): Expression Language (EL), provides a way to simplify expressions in JSP. EL provides the ability to use run-time expressions outside JSP scripting elements. Scripting elements are those elements which is used to embed Java code inside the JSP file. Mostly it contains the logic of the program.

Scripting elements have three subforms:

  • Declaration: The variables and methods are declared inside declaration.
  • Scriptlets: The business logic of the program is written inside this.
  • Expressions: output will be displayed by the expression.

Expression Language can be enabled in scriptfree JSP pages:

  1. By using a page directive: We can enable EL by using
    [code lang=”xml”]
    <%@ page isScriptingEnabled="true|false" isEnabled="true|false"%>
    [/code]
  2. By using an element of the deployment descriptor:
    [code lang=”xml”]
    <jsp-config>
    <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <el-enabled>true</el-enabled>
    <scripting-enabled>true</scripting-enabled>
    </jsp-property-group>
    </jsp-config>
    [/code]

JSP Fragments: Jsp fragments is a new feature of JSP 2.0 which allows page author to create custom action fragments that can be invoked. The JSP fragments allows a portion of Jsp code to be encapsulated into a Java object that can be passed around and evaluated zero or more times. Methods for creating a JSP fragment:

  1. Providing the body of a :

    [code lang=”xml”]
    <% attribute name="attributeName" fragment="true">
    [/code]

  2. Providing the body of a tag invocation

Simple Tag Handlers:
Easy tags creation with .tag files: With the introduction of JSP 2.0, knowledge of Java is no longer a prerequisite to create a custom tag action. Easy Header and Footer template using the prelude and coda includes. With JSP 2.0 web development has become easy and it also helps in maintaining dynamic web pages easily. To learn JSP 2.0 there is no need to learn java.

Filed Under: Java EE Tagged With: JSP 2.0

Servlet Life Cycle

August 1, 2008 by Krishna Srinivasan Leave a Comment

Before start writing the servlet, it is important to know the life cylce of every servlet instance created. Read What is Servlet? tips to know about the servlet basics.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

Servlet Life Cycle Methods

The following are the life cycle methods of a servlet instance:

  • init()
  • service()
  • destroy()

We will look into the each method in detail.

init()

This method is called once for a servlet instance. When first time servlet is called, servlet container creates instance of that servlet and loaded into the memory. Future requests will be served by the same instance without creating the new instance. Servlet by default multithreaded application.init() method is used for inilializing servlet variables which are required to be passed from the deployment descriptor web.xml. ServletConfig is passed as the parameter to init() method which stores all the values configured in the web.xml. It is more convenient way to initialize the servlet.

service()

This method is called for the each request. This is the entry point for the every servlet request and here we have to write our businesslogic or any other processes. This method takes HttpServletRequest and HttpServletresponse as the parameters. It is not mandatory to write this method, normally developers are interested in writing doGet() or doPost() methods which is by default called from theservice() method. If you override service(), it is your reponsibility to call the appropriate methods. If you are not overridden the service() method, based on the types of the request the methods will be called.

destroy()

This method will be called once for a instance. It is used for releasing any resources used by the servlet instance. Most of the times it could be database connections, Fill IO operations, etc. destroy() is called by the container when it is removing the instance from the servlet container.Servlet instance is deleted or garbage collected by the container only when the web server issues shut down or the instance is not used for a long time.

Single Thread Model

Although it is standard to have one servlet instance per registered servlet name, it is possible for a servlet to elect instead to have a pool of instances created for each of its names, all sharing the duty of handling requests. Such servlets indicate this desire by implementing the javax.servlet.SingleThreadModel interface. This is an empty, tag interface that defines no methods or variables and serves only to flag the servlet as wanting the alternate life cycle. A server that loads a SingleThreadModel servlet must guarantee, according to the Servlet API documentation, “that no two threads will execute concurrently the service method of that servlet.

Filed Under: Java EE Tagged With: Servlets

New Features in Servlet 3.0

July 31, 2008 by Krishna Srinivasan Leave a Comment

Servlet 3.0

The next version for servlet technology is Servlet 3.0, which is planned to be released with JEE 6.0in the last quarter of 2008. After the release of servlet 2.5 in spetember 2005, this is the new version with many new features included. Servlet 2.5 is released with JEE 5.0. Servlet 3.0 is maintained by the JSR 315. It is already submitted to the sun and started working on completing the specification.Expected to be released in the later part of 2008.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

There is many site already discussing about the new features will be introduced in the servlet 3.0 specification. This tips will give you an basic idea on list of features in the specification. We will not lookinto details of the each feature. Used JSR 315 as the reference documentation to write this tips. The following are the list of new features in servlet 3.0 specification request.

Web framework pluggability

  • Almost all of the Java based web frameworks build on top of servlets. Most web frameworks today plugin either through servlets or through web.xml. Annotations to define some of the servlets, listeners, filters will help in making this possible. Programatic access to web.xml and dynamic changes to configuration of a webapp are desired features. This JSR will aim to provide the ability to seamlessly plugin different web frameworks into web appplications

EOD

  • Annotations – use of annotations for the declarative style of programming
  • As part of the EoD effort the goal is to have zero configuration for web applications. The deployment descriptors would be used to override configuration
  • Generics – Use generics in the API where possible
  • Use of other language enhancements where possible to improve the usability of the API

Async and Comet support

  • Non-blocking input – The ability to receive data from a client without blocking if the data is slow arriving
  • Non-blocking output – The ability to send data to a client without blocking if the client or network is slow
  • Delay request handling – The comet style of Ajax web application can require that a request handling is delayed until either a timeout or an event has occurred. Delaying request handling is also useful if a remote/slow resource must be obtained before servicing the request or if access to a specific resource needs to be throttled to prevent too many simultaneous accesses
  • Delay response close – The comet style of Ajax web application can require that a response is held open to allow additional data to be sent when asynchronous events occur
  • Blocking – Non-blocking notification – The ability to notify push blocking or non-blocking events. Channels concept – The ability to subscribe to a channel and get asyncronous events from that channel. This implies being able to create, subscribe, unsubscribe and also apply some security restriction on who can join and who cannot

Security

  • Ability to login / logout
  • Self registration

Alignment

  • Alignment / requirements from REST JSR (JSR 311)
  • Alignment / requirements from JSF 2.0 JSR

Misc

  • Better welcome file support
  • ServletContextListener ordering
  • Container wide definition for init params
  • File upload – progress listener – where to store interim and final file
  • Clarifications of thread-safety issues

Filed Under: Java EE Tagged With: Servlets

What is servlet?

July 31, 2008 by Krishna Srinivasan Leave a Comment

Java Servlets

Java Servlet is the serverside Java programming language. We can say it as serverside applet. How applet is used for writing the client side code, servlet is used for writing the serverside programming language. Servlet programming is first created by Sun Microsystems in June 1997. The latest version is Servlet2.5 which is released with JEE 5.0specification. Servlet is a specification and it can be implemented by anyone who can fulfil the mandatory requirements of the specification maintained by Sun.

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

The following are the servlet version released in the past:

  • Servlet 3.0 – planned for next release
  • Servlet 2.6 – September 2005
  • Servlet 2.4 – November 2003
  • Servlet 2.3 – August 2001
  • Servlet 2.2 – August 1999
  • Servlet 2.1 – November 1998
  • Servlet 2.0 – 1997
  • Servlet 1.0 – June 1997

Tomcat is the reference implementation for the servlet. Reference Implementation(RI) means Apache Tomcat implements all the details in the servlet specification and creates a fully complaint servlet container. That can be used for
hosting and running the servlet application. Tomcat is maintained by the opensource foundation Apache. It is free and anyone can use for their project without buying the license. A Servlet container is a specialized web server that supports Servlet execution. It combines the basic functionality of a web server with certain Java/Servlet specific optimizations and extensions – such as an integrated Java runtime environment, and the ability to automatically translate specific URLs into Servlet requests.

The following are the few popular webserver and application server vendors:

  • Apache Tomcat
  • BEA Weblogic
  • IBM Websphere
  • Oracle
  • JBoss

Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http.Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language.

Filed Under: Java EE Tagged With: Servlets

EJB 3.0 and WebServices

July 24, 2008 by Krishna Srinivasan Leave a Comment

This article discusses how an enterprise bean can act as a Web-Service component. Since Web-Services itself is a vast technology, the first part of the article discusses more about Web-Services. Specifically, the first part of the article discusses what Web-Services are, its unique features among other related technologies, its architecture, and the various base components upon which Web- Services are built. The second part of the article describes the JSR-181 which is the “Web-Services Meta-data for the Java Platform” and how enterprise beans can make use of the API’s available under this JSR to expose themselves as Web-Services components.

also read:

  • Java EE Tutorials
  • EJB Interview Questions
  • EJB 3 Web Services
  • Annotation and Dependency Injection in EJB 3
  • Query API in EJB 3

Web Services-Introduction

Normally a Service represents any kind of feature or some piece of functionality that a specific kind of client can be benefited from. Say for a printer service, the clients are either the applications or the programs using the printers or users. Consumers of an ATM service are Bank Customers, like-wise the list of real-world services goes on.

Like these kinds of service, a Web-Service is a kind of remote service that is available in the web and it can be accessed through some standard protocols. A Web-Service can be imagined as a program that is running in a remote machine, usually guarded by a server, so that it can be made accessible by remote clients. How Web-Services are very different from the existing technologies is that, Web-Services have some unique features that are very uncommon to other existing technologies. The clients for these Web-Services can be any one, it can be a user or HTML browser, or even another Web-Service.

Features of Web Services

Following are the unique features of a Web-Service based application.

  • Language Independent
  • Operating System Independent

Language Independent

Let us assume that a Web-Service is running in a remote machine. Suppose an application (can be a Web-Service also) want to gain the functionality of the Web-Service by accessing it. It is not that both the Web-Service and the client application must be built in the same language or technology. They can be different. From this, we can infer that a Web-Service can be built in Java, running in some remote machine and the client of the Web-Service can be a legacy C++ application or a DotNET application.

Communication between Web-Service and heterogeneous clients

From the above diagram, we can see that 3 different applications (built on 3 different technologies) are accessing the same Web-Service.

Operating System Independent

Web-Services are independent of operating systems. This implies that the Web-Service and its consumer can be running in different operating systems. It means that an application running in Unix operating system can access a Web-Service that is running in Windows OS. This is possible, because of the fact that, Web-Services have their specifications defined by W3C and vendors who are providing implementations for the various Web-Services standards are bound to follow the specifications.

[W3C, which stands for World Wide Web Consortium, is a group of companies for proposing and defining some standards for World Wide Web (W3). A whole bunch of Internet standards have been given by W3C till now. Major standards include HTML, XHTML, XML, SOAP, and WSDL…]

Comparison with Other Technologies

If we have a broader look over Web-Services, it is nothing but a distributed computing enabling integration between applications. So many distributing computing standards are there till date and each of them have their own set of limitations. Some of the popular distributing computing technologies include COM-DCOM from Microsoft, Java’s RMI and EJB and Object Managements’ Group CORBA. Each of the above-mentioned technologies seriously suffered from issues like portability, platform-dependency, etc.,

Considering the effort taken by Microsoft to give a common solution to Distributed computing is that both COM (Component Object Model) and DCOM (Distributed Component Object Model) technologies allowed Component based software model development and the components can only be written in a language like VB, VC++ or any Microsoft’s compliant language. Therefore, components written in VB and VC++ can communicate with each other and this doesn’t seem to promote language independency. Another issue is that these COM and DCOM technologies are available only in Operating systems like Windows 98, XP and 2000.

Sun’s Remote Method Invocation, through the support of Java Remote Method Protocol (JRMP) , though is operating system independent (as Java code can be written only once and can be run anywhere as long as a JVM is installed in the target operating system), lacked the same issue of language independency. Both RMI enabled servers and clients should only be written in Java. Outside languages are prohibited to take the advantage of this distributed computing. Though, EJB has support to integrate well with other technologies like DotNet, it hasn’t become very popular, as providing integration of a J2EE Component with other technologies, for sure, will lose the efficiency of portability of the applications in other platforms.

In comparison with the other two technologies, CORBA almost eliminated all the serious issues by providing a language independent and a platform independent framework. It means that in a distributed application, a C++ Server can talk to a Java Client and vice versa. Though this looks good from the outside view, there are other issues like maintaining a heavy middle-ware between the client and the server called Object Adapter and Object Broker, which does the job of locating and loading servers, creating server objects on behalf of clients etc., which made it to prevent from being a successful technology.

Web Services Architecture

A Web Service is not a single technology but it is a combination of several other technologies like

  • SOAP
  • WSDL
  • UDDI

Following sections cover these technologies in greater depth.

SOAP

For establishing communication between heterogeneous systems for exchange of data, we have to adhere to some set of standards in the form of protocols. Distributed computing technologies likeDCOM, CORBA, and RMIetc. have their own proprietary protocols. For example, CORBA usesIIOP (Internet Inter-ORB Protocol) as the standard protocol for communication, DCOMuses ORPC(Object Remote Procedure Call) and Java’s RMIused JRMP(Java Remote Method Protocol). Similarly,Web-Services uses SOAP(Simple Object Access Protocol) as the standard protocol for transferring data between applications. SOAP is an XML based protocolfor packing messages in XML format. Since SOAP is using XML to transfer data/messages between applications, it provides a lighter mechanism and that’s the reason why most of the Web-Services applications use SOAP over HTTPas the standard transport protocol for exchanging messages over the Internet, although Web-Services can easily mingle with any type of compliant protocols.

SOAP Specification

SOAP which is the standard protocol for Web-Services, is actually a standard given by W3C (World Wide-Web Consortium) Group.  The following section discusses the structure of  SOAP messages in greater detail.

The SOAP message

Communication between two heterogeneous systems using Web-Services can be achieved with the help of SOAP protocol by sending and receiving SOAP messages. A client construct a SOAP message, which is an XML based message with appropriate XML schema (http://schemas.xmlsoap.org/soap/envelope/) and sending the message as a request message to the processing application. The processing application (which is usually a Web-Service) unpacks the message, performs the requested operation and returns the result back to the calling application in the form of SOAP response message.

Structure of a SOAP message

The SOAP message consists of the following parts namely, the Envelope, Headerand the Body. Following diagram shows how a SOAP message looks like,

Envelope

From the above picture, one can infer that the Envelopeforms the outer-most structure in a SOAP message and it acts as a container for both the Headerand the BodyEntries. The Envelope therefore forms a mandatory part in the SOAP message. Envelope doesn’t contain any of the data to be transmitted to the receiving application, but still it may contain the necessary meta-data of the sending and the receiving applications.

Following is how the envelope looks like in XML format,

[code lang="xml"]

&amp;lt;Soap:Envelope

xmlns:Soap="&amp;lt;a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;http://schemas.xmlsoap.org/soap/envelope/&amp;lt;/a&amp;gt;"&amp;gt;

….

&amp;lt;/ Soap:Envelope&amp;gt;

[/code]

As we can see, the above Soap envelope declaration references the name-spacefrom ‘http://schemas.xmlsoap.org/soap/envelope’. See more about name-spacesbelow. The name of the envelope element is ‘Envelope’ and the fully-qualified name (element name along with namespace prefix) isSoap:Envelope, where Soap is the namespace prefix.

[XML Namespaces – XML Namespaces are a way to avoid name collisions that may occur in the elements and attributes that are found in a XML document. Consider a situation where we want to represent a television monitor and a computer monitor in a XML file. Following may be one kind of representation for this,

[code lang="xml"]

&amp;lt;items&amp;gt;

...

&amp;lt;television&amp;gt;

&amp;lt;monitor inch=’14’/&amp;gt;

&amp;lt;/television&amp;gt;

&amp;lt;computer&amp;gt;

&amp;lt;monitor inch = ‘11’/&amp;gt;

&amp;lt;/computer&amp;gt;

...

&amp;lt;/items&amp;gt;

[/code]

In the above simple example, we have two monitor elements within television and computer elements both sharing the common name(‘monitor’). It may happen for the processing applications to spend a good deal of time, to find whether the parsed ‘monitor’ element belong to television or computer element by analyzing its root element. Situations may go even worse if both the monitor elements are at the same level.

So, to avoid these kinds of naming collisions within an XML document, XML namespaces were introduced. A namespace represents a collection of names and no two names within the namespace can be the same. Following represents the syntax to define a namespace in a XML document, xmlns:prefixId=’NamespaceIdentifer’.

The above syntax has 3 entities, namely the keyword name ‘xmlns’ (which stands for XML Namespace), the prefix which serves as a short-hand representation for the NamespaceIdentifier. Any kind of string can be given for NameSpaceIdentifer, but the preferred way is to give URL’s as no two URL’s in the world can be unique.

Now these namespace definitions have to be applied to the elements in such a way that the element’s name have to be prefixed with the prefix that we have already declared in the namespace definition.

[code lang="xml"]

&amp;lt;tele:television xmlns:tele=’http://www.mytelevisions.com’&amp;gt;

&amp;lt;tele:monitor inch=’14’/&amp;gt;

&amp;lt;/tele:television&amp;gt;

[/code]

The above modified element declared can be interpreted like this, a namespace called “http://www.mytelevisions.com” is created and it is given a prefix ‘tele’, After this all the elements within the television element are made namespace-aware by prefixing them with ‘tele’.

Now, the revised XML document will look similar to this,

[code lang="xml"]

&amp;lt;items&amp;gt;

...

&amp;lt;tele:television xmlns:tele=’http://www.mytelevisions.com’&amp;gt;

&amp;lt;tele:monitor inch=’14’/&amp;gt;

&amp;lt;/tele:television&amp;gt;

&amp;lt;comp:computer xmlns:tele=’http://www.mycomputers.com’&amp;gt;

&amp;lt;comp:monitor inch = ‘11’/&amp;gt;

&amp;lt;/comp:compuer&amp;gt;

...

&amp;lt;/items&amp;gt;]

[/code]

Header

The next optional element in the SOAP Envelope is the headerelement. If present, the element comes immediately after the Envelopeelement. The XML representation for the Headerelement looks like the following,

[code lang="xml"]

&amp;lt;Soap:Envelope

xmlns:Soap="&amp;lt;a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;http://schemas.xmlsoap.org/soap/envelope/&amp;lt;/a&amp;gt;"&amp;gt;

&amp;lt;Soap:Header&amp;gt;

…

&amp;lt;/Soap:Header&amp;gt;

&amp;lt;Soap:Header&amp;gt;

…

&amp;lt;/Soap:Header&amp;gt;

&amp;lt;/Soap:Envelope&amp;gt;

[/code]

Any number of header elements can appear after the Envelopeelement. The Headerelement is used to provide some meaningful information to the receiving application. For example, a sender application can include the language and the currency information as part of the header information like this,

[code lang="xml"]

&amp;lt;Soap:Envelope

xmlns:Soap="&amp;lt;a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;http://schemas.xmlsoap.org/soap/envelope/&amp;lt;/a&amp;gt;"&amp;gt;

...

&amp;lt;Soap:Header&amp;gt;

&amp;lt;language&amp;gt;English&amp;lt;/language&amp;gt;

&amp;lt;/Soap:Header&amp;gt;

&amp;lt;Soap:Header&amp;gt;

&amp;lt;currency&amp;gt;INR&amp;lt;/currency&amp;gt;

&amp;lt;/Soap:Header&amp;gt;

...

&amp;lt;/Soap:Envelope&amp;gt;
[/code]

Body

Unlike the optional header element, Bodyelement is mandatory as it includes that actual data to be sent to the receiving application. The bodyelement immediately follows the Envelope element -if there is no Header element, or it comes after the Header element.

[code lang="xml"]

&amp;lt; Soap:Envelope

xmlns:Soap="&amp;lt;a href="http://web.archive.org/web/20080116132738/http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;http://schemas.xmlsoap.org/soap/envelope/&amp;lt;/a&amp;gt;"&amp;gt;

&amp;lt;Soap:Header&amp;gt;

&amp;lt;language&amp;gt;English&amp;lt;/language&amp;gt;

&amp;lt;/Soap:Header&amp;gt;

&amp;lt;Soap:Body xmlns:MyData=”http://mydata.com”&amp;gt;

&amp;lt;MyData:MyPersonalData&amp;gt;

&amp;lt;MyData:Name&amp;gt;MyName&amp;lt;/MyData:Name&amp;gt;

&amp;lt;MyData:Age&amp;gt;MyAge&amp;lt;/MyData:Age&amp;gt;

&amp;lt;/MyData:MyPersonalData&amp;gt;

&amp;lt;/Soap:Body&amp;gt;

&amp;lt;/Soap:Envelope&amp;gt;

[/code]

Note that in the above XML, a namespace called “http://mydata.com” is referenced and all the elements within the body like ‘MyPersonalData’, ‘Name’ and ‘Age’ are fully qualified as ‘MyData:MyPersonalData’, ‘MyData:Name’and ‘MyData:Age’ respectively.

SOAP messages with Attachments

In many of the situations SOAP messages alone cannot be sufficient for data transmission between applications as a SOAP message can hold only textual representation of data. Say, an XML message can only hold a Customer Name, an Employee Id, or a Cricket Score. It cannot hold binary information like images, audio files or video files. In such a case, SOAP XML messages cannot always best represent the whole set of real-world data. To get rid-off the lacking functionality with SOAP, came the specification from W3C called “Soap Messages with Attachments”.

One can identify from the name that SOAP messages with Attachments are extensions to SOAP messages in that it can hold not only textual data (in the form of XML) but also other types of messages (like audio files, image files etc.,). Logically, SOAP messages with attachments can two different parts (or sections) namelySOAP Partand the Attachment Part, which is illustrated in the following diagram.

SOAP Implementation

Different vendors have given implementation for the specification of SOAP given by W3C. Popular SOAP implementation (or products) includes, SAAJ(SOAP withAttachments API for Java) from Java, IBM’s SOAP4J(SOAP for Java) and Microsoft’s SOAP Toolkit. The following section presents a sample application for constructing a SOAP message using the SAAJ API.

Sample Application

With the above basics like SOAP messages and attachments in mind, let us write a sample SOAP application in Java usingSAAJ API. SAAJ, which stands for SOAP with Attachments API for Java, can be used to send XML messages along with Attachments between two applications. The entire API needed for sending and receiving SOAP messages are available injavax.xml.soap.

Let us use the API to construct a sample SOAP message. Though the API provides rich features like constructing, sending and receiving SOAP messages, this sample is limited in showing the construction of SOAP messages only. Listing shows the code to construct the SOAP message using the SAAJ API.

[code lang="java"]

SoapMessageConstruction.java:

package test;

import javax.xml.namespace.QName;

import javax.xml.soap.*;

public class SoapMessageConstruction {

public SoapMessageConstruction() {

}

public void construct(){

try{

MessageFactory messageFactory = MessageFactory.newInstance();

SOAPMessage message = messageFactory.createMessage();

// Add header entries here.

SOAPHeader soapHeader = message.getSOAPHeader();

// Application name header.

QName qNameForAppName = new QName("http://myApp.com", "Bank-Name", "app");

SOAPHeaderElement headerForAppName = soapHeader.addHeaderElement(qNameForAppName);

headerForAppName.addTextNode("ICICI Bank");

// Currency header.

QName qNameForCurrency = new QName("http://myApp.com", "Currency", "app");

SOAPHeaderElement headerForCurrency = soapHeader.addHeaderElement(qNameForCurrency);

headerForCurrency.addTextNode("INR");

// The SOAP part of the message.

SOAPPart soapPart = message.getSOAPPart();

SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

SOAPBody soapBody = soapEnvelope.getBody();

QName qNameForAccNo = new QName("http://myBank.com", "Account-No", "bank");

SOAPBodyElement elementForAccNo =

soapBody.addBodyElement(qNameForAccNo);

elementForAccNo.addTextNode("123456789");

QName qNameForTotalAmount = new QName("http://myBank.com", "Total-Amount", "bank");

SOAPBodyElement elementForTotalAmount =

soapBody.addBodyElement(qNameForTotalAmount);

elementForTotalAmount.addTextNode("75000.00");

message.writeTo(System.out);

}catch(Exception exception){

exception.printStackTrace();

}

}

public static void main(String args[]){

SoapMessageConstruction constructor = new SoapMessageConstruction();

constructor.construct();
}

[/code]

The output for the above sample program is given below,

[code]&amp;lt;/pre&amp;gt;
&amp;lt;SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;

&amp;lt;SOAP-ENV:Header&amp;gt;
&amp;lt;app:Bank-Name&amp;nbsp;xmlns:app="http://myApp.com"&amp;gt;

ICICI Bank

&amp;lt;/app:Bank-Name&amp;gt;

&amp;lt;app:Currency&amp;nbsp;xmlns:app="http://myApp.com"&amp;gt;

INR

&amp;lt;/app:Currency&amp;gt;

&amp;lt;/SOAP-ENV:Header&amp;gt;

&amp;lt;SOAP-ENV:Body&amp;gt;

&amp;lt;bank:Account-No&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;xmlns:bank="http://myBank.com"&amp;gt;123456789&amp;lt;/bank:Account-No&amp;gt;

&amp;lt;bank:Total-Amount&amp;nbsp;xmlns:bank="http://myBank.com"&amp;gt;75000.00&amp;lt;/bank:Total-Amount&amp;gt;

&amp;lt;/SOAP-ENV:Body&amp;gt;

&amp;lt;/SOAP-ENV:Envelope&amp;gt;
&amp;lt;pre&amp;gt;[/code]

Let us see the various pieces of code in detail.

[code lang="java"]
MessageFactory messageFactory = MessageFactory.newInstance();

SOAPMessage message = messageFactory.createMessage();

[/code]

The initial point of entry to construct a SOAP message is to depend on the MessageFactory class which is a factory class to create SOAP messages. The createMessage() method creates and returns a new instance of the SOAP message. The very good thing is that as soon as a SOAP message is created, the inner elements like envelope, header and body are created by default. Printing the SOAP message object to the console  (by calling message.writeTo(System.out)) will result in an output like this,

[code lang="html"]

&amp;lt;SOAP-ENV:Envelope&amp;nbsp;xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;

&amp;lt;/SOAP-ENV:Envelope&amp;gt;

// Add header entries here.

SOAPHeader soapHeader = message.getSOAPHeader();

// Application name header.

QName qNameForAppName =

new QName("http://myApp.com", "Bank-Name", "app");

SOAPHeaderElement&amp;nbsp;headerForAppName =

soapHeader.addHeaderElement(qNameForAppName);

headerForAppName.addTextNode("ICICI Bank");

// Currency header.

QName qNameForCurrency =

new QName("http://myApp.com", "Currency", "app");

SOAPHeaderElement headerForCurrency =

soapHeader.addHeaderElement(qNameForCurrency);

headerForCurrency.addTextNode("INR");

[/code]

The next section of the code gets the header element of the SOAP message by callingmessage.getSOAPHeader()and adds some header entries to it. It does so by calling theSOAPHeader.addHeaderElement(QName)method (See more about QName below.) which adds an empty element called “Bank-Name”. The Bank-Name element is populated with some text content by calling theSOAPHeaderElement.addTextNode(String)method. The above code will result in populating the message structure like this,

[code lang="java"]

QName – QName which stands for qualified name represents the fully qualified name for an xml element, Consider the following xml,

&amp;lt;cricket:player xmlns:cricket = “&amp;lt;a href="http://web.archive.org/web/20080116132744/http://www.cricket.com/"&amp;gt;http://www.cricket.com&amp;lt;/a&amp;gt;”&amp;gt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;lt;name&amp;gt;….&amp;lt;/name&amp;gt;

&amp;lt;/cricket:player&amp;gt;

&amp;lt;football:player xmlns:football = “&amp;lt;a href="http://web.archive.org/web/20080116132744/http://www.football.com/"&amp;gt;http://www.football.com&amp;lt;/a&amp;gt;”&amp;gt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;lt;name&amp;gt;….&amp;lt;/name&amp;gt;

&amp;lt;/football&amp;gt;
[/code]

We have two player elements here, However, with the help of XML name-spaces, they are fully qualified as cricket:player and football:player. For the cricket:player, the element name is “player”, the prefix is “cricket” and the reference name-space is “http://www.cricket.com”.

This fully qualified name representation forms the QName for an element, For example, the above xml code is logical equivalent to the following java code,

[code lang="java"]

QName qNameForCricketPlayer = new QName(“&amp;lt;a href="http://web.archive.org/web/20080116132744/http://www.cricket.com/"&amp;gt;http://www.cricket.com&amp;lt;/a&amp;gt;”, “player”, “cricket”);

QName qNameForFootballPlayer = new QName(“&amp;lt;a href="http://web.archive.org/web/20080116132744/http://www.cricket.com/"&amp;gt;http://www.&amp;nbsp;football.com&amp;lt;/a&amp;gt;”, “player”, “football”);

[/code]

The first three arguments in the constructor refers to the name-space URI, the element name and the prefix respectively]

[code lang="xml"]

&amp;lt;SOAP-ENV:Envelope

xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;

&amp;lt;SOAP-ENV:Header&amp;gt;

&amp;lt;app:Bank-Name&amp;nbsp;xmlns:app="http://myApp.com"&amp;gt;

ICICI Bank

&amp;lt;/app:Bank-Name&amp;gt;

&amp;lt;app:Currencyxmlns:app="http://myApp.com"&amp;gt;

INR

&amp;lt;/app:Currency&amp;gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;

&amp;lt;/SOAP-ENV:Header&amp;gt;

&amp;lt;/SOAP-ENV:Envelope&amp;gt;

// The SOAP part of the message.

SOAPPart soapPart = message.getSOAPPart();

SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

SOAPBody soapBody = soapEnvelope.getBody();

QName qNameForAccNo = new QName("http://myBank.com", "Account-No", "bank");

SOAPBodyElement elementForAccNo =

soapBody.addBodyElement(qNameForAccNo);

elementForAccNo.addTextNode("123456789");&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;

QName qNameForTotalAmount = new QName("http://myBank.com", "Total-Amount", "bank");

SOAPBodyElement elementForTotalAmount =

soapBody.addBodyElement(qNameForTotalAmount);

elementForTotalAmount.addTextNode("75000.00");&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;

[/code]

Similarly, the elements within the body content are added using the above code. Now the resultant SOAP message will look similar to this,

[code lang="xml"]

&amp;lt;SOAP-ENV:Envelope&amp;nbsp;xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&amp;gt;

&amp;lt;SOAP-ENV:Header&amp;gt;

&amp;lt;app:Bank-Name&amp;nbsp;xmlns:app="http://myApp.com"&amp;gt;

ICICI Bank

&amp;lt;/app:Bank-Name&amp;gt;
&amp;lt;app:Currency&amp;nbsp;xmlns:app="http://myApp.com"&amp;gt;INR&amp;lt;/app:Currency&amp;gt;

&amp;lt;/SOAP-ENV:Header&amp;gt;

&amp;lt;SOAP-ENV:Body&amp;gt;

&amp;lt;bank:Account-No&amp;nbsp;xmlns:bank="http://myBank.com"&amp;gt;123456789&amp;lt;/bank:Account-No&amp;gt;
&amp;lt;bank:Total-Amount&amp;nbsp;xmlns:bank="http://myBank.com"&amp;gt;75000.00&amp;lt;/bank:Total-Amount&amp;gt;

&amp;lt;/SOAP-ENV:Body&amp;gt;

&amp;lt;/SOAP-ENV:Envelope&amp;gt;

[/code]

Filed Under: Java EE Tagged With: EJB, EJB 3

Publish and Subscribe messages using JMS Topic in JBoss Server

July 10, 2008 by Krishna Srinivasan Leave a Comment

Publish and Subscribe using JMS Topic

This tips gives overview on how to write Java Messaging Service(JMS) code for creating Topic in the Tomcat server. This is very basic example and only show how to get started instead of looking into the advanced concepts in JMS technology.

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

In JMS, publish/subscribe messaging uses a JMS-managed object called a Topic to manage message flow from publishers to subscribers. JMS publishers are called message producers, and JMS subscribers are called message consumers. A message producer acquires a reference to a JMS Topic on a server, and sends messages to that Topic. When a message arrives, the JMS provider is responsible for notifying all message consumers subscribed to that Topic. The JMS provider (optionally) receives acknowledgment of the message receipt each time it sends the message.

This example is used JBoss server for the testing of application. Before run this example please start your JBoss server and put the following jar files in the classpath. JAR files are specific to the JBoss server MQ operations. It may not work with other vendor provided application servers.

The example program just simply add a message into the JMS Topic and subscribe to the topic.

JAR files

  • jms.jar
  • jnp-client.jar
  • jboss-common.jar
  • concurrent.jar
  • jbossmq-client.jar
  • JMSExample.java

jbossmq-destinations-service.xml

The following code needs to be added in the JBoss configuration xml file for creating the Topic while server
is started.
[code lang=”xml”]
<mbean code="org.jboss.mq.server.jmx.Topic"
name="jboss.mq.destination:service=Topic,name=testTopic">
<depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>
<depends optional-attribute-name="SecurityManager">jboss.mq:service=SecurityManager</depends>
<attribute name="SecurityConf">
<security>
<role name="guest" read="true" write="true"/>
<role name="publisher" read="true" write="true" create="false"/>
<role name="durpublisher" read="true" write="true" create="true"/>
</security>
</attribute>
</mbean> [/code]

jbossmq-destinations-service.xml

[code lang=”java”]
package javabeat.net.jms;

import java.util.Properties;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;

public class JMSExample implements MessageListener {

public static void main(String argc[]) {
new JMSExample().testMessage();
}

public void testMessage() {
TopicConnection conn = null;
TopicSession session = null;
Topic topic = null;
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.factory.url.pkgs",
"org.jboss.naming");
props.setProperty("java.naming.provider.url", "localhost");
Context context = new InitialContext(props);
TopicConnectionFactory tcf = (TopicConnectionFactory) context.lookup("ConnectionFactory");
conn = tcf.createTopicConnection();
topic = (Topic) context.lookup("topic/testTopic");
session = conn.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
conn.start();
TopicPublisher send = session.createPublisher(topic);
TextMessage tm = session.createTextMessage("JavaBeat Test Message");
send.publish(tm);
send.close();
TopicSubscriber topicSubscriber = session.createSubscriber(
topic);
topicSubscriber.setMessageListener(this);
while (true) {
Message message = topicSubscriber.receive(1);
if (message != null) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println(message);
System.out.println(
textMessage.getText());
} else {
break;
}
}
}

} catch (Exception e) {
System.out.println(e.toString() + " Does the queue exist?");
}
}

public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
System.out.println(text);
} catch (Exception jmse) {
jmse.printStackTrace();
}
}
}[/code]

Filed Under: Java EE Tagged With: JBoss, JMS

Create EJB 3.0 project in NetBeans 6.1

July 4, 2008 by itadmin Leave a Comment

Introduction

This article explains how to create EJB 3.0 project using NetBeans IDE 6.1. This article will not explain the details of EJB 3.0 but will give basic knowledge on how to create simple EJB 3.0 project using NetBeans 6.1 IDE.

also read:

  • Java EE Tutorials
  • EJB Interview Questions
  • EJB 3 Web Services
  • Annotation and Dependency Injection in EJB 3
  • Query API in EJB 3

Creating Project in NetBeans 6.1

Step 1 : Create Project

Show Full Image

Step 2 : Select Enterprice Project

Show Full Image

Step 3 : Specify Project Name

Show Full Image

Step 4 : Select server and create EJB,WEb modules

Show Full Image

Step 5 : Project is created

Show Full Image

Filed Under: Java EE Tagged With: EJB

Entity Beans in EJB(BMP)

May 25, 2008 by Krishna Srinivasan Leave a Comment

ENTITY BEAN WITHBEAN-MANAGED PERSISTENCE

Thus far, we acquainted ourselves with Sessionbeans ( both stateless & stateful) and also CMP Entity bean.

also read:

  • Java EE Tutorials
  • EJB Interview Questions
  • EJB 3 Web Services
  • Annotation and Dependency Injection in EJB 3
  • Query API in EJB 3

In this instalment, we take up the most difficult type, (ie) Bean-Managed Persistent Entity bean.(BMP)

Example for Bean-Managed Entity Bean

We have to write the SQL code for Persistence ,ourselves, in the case of Bean-Managed persistence. In our example, If we consider a single instance of the bean, it exists as an object in memory with 3 attributes (key,name,place)At the same time, it should also be persisted as arow,with correspondingfields,in'table1' of 'customer'database in hard disk.They should match. This is known as 'Synchronization'.

The mechanism by which Synchronization is achieved by various vendors may vary. It is known as 'Object-relational mapping'.

Whether, it is CMPor BMP, the process of synchronising is done by the container.The only difference is that , in CMP , we do not write anySQL for Storing ( memory to hard disk) or for 'Loading' (hard disk to memory).In BMP, we have to write the SQLfor thesetasks.

However, the client cannot explicitly , call either 'load' or 'store' functions.This job is taken care of by the Container.Depending on a number of factorssuch as Transaction monitoring, the container chooses the appropriate moment to synchronize the data in memory with the data in table of hard disk storage.

This process, is transparent ,(ie) the programmer need not know about it. The methods are 'callback' methods. Such methods are called by the container by itself without explicit user program or interaction.

In CMP, we just deal with the objects in memory. The task of persistence is automatically done by the container, at the appropriate time. The container itself generates the required SQL code to perform this task. But, in BMP , we should write the necessary SQL code for Store and Load.

This is the difference between CMP and BMP.

Which is better? Opinions differ.One camp claims that CMP is better because,it abstracts the details about the underlying database and deals only with objects in memory.

The other camp feels that CMP is useful only for very simple cases and most of the real life applications are complex, requiring joins from different tables and CMP is not suitable for real life situations.

It will be safer for us to be conversant with BMP , in case it is needed by our application.

As before ( as in the case of CMP), we begin with :

  1. customerRemote.java
  2. customerHome.java

A DEMO FOR BEAN-MANAGED PERSISTENT ENTITY-BEAN
[code]
Access Database name : Customer

tablename:table1
[/code]
Three fields ( key, name, place) ( all String type).
[code]
(Primary key field is 'key').
[/code]
For our example, remember to register the database 'customer' with ODBC.

( The java source files for 'customerRemote' & 'customerHome') are the same as for CMP bean.

Let us create our source files in the following folder:
[code]
c:weblogicbeansbmpdemo
[/code]

As before remember to set JAVA_HOME, WL_HOME. Also, set path & classpath;

[code]
c:weblogicbeansbmpdemo>set JAVA_HOME=C:JDK1.3

…bmpdemo>set WL_HOME=C:WEBLOGIC

…bmpdemo>set path=c:windowscommand;

c:jdk1.3bin;

c:weblogicbin

…bmpdemo>set classpath=c:weblogicbeansbmpdemo;

c:weblogicclasses;

c:weblogiclibweblogicaux.jar;
[/code]

customerRemote.java
[code lang=”java”]
import javax.ejb.*;

import java.rmi.*;

public interface customerRemote extends EJBObject

{

public StringgetName()throws RemoteException;

public voidsetName(Strings)throws RemoteException;

public StringgetPlace()throws RemoteException;

publicvoidsetPlace(String s) throws RemoteException;

}
[/code]

customerHome.java

[code lang=”java”]

import javax.ejb.*;

import java.rmi.*;

public interface customerHome extends EJBHome

{

publiccustomerRemotecreate(String a, String b, String c) throws

RemoteException, CreateException;

public customerRemotefind By PrimaryKey(String a) throws RemoteException, FinderException;
}
[/code]

The difference between CMP and BMP occurs only in the Bean class. Therefore the Remote and Home files are exactly same for CMP and BMP.

We now take up customerBean.java. As this is a lenthy file, it is always good practice to list the sequence in which the functions appear in code file:

(This is just for convenience in code-reading).

  1. setName()
  2. getName()
  3. setPlace()
  4. getPlace()
  5. getConnection ()( this is defined by us)
  6. ejbCreate(
  7. ejbFindByPrimaryKey(
  8. ejbLoad()
  9. ejbStore()
  10. ejbRemove()
  11. ejbPostCreate(
  12. ejbSetEntityContext(
  13. ejbUnsetEntityContext()
  14. ejbActivate()
  15. ejbPassivate()

(note:A single round bracket means there are parameter/parameters).

It will necessary to give very brief note on the purpose of these various methods.

  1. The important function is 'getConnection'. This is written by us.Thepurpose is to to get connection to the database.
  2. 'ejbCreate' method is called when the client invokes 'create' method. Its purpose is to create anew object in memory with the parameters passed by the client and also create the corresponding row in the database table.
  3. 'ejbPostCreate' is called after 'ejbCreate' by the container.This can be used for any desired tasks.It should have the same parameters as the 'ejbCreate' method.
  4. 'ejbLoad' is meant for bringing a row from table into the memory. depending on the primary key in the current context. ( context.getPrimaryKey() ).and setting the attributes of the object accordingly. This is a 'callback' method (ie) it is invoked at the appropriate time by the container.
  5. 'ejbStore' is meant for storing the state of the bean specified by the primary key in the current context and updating the row in thetable accordingly.This also is a callback method.
  6. 'ejbActivate' is a callback method which brings a bean into the bean-pool.
  7. 'ejbPassivate' is a callback method which removes a bean from the bean-pool.

Note:

In most of the books, we will find that the authors use 'stored procedure' method using 'PreparedStatement'. It is not absolutely essential. We have used the much simple 'Statement'method, so that it will be easier to follow.

Some authors opine that the use of Stored procedure does not result in any marked improvement in performance, in network environment!

[code lang=”java”]
//customerBean.java

import javax.ejb.*;

import java.rmi.*;

import java.sql.*;

import javax.sql.*;

import javax.naming.*;

public class customerBean implements EntityBean

{

publicStringkey;

publicStringname;

publicStringplace;

publicEntityContextcontext;

Connectionconnection;

//————————————————————

public String getName()
{
returnname;
}

public void setName(String b)
{
name=b;
}
//———————————————————-
public StringgetPlace()
{
returnplace;
}

public void setPlace(String c)
{
place=c;
}
//—————————————————————-

private Connection getconnection()// this is our own method!

{

try

{

Contextcontext=new InitialContext();

Stringdsn=’java:comp/env/jdbc/customer’;

DataSource ds=(DataSource)context.lookup(dsn);

connection=ds.getConnection();

System.out.println(‘Connection obtained’);

} catch(Exception e1){System.out.println(”+e1);}

return connection;

}

//————————————————————

publicStringejbCreate(String a, String b, String c)

throws CreateException

{

try

{

key=a;

name=b;

place = c;
connection=getconnection();

Statementstatement= connection.createStatement();

Stringsql = ‘insert into table1 values('’+a+’','’+b+’','’+c+’')’;

statement.execute(sql);

connection.close();

System.out.println(‘Connection closed’);

} catch(Exceptione1) {System.out.println(”+e1);}

returnkey;

}

//———————————————————–

publicStringejbFindByPrimaryKey(String a)

{

try

{

connection=getconnection();

Statementstatement=connection.createStatement();
Stringsql=’ select * from table1 where key='’+a+’' ‘;
ResultSetrs=statement.executeQuery(sql);
connection.close();
System.out.println(‘Connection closed’);

} catch(Exception e1) {System.out.println(”+e1);}
returna;

}

//———————————————————–

publicvoid ejbLoad()//get the data from database

{

try

{

Stringpk = (String) context.getPrimaryKey();
// * important

connection=getconnection();

Statementstatement=connection.createStatement();

Stringsql = ‘select * from table1 where key='’+pk+’' ‘;

ResultSetrs=statement.executeQuery(sql);

while(rs.next())

{

key=rs.getString(1);

name=rs.getString(2);

place=rs.getString(3);

}

rs.close();

connection.close();

System.out.println(‘Connection closed’);

}catch(Exception e1) { System.out.println(”+e1); }
}

//——————————————————————–
publicvoidejbStore()//send data to database

{

try

{

connection=getconnection();
Statementstatement=connection.createStatement();
[/code]

Filed Under: Java EE Tagged With: EJB

Entity Beans in EJB(CMP)

May 25, 2008 by Krishna Srinivasan Leave a Comment

Entity beans are characterized by the following 3 features.

  1. They are 'Persistent'. ( they are stored inhard-disk)
  2. They are shared by many clients.
  3. They have ,'Primary key'.

also read:

  • Java EE Tutorials
  • EJB Interview Questions
  • EJB 3 Web Services
  • Annotation and Dependency Injection in EJB 3
  • Query API in EJB 3

As already mentioned ,Entity beans can be thought of as a record ( or row) in a table of a relational database. ( This is just for easy understanding because, the database can also be Object Database, XML database etc.)

Let us consider a simple Java class named'customer'. Let this class havejust three attributes ,namely,'key','Name'and 'Place'. In a javabean, we would provide accessor methods, such as 'getName()'&'setName(String s)etc. for each attribute. The same method is employed in Entity bean. ( Roughly).

Thus,we deal with Java idiom only andthis is more intuitive.If we have an account bean, we can write code for deposit as follows:

[code lang=”java”]

intn=account1.getBalance();

n=n+400;

account1.setBalance(n);
[/code]
Doubtless, this is much simplerand easier than writing sql code.

Entity beans 'persist' (ie) they are stored inEnterprise server's hard disk and so even if there is a shutdown of the server, the beans 'survive' and can be created againfrom the hard disk storage.[A session bean is not stored in hard disk].

A Session bean , whether it isstateless or statefulis meant for a single client. But Entity bean , being a record in a table of a database, is likely to be accessed by a number of clients . So, they are typically shared by a number of clients. For the same reason, entity beans should work within 'Transaction'.managementas specified. in the Deployment descriptor.

Canwe use a session beanfor accessing a database either for 'select' query or for modifying?

Yes. We can, provided that the application is simple &is not accessed by multiple users . But we should note that the session
beanjust displays or manipulates a record in database whereas the entity bean is the record itself!

But, typically in an enterprise situation, a database will be accessed by thousands of clients concurrently, and the very rationale for the development of EJB is to tackle the problems which arise then. That is why, Entity beans are the correct choice for Enterprise
situations.

If we think of an entity bean instance as a record in a table of database, it automatically followsthat itshouldhave a primary key for unique identification of the record..[Many books provide a 'primary key
class'.But it is not atall necessary.] But carefully note that it should be a serializable java class. So, if we provide a primary key as 'int' type, we will have to provide a wrapper class (ie) Integer. This is clumsy. The best and easiest method
is to provide a string type as the primary key. (String class). This is the method that we will be following in our illustarations.
( We are using WebLogic 5.1)
So, in our example, we are having an Accessdatabase named 'customer'.This database has a table known as 'table1'. The table has three columns .

  1. 'key'(primary key field)
  2. 'name'
  3. 'place'

( all of them are ofStringtype)

We create a table like this without any entries and then register it in ODBC.( this is the most familiar and easy approach.We can also use other types of jdbc drivers.)

[This does not mean that the recordshaveto be created only through Entity bean. We can always add, delete and edit records directly in the table].

Entity beans can have two types of Persistence.

  1. Container-managed Persistence(CMP)
  2. Bean-managed Persistence type(BMP)

We can declare the type of persistence required by us in the 'Deployment Descriptor'.

In CMP, the bean designer does not have to write any sql-related code at all. The necessary sql statements are automatically generated by the container. The container takes care of synchronizing the entity bean's attributes with the corresponding columns in the table of the database. Such variables are referred to as 'container-managed fields'.

This requirement also is declared by us in the Deployment descriptor.

With CMP, the entity bean class does not contain the code that connects to a database. So, we are able to get flexibility by simply editing the deployment descriptors and weblogic.properties files, without editing and recompiling the java class files.

What are the advantages of CMP?

CMPbeanshave two advantages:

  1. less code.
  2. the code is independent of the type of data store such as Relational database.

What are the limitations of CMP?

If we want to have complex joins between different tables, CMP is not suitable. In such cases, we should use BMP.

EXAMPLE FOR CMP -ENTITY BEAN

As before we begin with the Remote Interface file.

//customerRemote.java

[code lang=”java”]
import javax.ejb.*;

import java.rmi.*;

public interface customerRemote extends EJBObject

{
public StringgetName()throws
RemoteException;

public voidsetName(Strings)

throws RemoteException;

public StringgetPlace()throws RemoteException;

publicvoidsetPlace(String s)

throws RemoteException;

}
[/code]

Next we write the home interfcae.

//**********customerHome.java *******************
[code lang=”java”]
import javax.ejb.*;

import java.rmi.*;

public interface customerHomeextends EJBHome

{

public customerRemote create

(String a,String b,String c)

throwsRemoteException, CreateException;

public customerRemote findByPrimaryKey(String a)

throwsRemoteException, FinderException;

}
[/code]

//customerBean.java
[code]
import javax.ejb.*;
import java.rmi.*;

public class customerBean implements EntityBean
{

public Stringkey;
public Stringname;

public Stringplace;

public StringgetName()

{

returnname;

}

publicStringgetPlace()

{

returnplace;

}

//—————————

public void setName(String b)

{

name=b;

}

publicvoidsetPlace(String c)

{

place=c;

}

//——————————-

public StringejbCreate

(Stringa, Stringb, Stringc)

throws CreateException

{

this.key=a;

this.name=b;
this.place = c;
return null;//it should be null!
}

public void ejbPostCreate

(String a,String b,String c)

throws CreateException{}

public void ejbActivate(){}

publicvoidejbPassivate(){}

public void ejbRemove(){}

publicvoidejbLoad(){}

public void ejbStore(){}

public void setEntityContext(EntityContext
ec){ }

public void unsetEntityContext(){ }
}
[/code]

We now createthreexml files as given below.

  1. ejb-jar. xml
  2. weblogic-ejb-jar.xml
  3. weblogic-cmp-rdbms-jar.xml

These three files are very important and should be created with utmost care. Remember that XML is case-sensitive and the DTD (Deployment descriptor) for each file expects the correct structure of the document. So type exactly as given.(No formatting..shown here for clarity only)

ejb-jar. xml
[code lang=”xml”]
<?xml
version="1.0"?>
<!DOCTYPE
ejb-jar PUBLIC
‘-//Sun
Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN’
‘http://java.sun.com/dtd/ejb-jar_1_1.dtd’>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>customerBean</ejb-name>
<home>customerHome</home>
<remote>customerRemote</remote>
<ejb-class>customerBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>key</field-name>
</cmp-field>
<cmp-field>
<field-name>name</field-name>
</cmp-field>
<cmp-field>
<field-name>place</field-name>
</cmp-field>
<primkey-field>key</primkey-field>
</entity>
</enterprise-beans>
</ejb-jar>

[/code]

weblogic-ejb-jar.xml

[code lang=”xml”]
<?xml
version="1.0" ?>
<!DOCTYPE
weblogic-ejb-jar PUBLIC
"-//BEA
Systems, Inc.//DTD WebLogic 5.1.0 EJB//EN"
"http://www.bea.com/servers/wls510/dtd/weblogic-ejb-jar.dtd">
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>customerBean</ejb-name>
<persistence-descriptor>
<persistence-type>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>5.1.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-type>

[/code]

Filed Under: Java EE Tagged With: EJB

  • « Previous Page
  • 1
  • …
  • 17
  • 18
  • 19
  • 20
  • 21
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved