Developing and deploying web applications
IBM WebSphere Application Server V8.5 Liberty Profile provides a simplified environment for developing and deploying applications. Whether working in the Liberty profile developer tools or in a third-party text editor, you can quickly build, run, and update applications. Development impact, such as configuration and server restarts, are kept to a minimum to reduce the amount of time it takes to develop new applications. The Liberty profile supports Java SE 6, Java SE 7, and Java SE 8 runtime environment, but the Java EE 7 features require Java SE 7 or later. In this chapter, we describe the benefits of developing applications in the Liberty profile environment.
The chapter contains the following sections:
3.1 Developing applications using the Liberty profile developer tools
The Liberty profile developer tools provide a lightweight, rich environment for developing applications. Using the Liberty profile developer tools simplifies the creation of applications by providing wizards and graphical design tools for Java EE applications. Server configuration tasks are simplified by using the tools. In many cases, the tools can infer what configuration is needed based on the application and update it automatically. Working in the Liberty profile developer tools environment also enables iterative development by republishing applications when you make changes in the integrated development environment (IDE).
In this section, we describe an iterative development scenario involving several technologies that are supported by the Liberty profile server.
3.1.1 Using the tools to create a simple servlet application
In this section, we describe how to develop and deploy a simple servlet application using either the Liberty profile developer tools or a simple text editor. Following the procedure that is described in this chapter reveals the simplicity of developing and updating applications in the Liberty environment.
Liberty profile supports the Java EE Servlet 3.1 API. This book assumes some knowledge of Java EE technologies, so the actual coding of the example servlet is not described here.
The Liberty profile developer tools provide a rich development environment for building web applications. In this section, we take you through the end-to-end process of developing, deploying, and updating an application.
Getting started
Before you begin, make sure that you have installed the Liberty profile server and tools as described in 2.1, “Installing the WebSphere developer tools” on page 38. The following steps outline how to create a new project for later deployment:
1. Begin by creating a web project in the Liberty profile developer tools by using the Create a Web Project wizard from the toolbar, as shown in Figure 3-1.
Figure 3-1 Selecting the Create a Web Project wizard
2. In the first window, give the project the name ITSOWeb and select the Simple project template. Leave Programming Model, as the default value, Java EE. Clicking Next takes you to the Deployment options.
3. Under Target Runtime, make sure that WebSphere Application Server V8.5 Liberty Profile is selected. Leave all other options as the default values, and click Finish. Accept the option to switch to the web perspective if you are prompted to do so.
Building a servlet application
Now add a servlet to the ITSOWeb web project by completing the following steps:
1. Begin by creating a servlet using the Create Servlet wizard:
a. To start the wizard, right-click your ITSOWeb project in the Enterprise Explorer window and select New → Servlet.
b. Use com.itso.example for the package name and HelloITSO for the servlet class name. All other values can be left at the defaults. Figure 3-2 shows the Create Servlet wizard.
Figure 3-2 Create Servlet wizard
2. After finishing the wizard, the HelloITSO.java file is included in the ITSOWeb project. Open the file and add some simple output to the servlet’s doGet method. Figure 3-3 shows an example doGet method.
Figure 3-3 Example doGet method for the HelloITSO servlet
For more information about developing servlets and other dynamic web content, see the Liberty profile developer tools at the following website:
Deploying the application
Before deploying the application, ensure that you created a Liberty Profile Server in the development environment as described in 2.2.1, “Installation using the Liberty profile developer tools” on page 43. To deploy the application, complete the following steps:
1. In the Servers view, locate your Liberty Profile Server. Right-click the server and select Add and Remove.
2. In the resulting window, select the ITSOWeb project and click Add, then click Finish. The web project is now available on the server. You should see output similar to Figure 3-4 on page 62 in the console. If your server is not started, start your server. The application is automatically assigned the context root matching the project name of ITSOWeb. The application start is fast.
Figure 3-4 Output from deploying an application
 
