Ad Code

Responsive Advertisement

Quick Suggests :-

6/recent/ticker-posts

Introduction of Java Enterprise Edition Platform.

 Introduction of Java Enterprise Edition Platform.



Content :- 

1.Introduction :- 
1.1.The tutorial's objectives.
1.2.This tutorial's requirements.
1.2.1.A list of requirements.


2.Java Platform Knowledge, Enterprise Edition :- 
2.1.Distinction between Java EE and Java SE.
2.2.The basis for the Java programming language.
2.3.A summary of enterprise applications.
2.4.Tiered applications.
2.5.Java EE Servers.
2.6.Java EE containers.

3.Putting Together Your First Java EE Application :- 
3.1.The example application's architecture.
3.2.Tiers in the example application.
3.3.In the example application, java ee technologies were used.
3.4.Coding the DukesAgeResource example application.
3.5.Starting the process.
3.6.Creating the web service.


4.Putting Together Your Second Java EE Application :- 
4.1.Creating the firstcup Project.
4.1.1.Creating the web application project.
4.2.Creating the Java persistance API entity.
4.2.1.Creating the FirstcupUser entity class.
4.2.2.Add properties to the FirstcupUser entity.
4.2.3.Add constructers to the FirstcupUser entity.
4.2.4.Add a NamedQuery to the FirstcupUser entity.
4.3.Creating the enterprise bean.
4.3.1.Create the DukesBirthdayBean enterprise bean class. 
4.3.2.Add a logger instance to DukesBirthdayBean.java .
4.3.3.Add a business method to DukesBirthdayBean that gets the average age defference of fisrtcup users.  
4.3.4.Add a business method for calculating the age defference between Duke and the User.
4.4.Creating the web client. 
4.4.1.Creating a resource bundle.
4.4.2.Configuring the resource bundle in the configuration file.
4.4.3.Creating the DukesBday managed bean class.
4.4.4.Creating the facelets client.
4.5.Building,Packaging,Deploying and Running the firstcup web apllication.
4.5.1.Building,Package and Deploy the firstcup web application.
4.5.2.Run the firstcup application.


5.Next Steps :- 
5.1.The Java EE tutorial.
5.2.More information on the Java EE platform.
5.3.Java EE Servers.
5.3.1.Glassfish server open source edition.
5.3.2.Other Java EE Servers.

Preface.

A short lesson for new Java EE programmers called An Introduction to Java Platform, Enterprise Edition. This course will teach you how to construct an enterprise application from the ground up, from development to deployment.

Who is this tutorial for :-
This tutorial is intended for Java EE developers who are new to the platform. You should be comfortable with the Java programming language, especially the new capabilities in Java Platform, Standard Edition 6. While experience with corporate development and Java EE technologies is beneficial, this tutorial assumes you are new to Java EE application development.

Before you should read this tutorial :-
Before you start this tutorial, you should :-
■ Be familiar with the Java programming language.
■ Be able to install software on your work machine.
■ Have a modern web browser installed on your work machine.

Related Books and Projects :-
The following books and projects may be helpful to you in understanding this tutorial :-
■ The Java EE 6 Tutorial.
■ The Oracle GlassFish Server documentation set.
■ The NetBeans IDE documentation set.

Related Third-PartyWeb Site References :-
Third-party URLs are referenced in this document and provide additional, related information.

Typographic Conventions :-
The following table describes the typographic conventions that are used in this tutorial.

1.Introduction.

This tutorial's introduction. The goals and prerequisites for completing this tutorial are outlined in this chapter.

1.1.The tutorial's objectives.
At the completion of this tutorial, you will :-
■ Understand the basics of tiered applications.
■ Understand the basics of the Java EE platform.
■ Have created a multi-tiered Java EE application.
■ Have deployed and run your application on a Java EE server.
■ Know where to go next for more information on the Java EE platform.

