45,59 €
Your one stop solution to create highly scalable enterprise grade Java applications with WildFly.
If you are a Java developer with at least basic knowledge of Java EE, then this book is for you. No previous knowledge of WildFly is required.
Packed with rich assets and APIs, Wildfly 10 allows you to create state-of-the-art Java applications. This book will help you take your understanding of Java EE to the next level by creating distributed Java applications using Wildfly.
The book begins by showing how to get started with a native installation of WildFly and it ends with a cloud installation. After setting up the development environment, you will implement and work with different WildFly features, such as implementing JavaServer Pages. You will also learn how you can use clustering so that your apps can handle a high volume of data traffic. You will also work with enterprise JavaBeans, solve issues related to failover, and implement Java Message Service integration. Moving ahead, you will be working with Java Naming and Directory Interface, Java Transaction API, and use ActiveMQ for message relay and message querying. This book will also show you how you can use your existing backend JavaScript code in your application.
By the end of the book, you'll have gained the knowledge to implement the latest Wildfly features in your Java applications.
Each part of this book shows you how to use different features of WildFly 10 to create enterprise grade Java applications as easily as possible.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 461
Veröffentlichungsjahr: 2017
Create Enterprise-grade Java applications with WildFly
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2017
Production reference: 1160617
www.packtpub.com
Author
Luca Stancapiano
Copy Editors
Shaila Kusanale
Vikrant Phadkay
Reviewers
Alexandre Arcanjo de Queiroz
Deepak Vohra
Project Coordinator
Ritika Manoj
Commissioning Editor
Amarabha Banerjee
Proofreader
Safis Editing
Acquisition Editor
Shweta Pant
Indexer
Tejal Daruwale Soni
Content Development Editor
Mohammed Yusuf Imaratwale
Graphics
Jason Monteiro
Technical Editor
Murtaza Tinwala
Production Coordinator
Shantanu Zagade
Luca Stancapiano has been working in the IT industry since 2000. He specializes in Java EEand JBoss, and has collaborated with Apache, Alfresco, Atliassian,EXo, and JBoss communities on several open source products for many years.He lives in Italy and collaborates with leading consulting companies for design andimplementation of applications for both government and private companies dealingwith information, finance, and transport.Abroad, he is known for his interventions at the Daily Telegraph in portals. He brings projects such as Wildfly, Alfresco ECM, Activiti, JGroups, Arquillian, ExoPortal, Solr, Infinispan, JBoss Portal ,Gatein, Jira, and Confluence, and manages Vige, an open source community specializing in open government and smartcities.He is one of the authors of the Gatein Cookbook, showing Gatein's portal and how to develop portlets with it, published in 2012 by Packt.
Alexandre Arcanjo de Queiroz is a Brazilian software developer who graduated from the Faculty of Technology of Sao Paulo, a renowned institution in his country. He has experience in developing applications using Java EE and Spring Framework.
He currently works as senior software engineer for Geofusion. Geofusion is the leader in geomarketing in Brazil, and offers an online platform called OnMaps, which is indispensable for companies seeking expansion and assistance in more accurate decision making.
He worked as a technical reviewer for the books Spring Cookbook, Advanced Java EE Development with WildFly, and Enterprise Application Development with ExtJS, and in the Building Applications with ExtJS video course.
Deepak Vohra is a consultant and principal member of the NuBean.com software company. Deepak is a Sun Certified Java programmer and Web component developer, and has worked in the fields of XML, Java programming, and Java EE for 10 years. Deepak is the co-author of the Apress book Pro XML Development with Java Technology and was the technical reviewer for the O'Reilly book WebLogic: The Definitive Guide. He was also the technical reviewer for the course technology PTR book Ruby Programming for the Absolute Beginner. Also, he is the author of Packt's books JDBC 4.0 and Oracle JDeveloper for J2EE Development, Processing XML Documents with Oracle JDeveloper 11g, EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g, Java EE Development in Eclipse IDE, Advanced Java EE Development with WildFly.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787287173.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Introducing Java EE and Configuring the Development Environment
JSON and HTML5
WebSockets
Simplified JMS 2.0 API
Groundwork for Cloud environments
Batch applications
Updated web profiles
Concurrency utilities
Context dependency injection
Java API for RESTful web services (JAX-RS) 2.0
Servlet 3.1
JNDI
Asynchronous invocation
Timers
EJB Lite
Development in WildFly
Operating system
Java
Application server
Build system
Structure of the exercises
Tests
IDE
Netbeans IDE
IntelliJ IDEA
Eclipse IDE
Importing exercises
Debug exercises
Summary
Working with Dependency Injection
Dependency injection 1.0 for Java
Qualifiers
EL name resolution
Resources
Context and dependency injection 1.1 for Java
Injection and contexts
Managed beans
Producer methods and fields
Bean types
The BeanManager object
CDI
Unmanaged
Enabled and disabled beans
The injection target
Scopes
Session beans
Service Provider Interfaces
Events
Event qualifiers
Observer methods
Container lifecycle events
Utilities
Decorators
Enabled decorators
And more...
Model
TransientReference
Interceptors 1.2
Interceptor classes
Associating an interceptor class with the target class
Default interceptors
Interceptors for lifecycle callbacks
Interceptor bindings
Common annotations for the Java platform 1.2
Common annotation
SQL utilities
Web console for monitoring beans
Summary
Persistence
Common JPA annotations
Named queries
Relationships
Cascade on one-to-one and one-to-many
Cascading the one-to-one persist operation
Cascading the one-to-one merge operation
Cascading the one-to-one delete operation
The one-to-one delete orphan cascading operation
Cascade on Many To Many
Cascade of the persist many to many operation
Dissociation of one side in the many to many association
Tricks for many to many CascadeType.REMOVE
Conclusion
News from Java EE 7
Result set
Stored procedures
Converters
Named entity graphs
JPQL improvements
API Criteria bulk operations
Unsynchronized persistence context
Indexes
Packages and entities
DataSources and connectors
Deployment of the DataSource
DS file
XA and non XA
Activating the deployer
XML configuration
Web console
Summary
Implementing Business Logic
Scopes in EJB
Singleton
Local and remote interfaces
Remote clients
EJB client library
Remote naming project
Combining the remote naming project and EJB client library
Local and remote homes
The session context
Transactions
Exceptions
Transaction management annotation
Transaction attributes
Security
EJB container configuration
Session beans
Stateless
Stateful
Singleton
Entity beans
Remote
Thread pools
IIOP
In VM remote interface invocations
Summary
Working with Distributed Transactions
Transaction overview
BMT and CMT
Descriptor configuration
Remote transaction
Transactions and resource managers
ACID properties
Enterprise concurrent API
Managed executor service
Set of threads
Transactional tasks
Levels and transaction isolation problems
Isolation violations
Dirty read
Non-repeatable read
Phantom read
Isolation levels
Read committed
Read uncommitted
Repeatable read
Serializable
Transaction models
Flat transactions
Savepoints
Nested transactions
Saga
Chained transactions
Distributed transactions and the JTA
Distributed transaction scenarios
Multiple databases
Message queue and database
Multiple application servers
Transaction started by the client
Two-phase commit
Emulating two-phase commit
Summary
Creating REST Services
Services
REST and HTTP
GET methods
POST methods
PUT methods
HEAD methods
OPTIONS method
DELETE method
Using RESTEasy directly
REST application and components
Container components
Container request filter
Container Response Filter
Name binding
Providers
Client components
Client Request Filter
Client Response Filter
Interceptors
Reader interceptors
Writer interceptors
Features
Contracts
Dynamic features
Forms and beans
Selenium and Drone
Summary
Implementing WebSockets
History of the web
Implementation engine
A first basic example
WebSocket container
WebSocket session
Security
HTTPS
Security realm
Custom HTTPS configuration
WebSocket HTTPS connection
Negotiated subprotocols
Configurators for requests and responses
Request informations and parameters
Path parameters
Request parameters
Other features
Container configuration
Runtime configuration
Client WebSockets
Basic client
Async client
Message handlers
Whole
Partial
Custom message handler registration
Ajax versus WebSockets
Summary
Working with Messaging
Queues and topics
Queues
Creating the queue from the web console
Creating the queue using CLI and Maven WildFly plugin
Creating the queue through an Arquillian test case
Create the Java client for the queue
Topics
Creating the topic from the web console
Creating the topic with the Maven WildFly plugin
Creating the topic through an Arquillian test case
Creating the Java client for the topic
Remote clients
Message listeners
The JMS context
Summary
Implementing a Mail Client
Mail client API
Java example
Creating a client with Java SE
Configuration of the mail server
SMTP local mail server
Summary
Asynchronous REST
Asynchronous resources
REST timeouts
REST server callbacks
Connection callbacks
Asynchronous clients
Asynchronous client callbacks
Summary
Asynchronous EJB
The asynchronous annotation
Timers and schedulers
Timer service
File configuration
Timer configuration
Access timeout
Old specs compliant
Stateful timeout
Schedulers
Transactions and timers
Message driven beans
Message driven bean context
Acknowledge mode
Summary
Batches and Workflows
Workflows and BPM
Batch models
Chunks
Chunk and ETL
Chunk Reader
Chunk processor
Chunk writer
Client
Batchlets
Decision
Mail example
Client
Job context and step context
Metrics and step execution
Listeners
Job listener
Step listener
Chunk listener
Batch property
Checkpoint Algorithm
Checkpoint timeout
Exceptions
Monitoring of the batches
Deploying the workflows
Summary
Working with Servlets and JSP
Undertow
Servlets and web components
Ports and security
Request and response
Cookies
JSP pages
EL Expressions
Cookies operations
Web session and other scopes
Creation of a cookie
Cookies and JavaScript
Tests with Selenium
Error mappings
File configuration
File upload
Filters
HTTP servlet response wrapper
Event listeners
Session listener
Session ID listener
Servlet request listener
Servlet request attribute listener
Session attribute listener
Session binding listener
Session activation listener
Servlet context listener
Servlet context attribute listener
Asynchronous servlet
Non blocking I/O
Protocol handler
Dynamic context registration
External resources and themes
Web fragments
Security
File descriptor security
Programmatic security
Form login
Create a custom JAAS module
Summary
Writing a JSF Application
MVC
Components
Use
Structure
Configuring and developing your application
Internationalization
Navigation
Navigation inside the page
Phases and listeners
Working with Facelets
Web templates
Custom functions
Custom tags
Security
ACL permissions and PicketBox
Summary
Sharing the Web Sessions
Clustering
Infinispan
Distributable applications
Cluster domains
Customize the domains
Summary
WildFly in Cloud
OpenShift
WildFly installation
Command-line tools
Exposed services
Summary
Share your Data
Infinispan and the cluster
LRU and LIRS
JGroups configuration
Singleton HA Services
Writing the Service
Writing the Activator
Client for the Service
Summary
Deployment
Deployment types
Enterprise packages
Web archive
Java archive
EJB
Client application
Simple Java library
Resource adapters
Extension packages
Datasources
Service archives
Deployment tools
Administrator tools
HA deploy
Development tools
Summary
Working with OSGi
Modules
OSGi in WildFly
Installation
Deployment of bundles
Maven bundle plugin
Summary
Java EE is the main tool used over the last few decades to develop Information Technology (IT) applications. Java EE has evolved during these years according to the needs of large customers. Large companies such as Oracle, Redhat, and IBM have invested in Java EE by improving it over time, providing feedback and workflows for the JCP specifications, making it more suitable for ever stringent requests from around the world. The Java Community Process (JCP) has favored Java EE, thanks to the contribution of not only these companies but of anyone who is interested in the now-consonant open source philosophy. Many people and companies contribute to open source by providing their expertise and contributing to the design and development of well-known products in information technology. The development of important open source products has also helped improve Java EE. Implementations of Java EE specifics come mainly from the Apache and JBoss communities. JBoss initially emerged as a product implementing Java EE and later became a true open source community; it was the first community to invest in Java EE. WildFly is the evolution of JBoss, an application server that implements Java EE 7 specifications. In this book, we will show all the opportunities that this product can provide customers by focusing on Java EE implementations and some extensions that make WildFly a great alternative to proprietary application servers.
Chapter 1,Introducing Java EE and Configuring the Development Environment, gives an introduction to Java EE, focusing on the novelties introduced in version 7. The book provides several examples, and this chapter will explain how to install and use them when reading the various chapters.
Chapter 2,Working with Dependency Injection, states that dependency injection has brought innovation to the way of programming. The instantiation of automatically rendered objects at the configuration level has made it simpler and more performative in the development of applications, avoiding the problems of lack of memory and memory leaks. Thanks to annotations almost completely replacing XML configurations, development has become even simpler and more portable. In this chapter, we'll see how to use the CDI inside WildFly 10.
Chapter 3, Persistence, explores the significant novelties annotations have brought to the development of entities. It has now become very easy to create objects and make them persistent in a relational database. The JPA deals with this. We will look at the JPA 2.1 features on WildFly 10 in detail, with related examples.
Chapter 4, Implementing Business Logic, says that EJBs are the historical components provided by Java EE to implement the business logic. This chapter will show the novelties and all types of EJBs so that the reader can choose the most suitable component for their needs.
Chapter 5, Working with Distributed Transactions, teaches that distributed transactions are the key element of Java EE. Java Transaction Architecture (JTA) does not need much work to handle transactional operations; it is very easy to handle transactions not only between different applications, but also between different databases and application servers. In this chapter, we will show Narajana, the open source product that implements JTA within WildFly 10 and the possible transaction scenarios.
Chapter 6, Creating REST Services, explains that the latest specifications have conveyed the use of REST as the key to building services. REST is very easy to use, fast, and fits very well with the latest requirements of HTML 5. In this chapter, we will focus on the use of JAX-RS 2.0 implemented by RESTEasy and featured on WildFly since its inception.
Chapter 7, Implementing Web Sockets, states that the main innovation introduced by Java EE 7 is the web sockets that revolutionized the web world as it did in its AJAX times. With web sockets, we finally have a direct channel between the browser and web applications, so asynchronous mechanisms, such as notifications and messaging, make it simpler, safer, and faster.
Chapter 8, Working with Messaging, says thatJMS is a historical framework for Java EE. JMS provides good support for writing clients who receive messages from queues or topics. Version 7 introduces improvements in development by leveraging annotations to write a lot less code. In this chapter, we will analyze the development and configuration of the messaging server implemented by ActiveMQ Artemis.
Chapter 9, Implementing a Mail Client, teaches you tosend emails with JavaMail. WildFly provides a dedicated session for mails to be included in enterprise applications. We will see several examples and how to test them with the open source SubEtha Mail product.
Chapter 10, Asynchronous REST,finishes the work on REST by dwelling on the asynchronous mechanisms introduced in the last two Java EE specifications, such as timeouts and callbacks. We will write examples of clients using REST asynchronous.
Chapter 11, Asynchronous EJB, continues the discussion of EJBs by focusing on new asynchronous mechanisms, such as timers, schedulers, and timeouts, described in Java EE 6 and 7. We will also provide examples of listener and message-driven beans and explain how to support transactions.
Chapter 12, Batches and Workflows, discusses the scheduler's speech by analyzing new batch specifications introduced in Java EE 7. With WildFly 10, you can write rather complex batches and workflows by competing with highly consolidated BPM specifications.
Chapter 13, Working with Servlets and JSP, is entirely dedicated to the web and its Java components. We'll see how undertow, the new engine that implements web connectors, implements servlets 3.1 and JSP 2.3 through several examples of web pages.
Chapter 14, Writing a JSF Application, outlines how to develop Java Server Faces 2.2 applications with the help of the Mojarra engine present in WildFly 10. We will show examples of configurations, navigation, and major JSF components.
Chapter 15, Sharing the Web Sessions, covers how to set up a cluster with WildFly using standalone and domain mode. This chapter will also teach us how the data is propagated with the help of Infinispan, the product that implements the second-level cache, and which allows us to replicate the data in the WildFly cluster.
Chapter 16, WildFly in Cloud, showcases how to install and use WildFly in a cloud machine provided by OpenShift; the chapter will provide details on this product used to manage cloud machines in an open context.
Chapter 17, Share your Data, analyzes Infinispan components and displays network configurations in order to have special configurations depending on the network used.
Chapter 18, Deployment, looks at deployment as a key part of the application server. We will see examples of deploying different applications and custom configurations in this chapter.
Chapter 19, Working with OSGI, takes you through the modular structure of WildFly provided by JBoss modules, a framework that allows a strong personalization of the components that make up WildFly. In addition, we will see an extension of JBoss modules, JBoss OSGI, which allows us to deploy applications through OSGI.
To try the examples, it is important to have an internet connection and a PC or notebook with at least 8 GB of RAM and free space of about 3 GB on the hard drive. The preferred operating system is Linux, but other operating systems that are based on Linux core or have at least one bash shell is also good.
Given the wide array of examples, those who read the book should know the Java language. The knowledge of Java EE is not indispensable as the book proposes to make it known to both bases and details.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Specific commands or tools from the interface will be identified as follows:
Select the Save button.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 20718ms - Started 580 of 816 services (405 services are lazy, passive or on-demand)
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
asyncInvoker
.get(
new
InvocationCallback
<Response>() {@Override
public
void
completed
(Response
response
) {
...
Any command-line input or output is written as follows:
vi $USER_HOME/.bash_profile
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at .www.packtpub.com/authors
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Mastering-Java-EE-Development-with-WildFly. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any Errata, please report them by visiting http://www.packtpub.com/submit-Errata, selecting your book, clicking on the Errata submission form link, and entering the details of your Errata. Once your Errata are verified, your submission will be accepted and the Errata will be uploaded to our website or added to any list of existing Errata under the Errata section of that title.
To view the previously submitted Errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
WildFly 10 is an open source application server compliant with Java EE 7. Once called EJB-OSS and then JBoss, it was always one of the most used in the world. Redhat acquired JBoss and all of the community committed to it in 2005, with effect from version 5. Thanks to an internal Redhat policy, JBoss become WildFly in 2012; since version 8, WildFly is the first implementation of EE 7 by Redhat.
This application server is built with different architectures. Luckily WildFly maintains the same core architecture of the previous JBoss 7, adding some innovation from EE 7, a new set of competitive open source products and a very modular core, which simplify sharing libraries through applications.
So WildFly can be thought of as a set of sub-products all tied together by the same system.
Each of these products has its configuration in an XML file only, so we avoid redundant configurations. There is a web page for each module of these products. Moreover we can use all independent instruments provided if we want a detailed configuration.
The application server is made to maintain applications. A Java application server must be able to manage all classes from the applications; for example, it must deal with duplication classes, managing a more sophisticated class loading system. It must able to cache more frequently used objects to guarantee the fast loading of classes. Since the last enterprise specification, an application server simplifies the developing of real time services providing a wide set of instruments so the developer does not have to write voluminous code to manage asynchronous messages, concurrency, or multi-thread requests.
WildFly remains the best solution as a repository of web applications. These applications become more advanced year after year thanks to a continuous upgrade of the Java enterprise specifications.
This chapter will cover the following points:
Introduction to the new stuff of Java EE included in WildFly 10, showing the major details in the next chapters.
The Java EE specification certified by WildFly 10 is Java EE 7. We will cover the main features of EE 7 and the starting points for the next chapters.
A step by step guide to install the examples.
In WildFly, across configurations, it is very important to be able to develop applications. Many books explain the patterns and strategies of programming, and the user must be able to choose the right developing strategy according the need of the client. Each chapter will get its downloadable examples of web apps and enterprise components, and step by step we will strive to use them.
Good news from EE 7! JSON is included in the specification. HTTP always becomes more default, not only for writing web applications but also for services! REST through JSON confirms the HTML 5 approach and becomes the guideline for not only the frontend but also the service tier.
Undertow is the new substitute for Tomcat, becoming not only a servlet container but the infrastructure that manages all Java EE 7 web technologies as JSON, REST, and WebSockets.
Finally the asynchronous messaging system available through a browser becomes the standard. It's the WebSocket. Each site has its own chat available. For example, banking applications have online support through chat, with an operator ready to help. All this can be used without boring authentications and waits. We will dedicate Chapter 7, Implementing WebSockets to it.
JMS APIs provide an interface to send, receive, and authenticate asynchronous messages through Java. They let you develop a client connecting to a message engine. The message engine used in WildFly is Active MQ Artemis, a substitute for the deprecated JBoss Messaging. The difference between this specification and the older one is simplicity of use and development thanks to the new annotations. These annotations will be covered in detail in Chapter 8, Working with Messaging.
Every new feature and update is done here to get free access to the Cloud. By guaranteeing much simplicity to an interface, the interface becomes a candidate to be used in a Cloud system.
Standard paths or the simplest JNDI names too help to implement this. Infinispan is a distributed cache product and contributes to configuring a cluster better in a Cloud system. Clustering will be analyzed in Chapter 15, Sharing the Web Sessions and Chapter 16, Wildly in Cloud.
A very important contribution in these years is from workflows. With a workflow, you can develop complex systems in very little time.
An air reservation application is a workflow, for example. There are steps such as the choice of a flight, booking, and confirming the flight that can be configured and then executed without developing much code. Java EE 7 gets a new role for the Java enterprise, giving the opportunity to work with XML files to configure steps to add in web applications.
Schedulers too are part of it and they are finally standard. Frontend technologies now include flows with a strategy very similar to the workflows. Schedulers and flows will be discussed in Chapter 12, Batches and Workflows.
JBoss 5 introduced the web profile. A web profile is a configuration including only the technology base representing the Web. Java EE 7 included WebSockets and JSON together with old technologies as servlets, JSF, and CDI. Web profiles are a good mode to simply configure an application server in a Cloud machine.
Java EE always gives an alternative to the developer instead of working with threads. Threads are always denied in Java EE because they are dangerous. They risk compromising the correct execution of a Java enterprise component, especially concurrent components. With these utilities, we can use threads with more simplicity, minus the dangers concerning stability of our applications.
Many new features are provided by interfaces and annotations in our context dependency injection container. New scopes and new Service Provider Interface (SPI) were added to guarantee much stability to our injected objects. Chapter 2, Working with Dependency Injection will analyze the new features provided by Weld.
As for JMS, REST APIs are very flexible and simple to use. Get and post calls become more simple using the annotations. REST is now asynchronous too! RESTEasy is the product candidate to implement these APIs. REST will be seen in detail in Chapter 6, Creating REST Services as synchronous services and in Chapter 10, Asynchronous REST as asynchronous ones.
Java servlet technologies were made for the web developers as an extension to the functionalities of the web server functionality using Java and as access to business systems. There are new good features that we will show, for example the non-blocking I/O, an HTTP protocol upgrade mechanism, and new updates to security. Servlets and how WildFly implements them will explored seen in Chapter 13, Working with Servlets and JSP.
JNDI is the protocol for resolving names in WildFly. This is a standard specification ready since the birth of Java. All enterprise components can be called through JNDI. Here is the syntax to call an EJB:
java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
The java:global JNDI reference is used for the shared name. A name inside this path is accessible by all components inside the same application server.
Other paths include java: app to specify the path for a web or backend application and java: module to specify the path for a module. A module is a simple JAR file that has no lifecycle of its own, so it needs to be used by a third component.
The increase in asynchronous features is very high in Java EE 7. Each component can now be invoked in an asynchronous manner. With it, EJB and servlets add some major power, which will be seen in Part 3 - Asynchronous and real time of this book.
Now we can use our annotations to schedule events and processes. In any part of our component, we can create a timer and configure its time execution, configure the date and time to start it, and implement a set of operations. We will cover these in detail in Chapter 11, Asynchronous EJB.
EJB's are very complex architectures, including different EE technologies such as transactions, persistence, remote interfaces, security, and CORBA. Never in a web application do we need all of the stack that an EJB takes with itself.
To make the business logic less bulky, EJB Lite is introduced and can be used in lighter applications. It excludes the following technologies:
Message-driven beans
2.x remote home components
2.x local home components
3.x remote home components
Timers
RMI-IIOP
We will explore globally these components in detail in Chapter 4, Implementing Business Logic.
In this section, we will look at the mandatory inventory used to start development with WildFly 10.
WildFly is open source. Open source is a vast world of applications and ideas. So an open source operating globally system will get a regard point by us. In this book, we will work with Linux, a very important open source operating system. So we will guide you through bash console samples. Bash is the most used command line tool for managing an operative system, mainly Linux. Of course, any OS can work.
Usually Java EE and Java Standard globally follow the same path. For example Java EE 7 specifications recommend Java standard 7 as the JDK but none denies to use a major version of Java. A JDK version greater than 7 respect the EE never gave problems, even WildFly recommends using the last version of Java 8 and WildFly 10 denies to use Java 7. So we assume in our exercises that Java standard 8 is installed in your machine.
Of course, we will use the latest version of WildFly to work with enterprise components and web applications. WildFly, as an application server, provides a deploy system that you can install inside your application and use. It can be done through a filesystem, adding a package in the deploy directory, or through the console. The deployment system will be seen in detail in Chapter 18, Deployment.
The new version is 10.1.0. It can be downloaded from http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.zip . The installation is very simple. Just extract the downloaded ZIP and put it in your preferred folder.
Before we start the application server, we need to create a default admin user so that we can use the management web console. Through the command line, go to the WildFly root folder under the bin directory and execute this command:
./add-user.sh
After you will get the following output:
What type of user do you wish to add?a) Management User (mgmt-users.properties)b) Application User (application-users.properties)(a): aEnter the details of the new user to add.Using realm 'ManagementRealm' as discovered from the existing property files.Username : adminThe username 'admin' is easy to guessAre you sure you want to add user 'admin' yes/no? yesPassword recommendations are listed below. To modify these restrictions edit the add-user.properties configuration file.- The password should be different from the username- The password should not be one of the following restricted values {root, admin, administrator}- The password should contain at least 8 characters, 1 alphabetic character(s), 1 digit(s), 1 non-alphanumeric symbol(s)Password : adminWFLYDM0098: The password should be different from the usernameAre you sure you want to use the password entered yes/no? yesRe-enter Password : adminWhat groups do you want this user to belong to? (Please enter a comma separated list, or leave blank for none)[ ]:About to add user 'admin' for realm 'ManagementRealm'Is this correct yes/no? yesAdded user 'admin' to file '/Users/lucastancapiano/wildfly-10.1.0.Final/standalone/configuration/mgmt-users.properties'Added user 'admin' to file '/Users/lucastancapiano/wildfly-10.1.0.Final/domain/configuration/mgmt-users.properties'Added user 'admin' with groups to file '/Users/lucastancapiano/wildfly-10.1.0.Final/standalone/configuration/mgmt-groups.properties'Added user 'admin' with groups to file '/Users/lucastancapiano/wildfly-10.1.0.Final/domain/configuration/mgmt-groups.properties'Is this new user going to be used for one AS process to connect to another AS process?e.g. for a slave host controller connecting to the master or for a Remoting connection for server to server EJB calls.yes/no? yesTo represent the user add the following to the server-identities definition <secret value="YWRtaW4=" />
Now you have an admin user with credentials--,user: admin and password: admin
Once you have created the user you can start WildFly with the following command inside the bin directory of the root of WildFly:
./standalone.sh
When you log in, the console will show the row:
INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 20718ms - Started 580 of 816 services (405 services are lazy, passive or on-demand)
This means that the WildFly application server has started.
The web management console can be used by connecting from http://localhost:9990/console.
In the next chapter, we will see how to work with it.
Many tools can be used in Java to build applications. Open source products are Ant, Ivy, Maven, and the more recent Gradle. For convenience, as Maven the most popular in this book we will use it to build our examples.
Apache Maven is a software project management and comprehension tool. Based on the concept of project object model (POM), Maven can manage a project's build, reporting, and documentation from a central piece of information.
We will use Maven to manage our projects. With Maven we will get a simple starting point to build, execute, and test our projects. Maven 3.3.9 is downloadable from https://maven.apache.org/download.cgi.
Since we have installed JDK 8 in our machine, we can extract the downloaded Maven ZIP and put it in any folder that we prefer. After that, we will need a system variable, MAVEN_HOME, for our system. In Linux, you can set MAVEN_HOME by editing the .bash_profile file in your home directory:
vi $USER_HOME/.bash_profile
export MAVEN_HOME=/$your_home_path/apache-maven-3.3.9
export path:$MAVEN_HOME/bin
The second row lets you use Maven in any folder path. So, for example, in /etc, you can run the Maven command mvn. A Maven guide is not given in this book, but for those who don’t know Maven, we will use only three commands:
mvn clean
: Used to clean the project
mvn install
: Used to build, install, and test the project and create the packages to deploy in WildFly
mvn test
: Used only to execute test cases
All the commands can be used together. For example:
The mvn clean install command will execute both the commands, first cleaning the project and then installing it. If you avoid tests it's enough add the property:
mvn clean install -DskipTests
Maven can be used only in the folder for Maven projects. A Maven project is recognized by a file contained in the root of the folder, pom.xml. It is the key descriptor of the Maven projects. For example in this POM file you put the dependency libraries of the projects. When you install a project, it automatically downloads the mandatory dependencies if they are not present and it compiles with them.
This book provides different examples structured by projects divided by part and chapter. Each chapter excluding the introduction has its own project Maven sample. The exercises can be downloaded from the link provided in the Preface of this book.
Once you have downloaded the project, you will notice a tree similar to this:
Wildfly-book Business-components Injection pom.xmlPersistence pom.xml… pom.xml Class-loading … pom.xml … pom.xml
If you are interested only in testing the examples inside the Chapter 3, Persistence, you need only to go in the persistence folder and start the Maven commands seen before.
Three IDEs are recommended.
You can quickly and easily develop desktop, mobile, and web applications with Java, JavaScript, HTML5, PHP, C/C++, and very importantly Java EE 7 support.
NetBeans IDE is free, open source, and has a worldwide community of users and developers.
Each aspect of IntelliJ IDEA is exclusively organized to enhance the productivity of the developer. It provides a complete support for Java EE 7. Moreover, the analysis and the design of the code make development a comfortable experience and very productive.
Eclipse is a moduleable open source IDE written in Java to work in Java and other languages thanks to a good plugin management. It was started by IBM and later donated to the community. It manages all the Java EE components with good graphics tools. In this book, we will use Eclipse, the Neon.2a Release (4.6.2) version. It can be downloaded from https://www.eclipse.org/downloads/.
Now, see how to import the exercises inside Eclipse. Eclipse works with a workspace and working sets. The workspace is a physical directory where we put our projects.
Working sets are logical folders used inside Eclipse as collectors of projects usually organized by argument.
For example, a set of projects that describe a forum can all be put together in a working set and we can call it forum. Another set of projects can be used for an air reservation application, so we can put them in another working set called air-reservation.
The exercises projects, as we mentioned before, are written as a modular tree structure with parents and children. The parent folders are used as collectors of chapters, so they are not important in our system environment. We now create two Eclipse working sets, one for the children (book) and one for the parents (book-parent).
So, when we start Eclipse for the first time, we should set the workspace by choosing the directory we want to use:
Okay, the workspace is ready. Now configure the view with the working sets. Click on the little down arrow near the Project Explorer title and choose Working Sets:
A new window will be opened. In this window, choose the following dialog so we can start to create the working sets:
After that click on the New... button and choose the working set type:
Java is the better type for us. After you have done this, click on the Next > button and create the new book working set:
Repeat the same operations for the second working set: book-parent:
Now select all the created working sets and click on OK to end the configuration of the working sets:
Now we have to import the exercises. Click on File | Import:
We are importing a Maven project so select Maven | Existing Maven Projects:
Click on Next; you should select the root directory for the exercises that you have downloaded. Once you have selected it, you will see a list of all sub- projects. By default the first working set you have created is selected, so choose child projects to add to it and click on Next >:
The same operation must be done with the parent projects. So now select the book-parent working set and click on Next >:
Once done, go to the Select Working Set screen again and click on OK to refresh:
Now we will see a list of working sets:
If we open the working set we can see all ordered parent and child projects:
With this environment, we can debug our components too. It would be very useful to see how our components work inside the WildFly container. To start the debug process, simply enter the sub-project you want to test and enter, for example, the following command:
mvn test -Djboss.options="-Xdebug -Xrunjdwp:transport=dt_socket,address=8001,server=y,suspend=y"
Jboss.options is a property used by the Arquillian container managed subproject to add external properties to the start of WildFly startup process. So you can pass Java properties to set the debug environment.
In our case, we force WildFly to use the following parameters:
debug
: This activates debug mode. If set to
false
, the next parameters will not be considered.
runjdwp
: transport JDWP is the common communication protocol used to start the debug. The transport can be of type
DT_SOCKET
used in Linux or
DT_SHMEM
used in Windows.
Other parameters to add in the transport are:
Address
: The client/server connection URL. It can be valorized as
8001
. Adding only the port we presume the transport running on localhost, the same machine we will start the debug. When WildFly starts, after setting these properties, a JDWP server automatically starts on the specified port:
Server
: It must be set to
y
or else no server can be started:
Suspend
: If set to
y
, WildFly will wait for one connection by a JDWP client; otherwise it will be waiting. If set to
n
, WildFly will start anyway, leaving the connections free to start at another time.
Here is the complete command you need to start the debug:
-Xdebug -Xrunjdwp:transport=dt_socket,address=8001,server=y,suspend=n
Once the test starts, thanks to the suspend property. WildFly will be suspended till we start the JPDA client. This client is ready to work in Eclipse. Here's how to configure and start it.
Click on the row near the debug figure and select Debug Configurations...:
On, the item remote Java debugger right-click and select New:
You will see a new window. Fill in the fields like this:
The field port must be the same as the one used in jboss.options so that the client can connect to the JPDA server that was started in the test. The Project field can be one of the subprojects inside our exercises.
Now close the window. We need to put in a breakpoint, so we show the debugger at work. Simply, take a code class of the project you would like to test and click twice on a row, for example:
Again launch Debug Configurations and start the debugger:
Your breakpoint is now active!
Now we have all of the environment ready to work. In the next chapter, we will see tests and how to start them depending on the argument.
In other samples, you will find that Arquillian uses an annotation called @RunAsClient that lets you start test cases outside the container as remote clients. In that case, you cannot use jboss.options to start the debug because it starts the debug only inside the container.
To debug remote clients annotated with the @RunAsClient annotation, use this script:
mvn test -Dmaven.surefire.debug
And configure your JPDA client with the default port, 5005.
We have finished the configuration of our examples. We now know all the focal points of WildFly that we will explore in subsequent chapters. We are ready to start the examples while working through this book. In the next chapter we will start the first focal point in WildFly 10: injection. Read it well and practice!
Dependency injection is a very important design principle for working simply and at the same time with major security. It lets us write a very simple code to test. Java uses this principle since Java EE 5 through the CDI specifications.
The first Java frameworks to host this technology were the following:
Seam
: Firstly, it was a set of utilities to work better with web applications. Next, it was discontinued and integrated in the Java EE 5 specifications; now it represents the main standard that a developer must use.
Spring
: This was the first Java dependency injection framework born exclusively for complex Java applications. Now it is an evolved set of plugins where you can build anything through dependency injection. It remains an alternative to Java EE.
Contexts and Dependency Injection (CDI) is a set of annotations and services that make it easy for developers, when used together, to work with enterprise technologies in services, web applications and enterprise beans. CDI works fine with stateful objects too and also has many larger uses. It gives developers much flexibility to integrate various types of components in a loosely coupled but type safe way.
Weld 2.3 is the injection engine used by WildFly 10.1. We can consider it as the evolution of JBoss Seam because the idea was initiated by the same authors. All Java EE 7 interfaces and annotations we have seen are fully supported by Weld. It is integrated with other applications servers too, such as JBoss Enterprise Application Platform(EAP), GlassFish, Oracle WebLogic Server, and WebSphere Application Server.
Weld can be started standalone too, thanks to an external module called Weld SE. Of course, you can use it only as a pure injection engine. All the integration with enterprise components doesn't work outside the containers.
Weld has no interfaces and annotations of its own because the CDI specifications 1.2 provide a rather complete set of tools. So, you will never see in your application custom classes with a package name containing the weld name. However, it's the real meat of Weld, a very transparent engine fully compliant with Java EE.
The CDI specifications involved in Java EE 7 will be described in the next paragraphs. Here you can see what we will show:
All the annotations available in CDI and how to use them
All the bean types available in CDI