Result: Note the extreme speed of the application start and that it was automatically assigned the context root matching the project name of ITSOWeb.
Verifying the application
To verify the application, open a web browser and go to:
http://localhost:9080/ITSOWeb/HelloITSO
You should see the following output syntax:
Hello, Liberty developer
Updating the application
The Liberty profile server supports hot deployment for all applications. To verify, change the servlet to output a different message in its doGet method. When you save the file, the changes are automatically published to the server. In the console output, notice that the application was stopped, updated, and made available again almost instantaneously. Verify that your changes are active by visiting the HelloITSO page again.
3.1.2 Developing and deploying a JSP application
The Liberty profile server supports the JavaServer Pages (JSP) 2.3 specification. JSP allows you to separate presentation logic from your business logic.
The procedure for creating and deploying a JSP in the Liberty profile developer tools is similar to the procedure for a servlet. To create and deploy, complete the following steps:
1. Begin by creating a new JSP file by right-clicking the ITSOWeb project and selecting New → JSP File.
2. Enter ITSOWelcome.jsp for the name of the page and click Next.
3. On the Select JSP template window, make sure that the template New JSP File (HTML) is selected and click Finish.
4. The ITSOWelcome.jsp page automatically opens in the Rich Page editor. By default, the editor displays a split view that shows both the JSP source and a preview of the output.
Insert some text into the source editor between the body tags. Notice that the preview pane is automatically updated. Figure 3-5 on page 63 shows the JSP editor after adding a form to submit a simple input value to the HelloITSO servlet.
Figure 3-5 Editing the ITSOWelcome JSP file
The Rich Page editor contains several powerful features that are beyond the scope of this book. For more information, refer to the following website:
5. Because the ITSOWeb project is already deployed to the ITSO Example Server, no extra steps are needed to deploy and test the new JSP file. However, to test the JSP file, which is shown in Figure 3-6, open the HelloITSO servlet again and add an implementation for the doPost method. For example, the code, which is shown in Figure 3-6, outputs a message using the value of the JSP’s input field. When you are finished editing the servlet, save and close the file. Notice that the application is automatically updated on the server.
Figure 3-6  Example doPost implementation for the HelloITSO servlet
6. To test the application, enter the link in to your web browser:
http://localhost:9080/ITSOWeb/ITSOWelcome.jsp
You should be able to submit a value in the JSP file and see the output message from the servlet that reflects the value that is given in the input field of the JSP.
3.1.3 Developing and deploying a JSF application
JavaServer Faces (JSF) simplifies the development of user interfaces for web applications by providing the following features:
Templates to define layout
Composite components that turn a page into a JSF UI component
Custom logic tags
Expression functions and validation
Component libraries
XHTML page development
For more information about JSF and the features it provides, refer to the following website:
JSF tools
The Liberty profile developer tools provide a rich development environment for building high-quality JSF applications. In this section, we describe a simple JSF application using JSP files, a managed bean, and navigation rules. For more information about the powerful features that are provided by the JSF tools, refer to the following IBM Knowledge Center website:
Enabling JSF in a web project
To enable JSF in a web project, right-click the project and select Properties. Click Project Facets and enable JavaServer Faces, as shown in Figure 3-7. Click OK to close the properties.
Figure 3-7 Enabling JSF in a web project
Feature enablement
To reduce the impact and resource usage, the Liberty profile server enables only features that are actively being used. When you create a server using the Liberty profile developer tools, the configuration automatically is updated to enable servlets and JSPs. By default, the JSF application run time is not enabled. The server configuration must be updated to run JSF applications.
When you add applications to the server or update the facets of a project that is deployed to the server, the Liberty profile developer tools try to determine what features should be enabled on the server to support the application. If you update the project to add the JSF facet, the tools prompt you to resolve conflicts to add the jsf-2.2 feature to the Liberty profile server. You can add or remove the features by Add or Remove and resolve conflicts, as shown in Figure 3-8 on page 66.
Figure 3-8 JSF feature enablement
You can verify that the change took place by opening the server.xml file and confirming that <feature>jsf-2.2</feature> was added. Also, the console output shows that the jsf-2.2 feature was installed to the server, as shown in Figure 3-9.
Figure 3-9 Console output after JSF feature enablement
Building a JSF application
Now that JSF is enabled in your web project, begin creating a JSF application by opening the WebContent/WEB-INF/faces-config.xml file for editing in the Faces Config editor.
Adding a managed bean and set properties
Complete the following steps to add a managed bean:
1. On the ManagedBean tab, click Session and then click Add to add a session scoped managed bean.
2. In the resulting window, click Create a new Java class for the managed bean.
3. A window opens and in that window, create a class named UserManagedBean in the com.itso.example package.
4. Go through the remaining windows in the managed bean wizard by clicking Next and then Finish.
Figure 3-10 shows the ManagedBean configuration after the wizard finishes.
Figure 3-10 ManagedBean configuration for UserManagedBean
Now that the managed bean is added, complete the following steps to edit the UserManagedBean class:
1. Open the UserManagedBean class for editing.
2. Add String fields named user and location.
3. Add a getter and setter for both fields.
4. Add a method named, clear that sets both fields to null and returns the string “clear”.
5. Add a method that is named submit that simply returns the string “submit”.
Example code for the UserManagedBean class is shown in Figure 3-11 on page 68.
Figure 3-11 Example UserManagedBean code
To further edit the properties of the managed bean, complete the following steps:
1. Go back to the Faces Config editor for the managed bean. You can set initial values for the managed bean’s properties by clicking Add under the Initialization section.
2. From the property name drop-down menu, select the Name property. In the value field, enter Liberty User (Figure 3-12).
Figure 3-12 Adding a Managed Property
3. Repeat the process for the location property. In the value field, enter Liberty User Location.
Adding JSF-enabled JSP files
Create three JSP files, input.jsp, visit.jsp, and goodbye.jsp using the Create JSP wizard. To create each file, in the wizard’s template selection page, select New JavaServer Faces (JSF) Page (html).
The input.jsp file asks for two input parameters, a name and a location. The values are taken from the managed bean userManagedBean. Figure 3-13 shows example code to accomplish this process.
Figure 3-13 Example code for input.jsp
The visit.jsp file outputs the name and location value from the userManagedBean. It then displays a button to return to the previous page, and a button to quit the application. Figure 3-14 shows example code for visit.jsp.
Figure 3-14 Example code for visit.jsp
The goodbye.jsp file outputs the name value and has a command button that allows you to start over. Example code is shown in Figure 3-15.
Figure 3-15 Example goodbye.jsp file
Adding navigation rules and setting outcome properties
To add navigation rules, complete the following steps:
1. In the Faces Config editor, click the tab that is labeled Navigation Rule. Drag each of the three JSP files you created in the editor.
2. Create links between the files. If the palette is not already displayed, select Window  Show View  Palette. On the palette, click Link, and then click the input.jsp file. End the link by clicking the visit.jsp file. You should now see an arrow pointing from input.jsp to visit.jsp.
3. On the palette, click Select and then click the new link and view the properties in the properties view. If the properties view is not available, select Window  Show View → Properties. In the outcome field of the properties, enter submit.
4. Follow the same procedure to create a link between the visit.jsp file and the goodbye.jsp file, and set the outcome field to goodbye.
5. Create a link between the goodbye.jsp file and the input.jsp file, and set the outcome property to clear.
6. Finally, create a link from the visit.jsp file back to the input.jsp file and set the outcome to clear.
Figure 3-16 shows the navigation rule window after all the rules are created.
Figure 3-16 JSF navigation rules
Testing the application
Access the application by visiting the following website:
http://localhost:9080/ITSOWeb/faces/input.jsp
 