1.2.This tutorial's requirements.
1.2.1.A list of requirements.
To complete this tutorial, you need to :- 
■ Get the Java EE 6 Software Development Kit. 
■ Get NetBeans IDE and all necessary plugins. 
■ Configure your environment. 
■ Get the latest updates to the tutorial bundle.
For up-to-the-minute information on which versions of the required software are compatible with this tutorial, see the First Cup compatibility page (http://java.net/projects/ firstcup/pages/FirstCupCompatibility). 

Getting the Java EE 6 SDK :-
To get the Java EE 6 SDK, go to http://www.oracle.com/technetwork/java/javaee/ downloads/.

Getting NetBeans IDE :-
To get NetBeans IDE, go to http://www.netbeans.org/downloads/, and download the Java EE distribution.

Configuring Your Environment :-
Once you have all the necessary downloads, you must configure the tutorial bundle to reflect your environment.

Add GlassFish Server as a Server in NetBeans IDE :-
To run the tutorial examples in NetBeans IDE, you must register your GlassFish Server installation as a NetBeans server instance. Follow these instructions to register the GlassFish Server in NetBeans IDE.

1.From theTools menu, choose Servers.
The Servers dialog opens.
2.Click Add Server. 
3.Under Server, select GlassFish Server 3+ and click Next.
4.Under Platform Location, browse to or enter the location of your GlassFish Server installation.
5.Click Next. 
6.Under Domain, use the drop-down list to select an existing domain, type in the path to the domain directly in the field, or type the name of a new domain to create.
Normally, you will select the default domain, domain1.
7.Click Finish.

Getting the Latest Updates to the Tutorial :-
Check for any updates to the tutorial by using the Update Center included with the Java EE 6 SDK.

Update the Tutorial Through the Update Center:-
Open the Update Center and check for any updates to the tutorial.

1.Open the Services tab in NetBeans IDE and expand Servers. 
2.Right-click the GlassFish Server instance and select View Update Center to display the Update Tool.
3.Select Available Updates in the tree to display a list of updated packages.
4.Look for updates to the First Cup for Java EE 6 (javaee-firstcup-tutorial) package.
5.If there is an updated version of First Cup, select First Cup 2.1 for Java EE 6 (javaee-firstcup-tutorial) and click Install.

2.Java Platform Knowledge, Enterprise Edition :- 

This chapter outlines the features of Java Platform, Enterprise Edition (Java EE), how it differs from Java Platform, Standard Edition (Java SE), Java Platform, Micro Edition (Java ME), and JavaFX, and the basic concepts behind enterprise application development.
 
2.1.Distinction between Java EE and Java SE.

Java is a computer language as well as a platform. The Java programming language is an object-oriented high-level language with a distinct syntax and style. A Java platform is a computing environment that runs Java programming language applications.
There are various Java platforms to choose from. Many developers, even those who have worked with the Java programming language for a long time, are unaware of how the various platforms interact.

2.2.The basis for the Java programming language.

There are four platforms of the Java programming language :- 
■ Java Platform, Standard Edition (Java SE) 
■ Java Platform, Enterprise Edition (Java EE) 
■ Java Platform, Micro Edition (Java ME) 
■ JavaFX

A Java Virtual Machine (VM) and an application programming interface are present in all Java platforms (API). The Java Virtual Machine is a program that runs Java technology applications on a specific hardware and software platform. A programming interface (API) is a set of software components that can be used to develop other software components or applications. Platform-independence, power, stability, ease-of-development, and security are all advantages of the Java programming language. Each Java platform provides a virtual machine and an API, allowing applications written for that platform to run on any compatible system with all of the Java programming language's advantages: platform-independence, power, stability, ease-of-development, and security.

Java SE :-
The Java SE API is what most people think of when they think of the Java programming language. The Java SE API offers the Java programming language's essential capabilities. It covers everything from the Java programming language's basic types and objects to high-level classes for networking, security, database access, graphical user interface (GUI) creation, and XML parsing.
The Java SE platform includes a virtual machine, development tools, deployment technologies, and various class libraries and toolkits that are often used in Java technology applications, in addition to the core API.

Java EE :-
On top of the Java SE platform, the Java EE platform is constructed. The Java EE platform is a set of APIs and runtime environments for building and running large-scale, multi-tiered, scalable, dependable, and secure network applications.

Java ME :-
For running Java programming language programs on small devices, such as mobile phones, the Java ME platform provides an API and a small-footprint virtual machine. The API consists of a subset of the Java SE API as well as specific class libraries for developing small device applications. Clients of Java EE platform services are frequently Java ME applications.


Java FX :-
JavaFX is a framework for developing sophisticated internet applications with a simple user interface. To take advantage of higher-performance clients and a modern look-and-feel, JavaFX applications use hardware-accelerated graphics and media engines, as well as high-level APIs for connecting to networked data sources. Clients of Java EE platform services could be JavaFX apps.

2.3.A summary of enterprise applications.

This section describes enterprise applications and how they are designed and developed.
The Java EE platform, as previously said, is intended to assist developers in the development of large-scale, multi-tiered, scalable, dependable, and secure network applications. "Enterprise apps" is a shorthand term for these programs, which are meant to tackle challenges faced by major businesses. Enterprise applications, on the other hand, aren't just for big businesses, agencies, and governments. In an increasingly networked world, the advantages of an enterprise application are beneficial, if not vital, for individual developers and small businesses.
Enterprise applications are often complex due to the elements that make them powerful, such as security and reliability. The Java EE platform is intended to simplify enterprise application development by offering a development model, API, and runtime environment that allows developers to focus on the functionality of their applications.

2.4.Tiered applications.

In a multi-tiered application, the application's functionality is divided into discrete functional regions known as tiers. A client tier, a middle tier, and a data tier are common components of multi-tiered applications (often called the enterprise information systems tier). A client program makes requests to the intermediate tier as part of the client tier. The business functions of the middle tier handle client requests and process application data, which is then stored in a permanent datastore in the data tier.
Java EE application development concentrates on the middle tier to make enterprise application management easier, more robust, and more secure.

The Client Tier :-
The client tier is made up of application clients that connect to a Java EE server and are often hosted on a separate machine from the server. The server receives requests from the clients. The requests are processed by the server, which then sends a response to the client. Java EE clients can be many different types of applications, and they are not always, or even frequently, Java programs.
Clients can be a web browser, a standalone application, or other servers that execute on a computer other than the Java EE server.

The Web Tier :-
The web tier consists of components that handle the interaction between clients and the business tier. Its primary tasks are the following :- 
■ Dynamically generate content in various formats for the client. 
■ Collect input from users of the client interface and return appropriate results from the components in the business tier. 
■ Control the flow of screens or pages on the client. 
■ Maintain the state of data for a user's session. 
■ Perform some basic logic and hold some data temporarily in JavaBeans components. 

Java EE Technologies Used in the WebTier :-
The following Java EE technologies are used in the web tier in Java EE applications.


The Business Tier :-
The business tier is made up of components that offer an application's business logic.
Business logic is code that allows a specific business domain, such as the financial industry or an e-commerce site, to work. The business tier components include the fundamental functionality in a well-designed corporate application.

Java EE Technologies Used in the BusinessTier :-
The following Java EE technologies are used in the business tier in Java EE applications:


The Enterprise Information Systems Tier :-
Database servers, enterprise resource planning systems, and other legacy data sources, such as mainframes, make up the enterprise information systems (EIS) tier. These resources are usually located on a different system than the Java EE server and are accessed by business tier components.

Java EETechnologies Used in the EISTier :-
The following Java EE technologies are used to access the EIS tier in Java EE applications :-


2.5.Java EE Servers.

A Java Enterprise Edition server is a server program that implements the Java Enterprise Edition platform APIs and delivers standard Java Enterprise Edition services. Because they allow you to provide application data to clients in the same way that web servers serve web pages to web browsers, Java EE servers are also known as application servers.
Several application component types are hosted by Java EE servers, which correspond to the tiers in a multi-tiered application. In the form of a container, the Java EE server delivers services to these components.

2.6.Java EE containers.

The interface between the component and the platform's lower-level functionality to support that component is provided by Java EE containers. The platform defines the container's functionality, which varies depending on the component type. Nonetheless, the server enables the various component types to collaborate in order to give functionality in a business application.

The Web Container :-
The interface between web components and the web server is the web container. A servlet, a JavaServer Faces Facelets page, or a JSP page are all examples of web components. The container controls the component's lifecycle, routes requests to application components, and offers access to context data such current request information.

The Application Client Container :-
The application client container is the interface between Java EE application clients and the Java EE server. Java EE application clients are special Java SE applications that employ Java EE server components. The application client container is a gateway between the client application and the Java EE server components that the client utilizes. It runs on the client machine.

The EJB Container :-
The EJB container is the interface between enterprise beans and the Java EE server, which provide the business logic of a Java EE application. The EJB container oversees the execution of an application's enterprise beans and runs on the Java EE server.

3.Putting Together Your First Java EE Application :- 

This chapter gives an overview of the example applications and step-by-step instructions on coding and running the dukes-age web service example application.

3.1.The example application's architecture.

The example applications consist of four main components: DukesAgeResource, a JAX-RS RESTful web service; DukesBirthdayBean, an enterprise bean; FirstcupUser, a Java Persistence API entity; and firstcup, a web application created with JavaServer Faces Facelets technology.


DukesAgeResource is a JAX-RS resource that calculates the age of Duke, the Java mascot. Duke was born May 23, 1995, when the first demo of Java technology was publicly released.

DukesBirthdayBean is a local, no-interface view stateless session bean that calculates the difference between the user's age and Duke's age, and stores the user-submitted data in a Java Persistence API entity. 
FirstcupUser is a Java Persistence API entity that represents a particular user's birthday. It is stored in a Java DB database table, and managed by DukesBirthdayBean's business methods. 
The firstcup web application is a JavaServer Faces Facelets application that accesses DukesAgeResource to display Duke's age, reads in a date provided by the user, accesses DukesBirthdayBean to calculate who is older, and then displays the difference in years between the user and Duke and the average age difference of all users. 
The firstcup web application consists of the following :-
■ greeting.xhtml: An XHTML page that uses the JavaServer Faces Facelets tag libraries. Users can type their birth date in a field and submit it for comparison against Duke's birth date. 
■ response.xhtml: A Facelets-enabled XHTML page that tells the user whether he or she is older or younger than Duke, based on the date the user entered in the greeting.xhtml page, and displays the average age difference of all users. 
■ DukesBDay.java: A JavaServer Faces managed bean that defines properties to hold the user's birth date, get Duke's current age from the DukesAgeResource web service, and get the age difference between the user and Duke from the enterprise bean. 
■ web.xml: The web application's deployment descriptor, which is used to configure certain aspects of a web application when it is installed. In this case, it is used to provide a mapping to the application's FacesServlet instance, which accepts incoming requests, passes them to the life cycle for processing, and initializes resources. It also specifies greeting.xhtml as the welcome file for the application. 
■ WebMessages.properties and WebMessages_es.properties: Java programming language properties files that contain the localized strings used in greeting.xhtml and response.xhtml. By default, the English language strings in WebMessages.properties are used, but Spanish language strings are also provided in WebMessages_es.properties. 
■ DukesBirthdayBean.java: as described above, the enterprise bean packaged within the firstcup application. DukesBirthdayBean calculates the difference between the user's birthday and Duke's birthday.

3.2.Tiers in the example application.

The example applications have one web tier component (the firstcup web client), three business tier components (the DukesAgeResource web service, the FirstcupUser entity, and the DukesBirthdayBean enterprise bean), and one enterprise information system (EIS) tier (the data in the Java DB database table). The user's web browser is the client tier component, as it accesses the rest of the application through the web tier.

3.3.In the example application, java ee technologies were used.

The DukesAgeResource web service is a JAX-RS resource. The DukesBirthdayBean enterprise bean is a stateless session bean. The FirstcupUser entity is a Java Persistence API entity. The firstcup web client is a JavaServer Faces application that runs in the web container of the Java EE server.

3.4.Coding the DukesAgeResource example application.
This section describes how to code the DukesAgeResource example application, a JAX-RS RESTful web service endpoint.

3.5.Starting the process.

Before you start coding the example, you need to perform some configuration tasks :- 
1. Register the server with your NetBeans IDE as described in “Configuring Your Environment” on up. 
2. Create a directory for the example you will build.

Create a Directory for the Example :-
Create another directory at the same level as the tut-install/example directory, where tut-install is the location of the firstcup tutorial installation, and call it myexample. You'll create the applications described in this tutorial in this directory.

3.6.Creating the web service.

The DukesAgeResource endpoint is a simple RESTful web service. REST stands for representational state transfer, and software architectures that conform to the principles of REST are referred to as RESTful. RESTful web services are web-based applications that use the HTTP protocol to access, modify, or delete information contained within a resource. A RESTful web service resource is a source of specific information identifiable by a uniform resource identifier (URI), for example http://example.com/someResource, and may be manipulated by calling the HTTP protocol's methods, for example GET or POST.
RESTful web services are often contrasted to SOAP web services (for example, web services created with the JAX-WS API that is part of Java EE 6). Compared to SOAP web services, RESTful web services are simpler, as they use HTTP directly rather than as a transport mechanism for an underlying XML document format, and typically offer better performance.
Web services are designed to be independent of their clients. Typically RESTful web services are publicly available to a wide variety of clients, and the clients are located throughout the Internet. This is called “loose coupling,” as the clients and servers are connected only by the standard HTTP-based requests and responses, and do not need to know each other's implementation details. For this reason, DukesAge will be developed in its own application module, and deployed separately from the DukesBirthdayBean enterprise bean and firstcup web client. DukesAge could be deployed on a completely different machine without affecting the functionality of the firstcup web client.

JAX-RS Resources :-
DukesAgeResource is a JAX-RS resource class that responds to HTTP GET requests and returns a String representing the age of Duke at the time of the request.
To create DukesAgeResource, use the wizard provided by the JAX-RS plug-in for NetBeans IDE to generate the resource class. This class is annotated with the javax.ws.rs.Path annotation, which specifies the URL suffix to which the resource will respond. DukesAgeResource has a single method, getText, annotated with the javax.ws.rs.GET and javax.ws.rs.Produces annotations. @GET marks the method as a responder to HTTP GET requests, and @Produces specifies the MIME-type of the response sent back from getText to clients. In this case, the MIME-type is text/plain.

Creating the Endpoint :-
In NetBeans IDE, create a web project with a source file called DukesAgeResource.java in the firstcup.webservice package using the RESTful Web Service wizard.

Create the Project in NetBeans :-
1.From the File menu, choose New Project. 
2.In the Categories pane, select Java Web. 
3.In the Projects pane, select Web Application.
4.Click Next. 
5.In the Project Name field, type dukes-age. 
6.In the Project Location field, browse to tut-install/myexample, where tut-install is the location of the firstcup tutorial installation. 
7.Click Next. 
8.Select your GlassFish Server instance from the Server menu.
9.Select Java EE 6Web from the Java EE Version menu. 
10.In the Context Path field, type /DukesAgeService. 
11.Click Finish. 
You should now see the module you created in the Projects tab. 
12.From the Projects tab, right-click the index.jsp file and select Delete. Click Yes in the dialog.

Create the DukesAgeResource Class :-
1.Select the dukes-age project in the Projects tab. 
2.From the File menu, choose New File. 
3.In the Categories pane, selectWeb Services. 
4.In the FileTypes pane, select RESTfulWeb Services From Patterns. 
5.Click Next. 
6.Under Select Pattern, select Simple Root Resource and click Next. 
7.In the Resource Package field, type firstcup.webservice. 
8.In the Path field, type dukesAge. 
9.In the Class Name field, type DukesAgeResource. 
10.From the MIMEType menu, select text/plain. 
11.Click Finish. 
12.In the REST Resources Configuration dialog, uncheck Add Jersey Library and click OK. You should now see the DukesAgeResource.java file inside the firstcup.webservice package in the Projects tab. The DukesAgeResource.java file should also be open in the editor pane.

Configure the dukes-ageWeb Application :-
Set the default URL that is brought up in a web browser when you run dukes-age. 
1.Right-click the dukes-age project in the Projects tab and select Properties. 
2.In the Categories pane, click Run.
3.Set Relative URL to /resources/dukesAge. 
4.Click OK.

Remove the putText Method :-
The DukesAgeResource JAX-RS resource doesn't respond to HTTP PUT requests. Delete the generated putText method in DukesAgeResource.

Highlight the following generated Javadoc and method definition and delete it.
/** 
* PUT method for updating or creating an instance of DukesAgeResource 
* @param content representation for the resource 
* @return an HTTP response with content of the updated or created resource. 
*/ @PUT 
@Consumes("text/plain") 
public void putText(String content) { 
}

Implement the getText Method :-
Add code to DukesAgeResource.getText that calculates Duke's age at the time of the request. To do this, use the java.util.Calendar and java.util.GregorianCalendar classes to create an object representing the date May 23, 1995, Duke's birthday. Then create another Calendar object representing today's date, and subtract today's year from Duke's birth year. If today's date falls before May 23, subtract a year from this result. Then return the result as a String representation.

1.Highlight the current code in getText and replace it with the following code:
 // Create a new Calendar for Duke’s birthday
Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23); 
// Create a new Calendar for today 
Calendar now = GregorianCalendar.getInstance(); 

// Subtract today’s year from Duke’s birth year, 1995 
int dukesAge = now.get(Calendar.YEAR) - dukesBirthday.get(Calendar.YEAR); dukesBirthday.add(Calendar.YEAR, dukesAge); 

// If today’s date is before May 23, subtract a year from Duke’s age 
if (now.before(dukesBirthday)) { 
dukesAge--;
 } 
// Return a String representation of Duke’s age 
return "" + dukesAge;
2.Right-click in the editor window and select Format. 
3.Right-click in the Editor and select Fix Imports. 
4.From the File menu, choose Save to save the file.

Building and Deploying theWeb Service :-
Build the JAX-RS web application and deploy it to your GlassFish Server instance.

Build and Deploy theWeb Service Endpoint :-
Compile, package, and deploy dukes-age.war to GlassFish Server. This task gives instructions on deploying dukes-age.war in NetBeans IDE.

Right-click dukes-age in the Projects tab and select Run :-
After dukes-age.war deploys successfully to GlassFish Server a web browser will load the URL of the DukesAgeResource path, and you'll see the returned String representing Duke's age.

Example 3–1 :-
Output of DukesAgeResource :-

Here's an example of the output of DukesAgeResource displayed in a web browser. 
16
 At this point, you've successfully created, deployed, and run your first Java EE application. Now you will create a web application that uses this web service data.