Result: Notice how the managed bean fields were initialized without having to add code in the JSP. Also, notice that the application navigates to the correct pages based on the navigation rules without having to embed navigation logic in the JSP files.
3.1.4 Developing and deploying JAX-RS applications
The Java API for RESTful Web Services (JAX-RS) simplifies the development of applications that use Representational State Transfer (REST) principles.
More information about JAX-RS is available at the following website:
Building a simple JAX-RS application
To build and configure a JAX-RS application in the Liberty profile developer tools, complete the following steps:
1. To enable the JAX-RS facet on the web project, right-click the project and select Properties. Click Project Facets and enable JAX-RS by selecting the check box next to JAX-RS (REST Web Services). And select 2.0 from the pull-down list next to JAX-RS (REST Web Services), as shown in Figure 3-17.
Figure 3-17 Web project facet list
2. After Enabling JAX-RS (REST Web Services), you see a blue i mark below the window with a note that further configuration is available.
3. Clicking the note opens a window with various configuration options for JAX-RS. Enable the check box next to Update Deployment Descriptor. You can leave all of the values on this window as their defaults and click OK. If you open the web.xml file for the web project, you notice that a servlet and servlet mapping were added for JAX-RS.
Feature enablement
As with JSF, the Liberty profile server does not load the JAX-RS run time unless it is actively being used. Click OK on the facet window to enable the feature. If you load the server.xml file, in the source view, you notice that <feature>jaxrs-2.0</feature> now is added to the list of feature definitions.
Creating an application class
A JAX-RS application class is used to define the classes that are used in the application. Create one now by creating a new Java class that extends the javax.ws.rs.core.Application. The class should contain a getClasses() method that returns the classes that are involved in the application, as shown in Figure 3-18 on page 72.
Figure 3-18 JAX-RS application class
Creating the ITSOJaxrsExample class
To create the class for your JAX-RS, complete the following steps:
1. Create a Java class named ITSOJaxrsExample or import the class that is included in the download material for this book. For more information, see Appendix A, “Additional material” on page 251.
2. The class must be annotated with @Path(“/example”) to indicate that the class is used with requests to the ITSOWeb/jaxrs/example.
3. Add a method that is called getString that returns a javax.ws.rs.Response object. The method must be annotated with @GET. Also, add a method that is called postString that takes a string as a parameter and returns a response object. The postString method should be annotated with @POST.
Figure 3-19 shows an example of the completed class.
Figure 3-19 JAX-RS resource class
Adding a servlet initialization parameter
The servlet that was added when we updated the web project to enable the JAX-RS facet must know about your application class. This is done by creating an initialization parameter for the JAX-RS Servlet. To create an initialization parameter, complete the following steps:
1. Open the web.xml file in the design editor and right-click JAX-RS Servlet.
2. Select Add  Initialization Parameter.
3. On the resulting details window, enter javax.ws.rs.Application in the name field and the name of your Application class in the value field, as shown in Figure 3-20 on page 73.
Figure 3-20 Creating an initialization parameter for the JAX-RS servlet
Testing your application
To test your application, open a web browser and visit the following website:
http://localhost:9080/ITSOWeb/jaxrs/example
You should see the output Hello ITSO from JAX-RS.
 
Note: When you access web applications with JAX-RS enabled, you might see the error (shown in Example 3-1) displayed in the console output. This message does not represent a functional error and can be safely ignored.
Example 3-1 Error message with JAX-RS enabled
[ERROR ] An exception occurred during processing of the org.apache.wink.server.internal.providers.exception.EJBAccessExceptionMapper class. This class is ignored.
Creating the ITSOJaxrsExampleClient class
The Liberty profile supports Java EE Client API for JAX-RS (JAX-RS client) and provides the JAX-RS client wizard to create the JAX-RS client class.
To create the class for your JAX-RS client, complete the following steps:
1. Begin by opening ITSOWeb → Services → REST.
2. Right-click /example : com.itso.example.ITSOJaxrsExample, and select Generate → JAX-RS Client, as shown in Figure 3-21.
Figure 3-21 Open JAX-RS client wizard
3. Use ITSOJaxrsExampleClient for the class name and com.itso.example.client for the package name, and enable Generate JAX-RS Client Filter. All other values can be left as default. Click Finish.
The window in Figure 3-22 shows the JAX-RS client wizard.
Figure 3-22 JAX-RS client wizard
4. After finishing the wizard, you can verify that the ITSOJaxrsExampleClient.java file and the ITSOJaxrsExampleClientFilter.java file is included in the ITSOWeb project.
5. You do not have to enable the jaxrsClient-2.0 feature because the jaxrs-2.0 feature enables the jaxrsClient-2.0 feature. However, if the Liberty profile uses only the JAX-RS client function, you have to enable the jaxrsClient-2.0 feature.
Using JSON-P in the application
The Java API for JSON Processing (JSON-P) provides a standardized method for constructing and manipulating data to be rendered in JavaScript Object Notation (JSON).The Liberty profile supports JSON-P and provides the JSON-P feature.
You can use JSON-P in the RESTful services. In this part, we describe how you can use JSON-P in JAX-RS applications in the Liberty profile developer tools.
To use JSON-P in the ITSOJaxrsExample class, complete the following steps:
1. Open the ITSOJaxrsExample.java file, and find the @GET annotation.
2. The @Produces annotation under the @GET annotation is used to specify the MIME media types of representations. You should modify the @Produces annotation to remove TEXT_PLAIN and enter APPLICATION_JSON. Entering APPLICATION_JSON informs the client to accept the JSON data.
3. Next, you should modify the getString() method under the @Produces annotation to return JSON data to the client. You should create the JSON object using the createObjectBuilder() method, and add the values using the add() method, and return JSON object, as shown in Figure 3-23 as an example.
Figure 3-23 JSON-P example code
4. Enable the jsonp-1.0 feature in server configuration.
5. To test the application, enter the link in your web browser:
http://localhost:9080/ITSOWeb/jaxrs/example
You should see the JSON data was created by using JSON-P.
3.1.5 Using Context and Dependency Injection in web applications with the Liberty profile developer tools
By using the Context and Dependency Injection (CDI) feature of Java EE 6 and Java EE 7, you can inject resources into your applications. Previous versions of Java EE allowed you to inject certain resources, such as EJBs or a Persistence Context, but the CDI specification allows for more general-purpose resource injection.
CDI also helps manage the lifecycle of beans through annotations. Beans can be defined to live for the life of a request, session, application, or conversation.
For more information about CDI, refer to the following website:
Use the procedure that is outlined in the rest of this section to create a simple faces application that uses JavaBeans that are injected by CDI.
Enabling the CDI project facet
Enable the CDI project facet by completing the following steps:
1. Right-click the ITSOWeb project and select Properties. In the window that opens, click Project Facets.
2. Enable the CDI project facet by selecting the check box next to Context and dependency injection (CDI), as shown in Figure 3-24 on page 76. This creates a named beans.xml in the web project. You can find it under WebContent → WEB-INF.
Figure 3-24 Enabling the CDI project facet
Creating a simple bean class
Create a Java class named InjectedBean or import the class that is included in the download material for this book. The class should be annotated with @javax.enterprise.context.RequestScoped to indicate that the bean’s lifecycle is only as long as a single request.
The InjectedBean class should contain one method, getHello(), which simply returns the string “Hello from the injected bean”. The completed class should look like the example in Figure 3-25.
Figure 3-25 The InjectedBean class
Creating another managed bean class
You can inject InjectedBean resources into another managed bean class by using CDI. Now, create a Java class named ExampleBean that uses the InjectedBean to return a value. Add the following actions to the class implementation:
The @javax.enterprise.context.RequestScoped annotation should be added to the class to indicate the bean’s lifecycle.
The annotation @javax.inject.Named(“itsoBean”) should be added to the class to indicate that clients can access this managed bean by the name itsoBean.
The class should have a field of type InjectedBean. The field should be annotated with @javax.inject.Inject to indicate that the value is injected by the container.
The class should have a single method, getMessage() that simply returns the value of injectedBean.getHello().
The completed class should look like the example in Figure 3-26 on page 77.
Figure 3-26 The ExampleBean class
Creating a JSP file to use the managed beans
Creating a JSP file to use the managed beans allows you to access the applications using CDI with web browser.
To create a JSP named cdiExample.jsp, use the Create JSP wizard. In the wizard’s template selection window, click New JavaServer Faces (JSF) Page (html).
In the body of the new JSP file, add an outputText element that has a value of #{itsoBean.message}, as shown in Example 3-2. Earlier, when “Creating another managed bean class”, you annotated the ExampleBean class with @javax.inject.Named(“itsoBean”), so the value for the outputText element is populated with the results of calling getMessage() on an ExampleBean instance.
Example 3-2 Outputting the bean value in cdiExample.jsp
<body>
<f:view>
<h:outputText value=”#{itsoBean.message}”/>
</f:view>
</body>
Testing the application
Test the web application by visiting the link:
http://localhost:9080/ITSOWeb/faces/cdiExample.jsp
 