4.Putting Together Your Second Java EE Application :- 

This chapter gives step-by-step instructions on coding and running the firstcup web application, which uses the dukes-age web service described in Chapter 3, “Creating Your First Java EE Application.” The firstcup web application is a more complicated application, and uses several different Java EE APIs.
The firstcup example application retrieves, or “consumes,” the data from the dukes-age web service. A JavaServer Faces web front-end asks users to enter their birthdays to find out who is older, the user or Duke. This data is stored in a Java DB database table using the Java Persistence API. The business logic, which provides the core functionality of the application, is handled by an enterprise bean.
All the tiers described in “Tiered Applications” on page 13 are present in the firstcup web application. The web or client tier is the JavaServer Faces front-end. The enterprise information systems, or EIS, tier is the Java DB database. The business tier is the enterprise bean.

4.1.Creating the firstcup Project.
The firstcup web application project consists of the Java Persistence API entity, the enterprise bean, and the JavaServer Faces web front-end.
4.1.1.Creating the web application project.
Follow these steps to create a new web application project in NetBeans IDE.
1.From the File menu, choose New Project. 
2.In the Categories pane, select JavaWeb. 
3.In the Projects pane, selectWeb Application.
4.Click Next. 
5.In the Project Name field, type firstcup. 
6.In the Project Location field, browse to tut-install/myexample, where tut-install is the location of the firstcup tutorial installation. 
7.Click Next. 
8.Select your GlassFish Server instance from the Server menu. 
9.Make sure Java EE 6Web is selected in the Java EE Version menu. 
10.Check the Enable Contexts and Dependency Injection box. 
11.In the Context Path field, makes sure it is set to /firstcup. 
12.Click Next. 
13.Under Frameworks, select JavaServer Faces. 
14.Click Finish. 
15.From the Projects tab, right-click the index.xhtml file and select Delete. Click Yes in the dialog.