Result: You should see the output (Hello from the injected bean). Your web application did not have to directly instantiate either the ExampleBean or the InjectedBean class.
3.1.6 Developing JAX-WS web services applications with the Liberty profile developer tools
The Java API for XML Web Services (JAX-WS) allows you to create web services applications in a Java EE environment. The JAX-WS API eases the development of web services applications by allowing developers to expose Java classes as web services using annotations. Developers are freed from having to deal with the complexities of the message format. For more information about JAX-WS, refer to the following website:
JAX-WS support is provided only by WebSphere Liberty profile editions other than the core edition.
Complete the actions outline in the following sections to expose a Java class as a web service in WebSphere Liberty profile.
Creating the service implementation
This example simulates bottom-up web services development where an existing implementation is exposed as a service. To do this, create a simple Java class to act as the service implementation.
Create a Java class in the ITSOWeb project named ITSOGreeter. It should have one method, named getValue, that takes a String as an input. It should return the String Hello, <name> from the ITSO Greeter. The completed ITSOGreeter class is shown in Figure 3-27.
Figure 3-27 The ITSOGreeter class
Creating a web service
To expose the ITSOGreeter class as a web service, complete the following steps:
1. Begin by right-clicking the ITSOWeb project and selecting New → Other. In the “Select a wizard” dialog box, expand Web Services and select Web Service, as shown in Figure 3-28.
Figure 3-28 Web Service wizard selection
2. In the first window of the wizard, click Browse to select the ITSOGreeter class as the service implementation. Leave the web service type as the default, Bottom up Java bean Web Service.
3. On the left side of the window, there is a slider that lets you control how much of the web service is generated. For this example, leave the slider at the default value of Start service.
4. Under Configuration, the server run time should be WebSphere Application Server V8.5 Liberty Profile and the Web Service run time should be IBM WebSphere JAX-WS. These values are set by default, but if they are not, you can click the values to change them.
5. By default, the wizard does not generate client code for the web service. You can change this by moving the lower slider up to Start client. As with the web service configuration, the server run time should be WebSphere Application Server V8.5 Liberty Profile and the Web Service run time should be IBM WebSphere JAX-WS. Figure 3-29 shows the completed wizard window.
Figure 3-29 Web Services wizard
6. Click Next to advance to the next window. The second window has many options for the generated web service. If you plan to use this example code as a starting point for the example in 6.6, “JAX-WS security” on page 194, select the check box next to Generate WSDL file into the project. This step is optional as the example in this chapter works with or without a generated WSDL file, and the file can be generated later if needed.
7. Accept all of the defaults for other options and click Next to advance to the next window.
8. Accept all of the defaults on the WSDL interface options window and click Next.
9. If the Liberty profile server is not started, the next window requires you to start it before proceeding. After it is started, click Next.
10. Accept all defaults on the web service client options window and click Next.
11. Click Finish to complete the wizard. Note the following changes that the wizard made:
 – The wizard created a class named ITSOGreeterDelegate that provides a wrapper for the ITSOGreeter class. The ITSOGreeterDelegate class is annotated with @WebService to expose it as a JAX-WS web service.
 – The wizard created a new EAR project named ITSOWebEAR and added the ITSOWeb dynamic web project to the new project’s modules. It also added the new EAR to the server. You can verify this by loading the server configuration.
 – A new web project named ITSOWebClient was created to contain the JAX-WS client code. In addition to the JAX-WS artifacts, the new project contains JAXB generated classes.
 – A new EAR project named ITSOWebClientEAR was created to contain the ITSOWebClient. The wizard also deployed this EAR to the server.
 