4.2.Creating the Java persistance API entity.
The Java Persistence API allows you to create and use Java programming language classes that represent data in a database table. A Java Persistence API entity is a lightweight, persistent Java programming language object that represents data in a data store. Entities can be created, modified, and removed from the data store by calling the operations of the Java Persistence API entity manager. Entities, or the data encapsulated by the persistent fields or properties of a entity, can be queried using the Java Persistence Query Language (JPQL), a language similar to SQL that operates on entities.
In firstcup, there is a single entity that defines one query.
4.2.1.Creating the FirstcupUser entity class.
The FirstcupUser Java Persistence API entity represents a particular firstcup user, and stores the user's birthday and the difference in age between the user and Duke. FirstcupUser also defines a Java Persistence API query used to calculate the average age difference of all users.
1.Select the firstcup project in the Projects tab. 
2.From the File menu, choose New File. 
3.In the Categories pane, select Persistence. 
4.In the FileTypes pane, select Entity Class. 
5.Click Next. 
6.In the Class Name field, type FirstcupUser. 
7.In the Package field, type firstcup.entity. 
8.Click Next. 
9.Select jdbc/__default from the Data Source menu. 
10.ForTable Generation Strategy, select Drop and Create. 
11.Click Finish. 
You should now see the FirstcupUser.java file inside the firstcup.entity package in the Projects tab. The FirstcupUser.java file should also be open in the editor pane.