Caution: The code in the client project is generated to use JAX-WS APIs that are not available in JavaSE 6. If you are using JRE Version 6, you might need to change the order of dependencies on the project’s build path so that the Liberty profile runtime dependency precedes the JRE dependency.
Testing the web service
Test the web service by completing the following steps:
1. Make sure that the service side of the web service is working correctly by visiting the link:
http://localhost:9080/ITSOWeb/ITSOGreeterService?wsdl
This should return the WSDL document for the web service. Some web browsers hide XML documents by default. If you see an empty page when visiting the link, you might need to view the source to see the WSDL document.
2. Create a servlet in the ITSOWebClient project to drive the web service client. Using the Create Servlet wizard, create a servlet named JAXWSGreeterClient.
In the servlet’s doGet method, create an instance of ITSOGreeterService. This is one of the client classes that was generated by the web services wizard. Call the getITSOGreeterPort method on the ITSOGreeterService instance to get an ITSOGreeterDelegate instance. Finally, print the value that is returned from calling getValue on the delegate instance.
Figure 3-30 on page 81 shows the completed servlet code.
Figure 3-30 JAXWSGreeterClient servlet code
3. Test the servlet by visiting the link:
http://localhost:9080/ITSOWebClient/JAXWSGreeterClient
 
Result: You should see the output Hello, JAX-WS Client from the ITSO Greeter.
3.1.7 Developing WebSocket applications with the Liberty profile developer tools
WebSocket is a standard protocol that enables a web browser or client application and a web server application to communicate by using one full duplex connection. You can develop the WebSocket 1.0 and WebSocket 1.1 applications that are supported by the Liberty profile V8.5.5.4 and later.
For more information about WebSocket, refer to the following website:
Use the procedure that is outlined in the rest of this section to create a simple WebSocket application.
Creating a WebSocket server endpoint
Create a WebSocket server endpoint named WebSocket or import the class that is included in the download material for this book. In the case of creating, complete the following steps:
1. Begin with selecting the wizard by right-clicking the ITSOWeb project and selecting New → Other.
2. Select WebSocket Endpoint, and click Next. You can filter the entries that are shown in the dialog box by entering web in the search box, as shown in Figure 3-31 on page 82.
Figure 3-31 Selecting WebSocket Endpoint
3. Enter com.itso.example for the Java package and WebSocket for the Class name of the page, and click Finish. You can verify that <feature>websocket-1.1</feature> was added by opening the server.xml file.
4. The WebSocket.java page automatically opens. The class should be annotated with @OnOpen, @OnMessage, @OnClose, and @OnError. The onOpen() method should contain the processing to store the WebSocket session for later use. And the @OnMessage method should contain the processing to close the WebSocket session and to send the messages.
The completed class should look like the example in Figure 3-32 on page 83.
Figure 3-32 WebSocket class
Creating WebSocket client endpoint
Create an html file as the WebSocket client endpoint named WebSocketIndex or import the html that is included in the download material for this book. In the case of creating, complete the following steps:
1. Begin by creating the html file by right-clicking the ITSOWeb project and selecting New → HTML File.
2. Enter WebSocketIndex.html for the File name of the page, and click Next.
3. Select New HTML File (5) for the Templates, and click Finish.
4. The WebSocketIndex.html automatically opens. Insert the JavaScript into the source editor between the body tags. Figure 3-33 on page 84 shows the html file after adding a form to submit a simple value to the WebSocket server endpoint and the processing for WebSocket. The html file should contain the processing for creating a WebSocket object instance and handling the lifecycle events of WebSocket.
Figure 3-33 WebSocketIndex html
Testing the application
Test the web application by visiting the link:
http://localhost:9080/ITSOWeb/WebSocketIndex.html
 
Result: You should be able to submit a value in the html file and see the output message from the WebSocket server endpoint that reflects the value that is given in the input field of the html file. And you should be able to repeat many times. If you submit “close” as the value, you should see the output (Connection closed).
3.1.8 Debugging applications with the Liberty profile developer tools
One of the most powerful features of developing in the Liberty profile developer tools environment is the ability to debug code running on the server directly from the development environment. The following procedure is an example of how you debug a simple application in the Liberty profile developer tools environment.
To debug applications, complete the following steps:
1. The server must be run in debug mode. You can start (or restart) the server in debug mode by clicking the bug icon in the Servers view, as shown in Figure 3-34.
Figure 3-34 Restarting the server in debug mode
2. To debug the application, set a breakpoint in the doGet method of the HelloITSO servlet. On most platforms, you can do this by selecting a line in the method and pressing Ctrl+Shift+b. You can also right-click the vertical bar to the left of the line of code and select Toggle Breakpoint.
3. Open a web browser and enter the address for the HelloITSO example:
http://localhost:9080/ITSOWeb/HelloITSO
4. A dialog in the tools prompts you to switch to the debug perspective (unless you configured Eclipse to switch automatically). Click YES, and you see that the debugger hit the breakpoint in the doGet method. Make a change to the method and save the file. Advance past the breakpoint by clicking Resume on the menu bar (or by pressing F8.) The output in the browser changed based on the changes that you made.
3.2 Developing outside the Liberty profile developer tools
Developers who prefer working outside of the Liberty profile developer tools environment can also enjoy a simplified development experience by using the Liberty profile server. Liberty profile is designed to reduce development impact by providing a fast, lightweight environment for application development. The following list covers some of the key design features of the Liberty profile server that contribute to the new environment:
Quick server start
Hot deployment of applications
Dynamic feature enablement
Dynamic configuration
Simple configuration that can be modified in a text editor
These characteristics of the Liberty profile ensure that developers can write, debug, and update applications without wasting time on server restarts or updating configuration through a complex administrative interface.
In this section, we cover several considerations to keep in mind when developing applications outside of the Liberty profile developer tools environment.
3.2.1 Feature enablement
The Liberty profile server only loads into memory the subset of the run time that is being used. You must specifically enable features in the configuration for them to be available to your applications. The following is a list of features that are used in the examples in this chapter:
servlet-3.1 Servlet 3.1
jsp-2.3 JavaServer Pages (JSP) 2.3
jpa-2.0 Java Persistence Architecture (JPA) 2.0
jaxrs-2.0 Java API for RESTful Web Services (JAX-RS) 2.0
jaxrsClient-2.0 Java EE Client API for JAX-RS
jsonp-1.0 Java API for JSON Processing
wasJmsClient-2.0 Java Messaging Service (JMS) Client 2.0
wasJmsServer-1.0 Java Messaging Service (JMS) Server 1.0
cdi-1.2 Context and Dependency Injection (CDI) 1.2
jaxws-2.2 Java XML Web Services (JAX-WS) 2.2
websocket-1.1 WebSocket
Some of those listed features also provide other features. For example, the jsp-2.3 feature contains the EL-3.0 feature. If your server configuration has jsp-2.3 enabled, it does not need to have EL-3.0 additionally specified to run servlets.
When you add or remove a feature, the run time is dynamically updated to enable or disable the function. You can test this by deploying a simple servlet and removing the servlet-3.1 feature from the configuration. When you remove the feature, you see the text in Example 3-3 in the console output.
Example 3-3 Console output after removing the servlet feature
[AUDIT ] CWWKF0013I: The server removed the following features: [servlet-3.1].
If you attempt to load a servlet, the server should fail to respond to the request. Now, enable the servlet-3.1 feature again. You should see the output in Example 3-4 in the console.
Example 3-4 Console output after enabling the servlet feature
[AUDIT ] CWWKF0012I: The server installed the following features: [servlet-3.1].
If you load the servlet now, the request succeeds.
3.2.2 Dynamic application update
By default, applications are automatically updated whenever a change to the application files is made. This allows you to save time that is not lost restarting applications manually.
This behavior can be seen by updating the web.xml file for a deployed web archive (WAR). Make a change, such as changing the value of a servlet mapping, and save the file. Then, load the servlet using the new mapping, and observe that the application is automatically updated.
3.2.3 Common development configuration
Liberty profile uses reasonable default values for configuration whenever possible. Some common cases where you might decide to update the configuration during development are covered next in this section.
Context root for web applications
Unless it is explicitly defined in the server.xml file or in the application, the context root for a web application is automatically determined from the file name of the WAR file. By default, the value of the context root is the WAR file name without the WAR extension. If you want to change the value of the context root, it can be specified in the configuration using the application definition that is shown in Example 3-5.
Example 3-5 An application definition from server.xml
<webApplication contextRoot=”myWebAppRoot” location=”ITSOWeb.war” />
HTTP server ports
The default port for HTTP requests is 9080. You can also change this value in the configuration. To change the port to 9090, add the endpoint definition in Example 3-6 to the server.xml file. Setting the host value to * allows you to access this server from a different host machine. The default value for host is localhost, which limits access to browsers running on the local host machine.
Example 3-6 An endpoint definition from server.xml
<httpEndpoint id=”defaultHttpEndpoint” host=”*” httpPort=”9090”/>
3.2.4 Dynamic configuration
Dynamic configuration updates in Liberty profile server mean that you do not have to waste time restarting the server when you make changes to the configuration. This section covers some scenarios that display the benefits of dynamic configuration updates.
Changing the HTTP server port
If port 9080 is in use on your machine or you are running multiple server instances, you might want to change the default HTTP port. With the server running, add the endpoint configuration, which is shown in Example 3-6, to your server.xml file. Save the file, and try to access a web application from the updated port. The server did not need to restart to make this change.
Adding a JNDI entry
Liberty profile server gives you the ability to bind JNDI entries in the configuration. These values are automatically updated when they are added, updated, or removed from the configuration.
Before using JNDI, you must add the JNDI-1.0 feature to your server’s configuration.
To test this, create a simple servlet and add code similar to that shown in Figure 3-35 on page 88.
Figure 3-35 Look up a value using JNDI
Run the servlet, and notice that the servlet was unable to find the value. Now, add the XML element in Example 3-7 to the server.xml file.
Example 3-7 XML element in server.xml file
<jndiEntry value="This is a sample value" jndiName="jndi/exampleValue"/>
Save the file and without restarting the server, run the servlet again. Notice that it now prints out the value that was set in the server configuration. You can also test updating the value or removing the jndiEntry element. In each case, the server is dynamically updated without a restart.
 
Caution: Only the server configuration is dynamically updated. Values are only read from bootstrap.properties when the server starts, so any value changes do not take place until you restart the server.
3.2.5 API JAR files
API JAR files for technologies that are included in the Liberty profile server are in the dev directory under the Liberty profile server home directory. The following list notes those directories:
Java EE APIs are in dev/api/spec.
IBM APIs are in dev/api/ibm.
Third-party APIs are in dev/api/third-party.
The following list shows the API JAR files that are used for technologies that are covered in this chapter:
Servlets
dev/api/spec/com.ibm.ws.javaee.servlet.3.1_1.0.9.jar
JSP
dev/api/spec/com.ibm.ws.javaee.jsp.2.3_1.0.9.jar
JSF
dev/api/spec/com.ibm.ws.javaee.jsf.2.2_1.0.9.jar
dev/api/spec/com.ibm.ws.javaee.jsf.tld.2.2_1.0.9.jar
dev/api/spec/com.ibm.ws.javaee.jstl.1.2_1.0.9.jar
JAX-RS
dev/api/spec/com.ibm.ws.javaee.jaxrs.2.0_1.0.9.jar
dev/api/ibm/com.ibm.websphere.appserver.api.jaxrs20_1.0.9.jar
dev/api/third-party/com.ibm.websphere.appserver.thirdparty.jaxrs_1.0.9.jar
CDI
dev/api/spec/com.ibm.ws.javaee.cdi.1.2_1.2.9.jar
JMS
dev/api/spec/com.ibm.ws.javaee.jms.2.0_1.0.9.jar
JAX-WS
dev/api/spec/com.ibm.ws.javaee.jaxws.2.2_1.0.9.jar
 