4.2.2.Add properties to the FirstcupUser entity.
Create the FirstcupUser entity's two properties: birthday, of type java.util.Calendar; and ageDifference, of type int.
The birthday property must be annotated with the javax.persistence.Temporal annotation to mark the property as a date field in the underlying database table. All persistent fields or properties of type java.util.Calendar or java.util.Date must be annotated with @Temporal.

1.In FirstcupUser.java below the id field definition, copy and paste in the following field definitions for birthday and ageDifference : -
@Temporal(javax.persistence.TemporalType.DATE)
 protected Calendar birthday;
 protected int ageDifference;
2.Below the getter and setter methods for the id property, copy and paste in the following getter and setter methods for the birthday and ageDifference properties :-
public Calendar getBirthday() {
return birthday;
public void setBirthday(Calendar birthday) { 
this.birthday = birthday; 
public int getAgeDifference() { 
return ageDifference; 
public void setAgeDifference(int ageDifference) { 
this.ageDifference = ageDifference; 
}
3.Right-click in the editor window and select Format. 
4.Right-click in the editor window and select Fix Imports.

4.2.3.Add constructers to the FirstcupUser entity.
Create two constructors for FirstcupUser: one that takes no arguments, and another that takes two arguments.

1.Below the field definitions in the FirstcupUser class, add the following constructors :-
public FirstcupUser() {
public FirstcupUser(Date date, int ageDifference) {
Calendar cal = new GregorianCalendar(); 
cal.setTime(date); 
this.setBirthday(cal); 
this.setAgeDifference(ageDifference); 
}
2.Right-click in the editor window and select Format. 
3.Right-click in the editor window and select Fix Imports, then click OK.

4.2.4.Add a NamedQuery to the FirstcupUser entity.
Add a JPQL named query to the FirstcupUser entity that returns the average age difference of all firstcup users.
This query uses the AVG aggregate function to return the average of all the values of the ageDifference property of the FirstcupUser entities.
1.Directly before the class definition, copy and paste in the following code :-
@NamedQuery(name="findAverageAgeDifferenceOfAllFirstcupUsers", 
query="SELECT AVG(u.ageDifference) FROM FirstcupUser u"),
The @NamedQuery annotation appears just before the class definition of the entity, and has two required attributes: name, with the unique name for this query; and query, the JPQL query definition.
2.Right-click in the editor window and select Format. 
3.Right-click in the editor window and select Fix Imports. 
4.From the File menu, choose Save.

4.3.Creating the enterprise bean.
DukesBirthdayBean is a stateless session bean. Stateless session beans are enterprise beans that do not maintain a conversational state with a client. With stateless session beans, the client makes isolated requests that do not depend on any previous state or requests. If an application requires conversational state, use stateful session beans.
To create DukesBirthdayBean, create one Java class: DukesBirthdayBean, the enterprise bean class. DukesBirthdayBean is a local enterprise bean that uses a no-interface view, meaning two things. First, a local enterprise bean is only visible within the application in which it is deployed. Second, enterprise beans with a no-interface view do not need a separate business interface that the enterprise bean class implements. The enterprise bean class is the only coding artifact needed to create a local, no-interface enterprise bean.
DukesBirthdayBean will be packaged within the same WAR file as the Facelets web front-end.

4.3.1.Create the DukesBirthdayBean enterprise bean class.
Follow these steps to create the enterprise bean class in NetBeans IDE.
1.Select the firstcup project in the Projects tab. 
2.From the File menu, choose New File. 
3.In the Categories pane, select Enterprise JavaBeans. 
4.In the FileTypes pane, select Session Bean. 
5.Click Next. 
6.In the EJB Name field, type DukesBirthdayBean. 
7.In the Package field, type firstcup.ejb.
8.Make sure Stateless is selected under SessionType. 
9.Click Finish. 
You should now see the DukesBirthdayBean.java file inside the firstcup.ejb package in the Projects tab. The DukesBirthdayBean.java file should also be open in the editor pane.

4.3.2.Add a logger instance to DukesBirthdayBean.java .
Add a java.util.logging.Logger instance to the session bean for logging events.
1.Directly after the class declaration, paste in the following field definition :- 
private static final Logger logger = 
                                                    Logger.getLogger("firstcup.ejb.DukesBirthdayBean"); 
This code creates a logger for the session bean.
2.Right-click in the editor window and select Format. 
3.Right-click in the editor window and select Fix Imports, then click OK.

4.3.3.Add a business method to DukesBirthdayBean that gets the average age defference of fisrtcup users. 
Add a business method to the DukesBirthdayBean session bean to call the findAverageAgeDifferenceOfAllFirstcupUsers named query in FirstcupUser that returns the average age difference of all users.
1.Below the class definition, add a @PersistenceContext annotation and field of type EntityManager :-
@PersistenceContext
private EntityManager em;
2.Right-click in the editor window and select Fix Imports. 
3.Add a business method called getAverageAgeDifference by copying and pasting the following code :-
public Double getAverageAgeDifference() { 
Double avgAgeDiff = 
(Double) em.createNamedQuery("findAverageAgeDifferenceOfAllFirstcupUsers")
.getSingleResult(); 
logger.info("Average age difference is: " + avgAgeDiff); return avgAgeDiff; 
}
The named query in FirstcupUser is called by using the EntityManager's createNamedQuery method. Because this query returns a single number, the getSingleResult method is called on the returned Query object. The query returns a Double.
4.Right-click in the editor window and select Format. 

4.3.4.Add a business method for calculating the age defference between Duke and the User.
Add a business method that calculates the difference in age in years between Duke and the user and creates a new FirstcupUser entity.
1.Add a business method called getAgeDifference by copying and pasting the following code :- 
public int getAgeDifference(Date date) { 
int ageDifference; 
Calendar theirBirthday = new GregorianCalendar(); 
Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23); 
// Set the Calendar object to the passed in Date 
theirBirthday.setTime(date); 
// Subtract the user’s age from Duke’s age
ageDifference = dukesBirthday.get(Calendar.YEAR) 
- theirBirthday.get(Calendar.YEAR); 
logger.info("Raw ageDifference is: " + ageDifference); 
// Check to see if Duke’s birthday occurs before the user’s. If so, 
// subtract one from the age difference 
if (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) { 
ageDifference--; 
// create and store the user’s birthday in the database 
FirstcupUser user = new FirstcupUser(date, ageDifference);
em.persist(user); 
logger.info("Final ageDifference is: " + ageDifference); 
return ageDifference; 
}
This method creates the Calendar objects used to calculate the difference in age between the user and Duke and performs the actual calculation of the difference in age.
Similar to the DukesAgeResource.getText code, getAgeDifference subtracts Duke's birthday year from the user's birthday year to get a raw age difference. If Duke's birthday falls before the user's, and the raw difference is more than 0, it subtracts one year from the age difference.
A new FirstcupUser entity is created with the user's birthday and age difference, then stored in the Java DB database by calling the EntityManager's persist method.
The final age difference is returned as an int.
2.Right-click in the editor window and select Format. 
3.Right-click in the editor window and select Fix Imports, then OK. 
4.From the File menu, choose Save.

4.4.Creating the web client. 
To create the web client, you need to perform the following tasks :-
■ Create a resource bundle to hold localized messages used by the Facelets pages. 
■ Configure the resource bundle in the configuration file. 
■ Create the DukesBDay managed bean class. 
■ Create the Facelets pages.

4.4.1.Creating a resource bundle.
In this section, you'll create the resource bundle that contains the static text and error messages used by the Facelets pages. The firstcup client supports both English and Spanish locales. Therefore you need to create two properties files, each of which will contain the messages for one of the locales.
Create a Resource Bundle :-
1.Right-click the firstcup project in the Projects tab. 
2.From the popup menu, choose New, then choose Other. 
3.In the Categories pane, select Other. 
4.In the FileTypes pane, select Properties File, then click Next. 
5.In the File Name field, type WebMessages. 
6.In the Folder field, type src/java/firstcup/web as the location of the file. 
7.Click Finish. 
8.After NetBeans IDE creates the properties file, type the following messages or copy them from here to the file :-
Welcome=Hi. My name is Duke. Let us find out who is older -- you or I. 
DukeIs=Duke is 
YearsOldToday=years old today.
Instructions=Type your birthday and click submit. 
YourBD=Your birthday 
Pattern=MM/dd/yyyy 
YouAre=You are 
Year=year 
Years=years 
Older=older than Duke! 
Younger=younger than Duke! 
SameAge= the same age as Duke! 
Submit=Submit 
Back=Back 
AverageAge=The average age difference of all First Cup users is These messages will be referenced from the XHTML pages.
9.From the File menu, choose Save.
10.To add the Spanish translations of the messages, copy the properties file WebMessages_es.properties from
tut-install/firstcup/example/firstcup/src/java/com/sun/firstcup/web to tut-install/firstcup/myexample/firstcup/src/java/firstcup/web.
You can create multiple properties files, each with a set of messages for a different locale. By storing localized static text and messages in resource bundles, you don't need to create a separate set of XHTML pages for each locale.

4.4.2.Configuring the resource bundle in the configuration file.
To make the resource bundle available to the application, you need to configure it in the configuration file, by performing the following task.
Create a Configuration File :-
The faces-config.xml deployment descriptor contains configuration settings for the JavaServer Faces application. JSF applications don't require a deployment descriptor unless they use features that can only be configured in faces-config.xml. In firstcup, the deployment descriptor has settings defining the resource bundle that provides localized strings in English and Spanish.
1.Select the firstcup project in the Projects tab. 
2.From the File menu, choose New File. 
3.In the Categories pane, select JavaServer Faces. 
4.In the FileTypes pane, select JSF Faces Configuration.
5.Click Next, then click Finish.

Configure the Resource Bundle :-
The firstcup application is localized for the English and Spanish languages. JavaServer Faces applications can automatically select the proper language based on the locale of the user's web browser. Specify the default and supported locales in the faces-config.xml file.
1.With the newly created faces-config.xml file open, click XML. 
2.Place the cursor between the opening and closing faces-config tags. 
3.Add the following tag to configure the resource bundle:

The base-name element of the resource-bundle element identifies the fully qualified class name of the resource bundle. The var element identifies the name by which the XHTML pages will reference the resource bundle. The locale-config element identifies the locales supported by the resource bundle.
4.Right-click in the editor window and select Format. 
5.From the File menu, choose Save. 

4.4.3.Creating the DukesBday managed bean class.
The DukesBDay JavaBeans component is a backing bean. A backing bean is a JavaServer Faces managed bean that acts as a temporary data storage for the values of the components included on a particular JavaServer Faces page. A managed bean is a JavaBeans component that a JavaServer Faces application instantiates and stores in scope. The section following this one describes more about managed beans and how to configure them.
This section describes how to create the DukesBDay class. To create the class you need to do the following :-
■ Create the managed bean class. 
■ Add a property that stores Duke's current age from the JAX-RS web service. 
■ Add a property that stores the user's current birth date.
■ Add a property that stores the age difference from the DukesBirthdayBean enterprise bean. 
■ Add a property that stores the absolute value of the age difference. 
■ Add a property that stores the average age difference of all users. 
■ Add a method that calls DukesBirthdaybean.getAgeDifference, sets the absolute age difference, and forwards the user to the display page.

Create the Managed Bean Class :-
Create a JavaServer Faces managed bean class that will subsequently be modified.
1.Right-click the firstcup.web package in the Projects tab. 
2.From the popup menu, choose New, then choose Other. 
3.In the Categories pane, select JavaServer Faces. 
4.In the FileTypes pane, select JSF Managed Bean, then click Next. 
5.In the Class Name field, type DukesBDay. 
6.In the Package field, select firstcup.web. 
7.Select session from the Scope menu. 
8.Click Finish. You should now see the DukesBDay.java file inside the firstcup.web package in the Projects tab. The DukesBDay.java file should also be open in the editor pane. 
9.In the editor pane, find the @Named annotation and modify the value attribute, with the value DukesBDay.The resulting code should look like this: 
@Named(value = "DukesBDay")

Continued....

Reference :- Your First Cup: An Introduction to the JavaTM EE Platform.

E-Mail :- gawesh2020java@gmail.com
Youtube :- https://www.youtube.com/channel/UCwm7djDtBaueTDqXt_GIFKw
Linkedin :- https://lk.linkedin.com/in/gawesh-prabhashwara-792ab1205
Facebook :- https://www.facebook.com/gawesh98
Twitter :- https://twitter.com/gawesh_98
Instagram :- https://www.instagram.com/gawezh/
Tiktok :- https://www.tiktok.com/@gawesh_prabhashwara?lang=en

Post a Comment

0 Comments