Caution: Only spec and ibm-api libraries are visible to applications by default. See 3.3, “Controlling class visibility in applications” on page 93 for more information about class visibility.
3.2.6 Debugging applications
You can use a Java debugger to debug your applications by starting the server in debug mode. To do this, start the server with the server debug command. The server waits for a Java debugger to attach on port 7777 before starting. Optionally, you can change the port that the server uses for debugging by setting the value of WLP_DEBUG_ADDRESS to the wanted port in your operating system’s environment.
3.2.7 Using Maven to automate tasks for the Liberty profile
Apache Maven is a build scripting tool that is designed to hide some of the complexities of build management from the user. Maven simplifies dependency management by maintaining a set of versioned artifacts in a repository.
Liberty profile enables building with Maven by providing a plug-in that can be used for common administrative tasks and a repository that contains certain API JAR files.
Plug-in repository
To use Maven for automating development tasks, first include the Liberty profile plug-in, in your project’s pom.xml file. The plug-in is in a public central repository. Example 3-8 shows a sample plug-in definition.
Example 3-8 Maven plug-in repository definition
<pluginRepository>
<id>Liberty</id>
<name>Liberty Repository</name>
<url>http://public.dhe.ibm.com/ibmdl/export/pub/software/websphere/wasdev/maven/repository/</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
Specifying the plug-in and configuration
Example 3-9 shows how to load the Liberty Maven plug-in and specify a basic configuration. The configuration for serverHome and serverName is optional, but if it is not specified, it generally must be passed in as an argument when running from the command line.
Example 3-9 Loading and configuring the Liberty plug-in
<build>
<plugins>
<!-- Enable liberty-maven-plugin -->
<plugin>
<groupId>com.ibm.websphere.wlp.maven.plugins</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>1.0</version>
<!-- Specify configuration -->
<configuration>
<serverHome>/opt/IBM/wlp</serverHome>
<serverName>testServer</serverName>
</configuration>
</plugin>
</plugins>
</build>
 
Examples: The following examples pass in the serverHome and serverName as arguments on the command line. These can be omitted if they are specified in the pom.xml file.
Creating a server
Use the following command to create a server named SERVER_NAME in the directory SERVER_HOME:
mvn liberty:create-server -DserverHome=SERVER_HOME -DserverName=SERVER_NAME
Deploying and undeploying applications
Use the following command to deploy an application that is in APPLICATION_FILE to the server named SERVER_NAME:
mvn liberty:deploy -DserverName=SERVER_NAME -DserverHome=SERVER_HOME -DappArchive=APPLICATION_FILE
The server must be started to deploy the application.
Use the following command to undeploy the same application:
mvn liberty:undeploy -DserverName=SERVER_NAME -DserverHome=SERVER_HOME -DappArchive=APPLICATION_NAME
The server must be started to remove the application. In this scenario, the appArchive parameter uses the application name rather than a file path.
Starting and stopping the server
Use the following command line to start a Liberty profile server instance:
mvn liberty:start-server -DserverHome=SERVER_HOME -DserverName=SERVER_NAME
Use the following command to stop a running server:
mvn liberty:stop-server -DserverHome=SERVER_HOME -DserverName=SERVER_NAME
Packaging and installing the server
Use the following command line to package an existing server named SERVER_NAME in a file named ARCHIVE_FILE:
mvn liberty:package-server -DserverName=SERVER_NAME -DserverHome=SERVER_HOME -DpackageFile=ARCHIVE_FILE
Use the following command to install a server from an archive named ARCHIVE_FILE:
mvn liberty:install-server -DassemblyArchive=ARCHIVE_FILE
Dependency repositories
The API JAR files that are in the dev/ibm-api directory underneath the Liberty Profile Server home directory are also available in a public Maven repository. To use the repository, add the repository definition in Example 3-10 to your pom.xml file.
Example 3-10 Maven repository definition
<repository>
<id>wlp.central</id>
<url>http://public.dhe.ibm.com/ibmdl/export/pub/software/websphere/wasdev/maven/repository</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
Example 3-11 provides an example of referencing a specific artifact dependency. In this scenario, the example is referencing the IBM JAX-RS extension APIs.
Example 3-11 IBM JAX-RS extension APIs
<dependency>
<groupId>com.ibm.websphere.appserver.api</groupId>
<artifactId>com.ibm.websphere.appserver.api.jaxrs</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
Java EE dependencies, such as the servlet API, are not available in the IBM repository. These dependencies can be accessed by using the repository definition in Example 3-12.
Example 3-12 Repository definition
<repository>
<id>java.net</id>
<url>http://download.java.net/maven/2</url>
</repository>
The dependency definition in Example 3-13 shows how to reference the Java EE 7API.
Example 3-13 Java EE 7API reference
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
3.2.8 Using Ant to automate tasks for the Liberty profile
Liberty profile provides an Ant plug-in so you can automate build processes that include management of the server and applications.
Ant plug-in
The Liberty profile Ant plug-in is in the dev/tools/ant directory under the server home directory. To use the plug-in, you must make it available on the class path. To make the plug-in available, copy the plug-in JAR file to the lib directory of the Ant installation and reference it using an antlib namespace, as shown in Example 3-14.
Example 3-14 Using antlib to include the Ant plug-in
<project .... xmlns:wlp="antlib:com.ibm.websphere.wlp.ant">
...
</project>
Deploying and undeploying applications
You can automate the addition and removal of applications using the deploy and undeploy tasks that are shown in Example 3-15.
Example 3-15 Example of deploy and undeploy tasks
<wlp:deploy file="${basedir}/resources/ITSOExample.ear" timeout="40000"/>
 
<wlp:undeploy file="ITSOExample.ear" timeout="60000" />
Server administration
The following tasks are available for automating server administration tasks:
Create
<wlp:server installDir=”${wlp_install_dir} operation=”create”/>
Start
<wlp:server installDir="${wlp_install_dir}" operation="start" serverName="${serverName}" />
Stop
<wlp:server installDir=”${wlp_install_dir}” operation=”stop” serverName=”${serverName}” />
Status
<wlp:server installDir=${wlp_install_dir}” operation="status"/>
Package
<wlp:server installDir=”${wlp_install_dir}” operation=”package” archive=”packagedServer.zip”/>
3.3 Controlling class visibility in applications
Class visibility in the Liberty profile server is controlled by configuring a classloader for an application in the server configuration. Defining the classloader allows you to share common libraries with other applications and control the types of APIs that are visible to the application. Defining the classloader also ensures that applications load classes from their own libraries before using classes from the Liberty profile server run time.
3.3.1 Using shared libraries in applications
Java EE application development often involves using common utility JAR files across several applications. You can avoid having to maintain several copies of the same utility JAR files by using shared libraries.
A library, in the Liberty profile server, is composed of a collection of file sets that reference the JAR files to be included in the library. The library can be used in an application by creating a classloader definition for the application in the server configuration. The application classloader can share the in-memory copy of the library classes with other applications, or it can have its own private copy of the classes that are loaded from the same location.
Shared libraries, which are defined in the configuration, can be used only by applications that are explicitly configured in the server.xml file. Applications without configuration, such as those placed in the dropins directory, can use a global shared library, as described in 3.3.5, “Global libraries” on page 95.
3.3.2 Creating a shared library in the Liberty profile developer tools
To create a shared library in the Liberty profile developer tools, complete the following steps:
1. Load the server.xml file in the design editor.
2. Right-click the application and click Add  Classloader.
3. In the Classloader properties, click New next to Shared library references.
4. On the Shared Library details window, click New next to the Fileset reference to add a file set.
5. Enter the properties for the file set details window and save the server.xml file.
Look at the source view for the server.xml file. The application now contains a classloader, which contains a library, which contains a file set. Example 3-16 on page 94 shows the resulting configuration from the server.xml file.
Example 3-16 Shared library configuration in server.xml
<classloader >
<commonLibrary>
<fileset includes=”utility.jar”/>
</commonLibrary>
</classloader>
The Liberty profile configuration is flexible enough to allow many configuration elements to be specified either as a child of a parent element, or as an attribute reference from that parent element. The shared library configuration in 3.3.3, “Creating a shared library outside of the tools” on page 94 displays how some of the same configuration can be specified using references.
 
Caution: The Liberty profile developer tools use slightly different terminology than the server configuration file. A library in the tools is equivalent to a privateLibrary in server.xml. A shared library in the tools is equivalent to a commonLibrary in server.xml.
3.3.3 Creating a shared library outside of the tools
To create a shared library outside of the Liberty profile developer tools, you must manually edit the server.xml file to add the following items:
A file set that references the JAR files on disk.
A library that either contains or references the file set.
A classloader for each application that uses the shared library. The classloader should reference the library element. If you want the application to share the in-memory copy of the library, use the commonLibraryRef attribute to reference the library. If you want the application to have its own copy of the library, use the privateLibraryRef attribute.
Example 3-17 shows the definition of a shared library that is used by two different applications. Both applications share an in-memory copy of the classes.
Example 3-17 Definition of two applications using the same shared library
<library id=”loggingLibrary”>
<fileset dir=”${server.config.dir}/logger” includes=”ITSOLogger.jar”/>
</library>
 
<application name=”ITSOApp1” location=”ITSO_1.ear”>
<classloader commonLibraryRef=”loggingLibrary”/>
</application>
 
<application name=”ITSOApp2” location=”ITSO_2.ear”>
<classloader commonLibraryRef=”loggingLibrary”/>
</application>
3.3.4 Using libraries to override Liberty profile server classes
The Liberty runtime hides its internal Java packages from application classloaders and only exposes the defined APIs. Also, you should configure only the features that you require into your server. For these reasons, it is unlikely that you will need to override Liberty profile server classes, but this section describes how you can do that if you find it necessary. You can accomplish this by creating a shared library that contains the classes you want to use. Use the following options:
In the Liberty profile tools
On the classloader properties window, change the value in the drop-down menu for delegation to parentLast.
Outside the Liberty profile tools
To change the classloader delegation outside the Liberty profile developer tools, add the delegation=”parentLast” attribute on the classloader element in the server.xml file.
3.3.5 Global libraries
The Liberty profile server allows you to provide a library or set of libraries that can be accessed by all applications. To add a JAR file to this global shared library, simply copy it to one of the following two locations under ${WLP_USER_DIR}:
shared/config/lib/global
servers/server_name/lib/global
The libraries in these directories are used by all applications that do not specifically define a classloader. If you define a classloader for an application, the global library classes are not available unless you add the library global as a shared library. The sample configuration in Example 3-18 shows an application that is configured to use the global shared library.
Example 3-18 Application using a global shared library
<application name=”ITSOApp1” location=”ITSO_1.ear”>
<classloader commonLibraryRef=”global”/>
</application>
3.3.6 Using a classloader to control API visibility
By default, an application in Liberty profile can see supported specification APIs (such as the Java EE Servlet specification) and IBM provided APIs. For the application to load classes from third-party libraries, such as those in dev/third-party, you must configure the allowed API types for the application classloader. In the Liberty profile developer tools, you can configure this value in the Allowed API types field on the classloader service details window. If you are directly editing the server.xml file, add the apiTypeVisibility attribute to the classloader element. In both cases, the value is to be a comma-separated list of any combination of the following items:
spec Supported Specification Libraries
ibm-api IBM provided APIs
ibm-spi IBM provided SPIs
third-party Third-party APIs
For example, the following classloader element allows an application to see specification libraries, IBM provided APIs, and third-party APIs:
<classloader apiTypeVisibility="spec,ibm-api, third-party"/
 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset