The Bean Class for Java Programming

      15 Comments on The Bean Class for Java Programming

In the courses that you take with me I define a bean as a class used to aggregate or collect both primitive data types and other classes for modelling data in a program. Most programs require the definition of multiple elements or values to describe the data that they interact with. Rather than list each element individually, these elements are grouped together into a single class.

The original concept of a bean called a JavaBean dates to 1996. It was intended to be a component model for visual elements of a program. These components could then be easily manipulated by a visual modelling tool. You can read the current specification at http://tinyurl.com/ybzwmldq that was last updated in 1997.

I require you to use a subset of this original concept that I refer to as a bean class in the programs that you write for the courses you are taking with me. Here is the rundown of the rules for a bean in my courses:

Mandatory:

  • All fields, also called instance variables or properties, can only be private.
  • There must be a default constructor.
  • Methods to read or write the instance variable must begin with the prefixes set or get.
  • The bean class should implement the serializable interface

Optional:

  • The bean class should have a toString method.
  • The bean class should have a hashCode and an equals method
  • The bean class should implement the Comparable interface and have a compareTo method.

Bonus:

  • The companion Comparable object for when you need to have more than one possible comparison
  • The Java 8 lambda implementation of of a Comparator
  • The Java 8 functional implementation of a Comparator

For example, consider a problem where it is necessary to model a book. Here is the basic bean.

public class Book implements Serializable{

    private String isbn;
    private String title;
    private String author;
    private String publisher;
    private int pages;

    /**
     * Default constructor
     */
    public Book() {
        this.isbn = "";
        this.title = "";
        this.author = "";
        this.publisher = "";
        this.pages = 0;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(final String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(final String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(final String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(final String publisher) {
        this.publisher = publisher;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(final int pages) {
        this.pages = pages;
    }
}
Basic Bean 1

The methods for reading and writing must adhere to the naming convention. They must begin with set, get or is all in lower case. The is prefix is an alternative to get when the type of value returned is a boolean. They must be followed by a capital letter. They usually correspond to the private fields in the class. You may also add any additional methods that your logic may require.

You now have a class that models a book. Any part of your code now requires only a single reference to an object of type Book to represent all the data points or fields for a book. Reading or writing to any field must now go through a method. The serializable interface allows the state of the object to be preserved by writing it to disk. For distributed applications, such as web services, this allows the object to be transmitted over the internet. Review the documentation on serialization as not every class type can be serialized without additional code. Primitives and Strings can be serialized without additional code.


Special Note 1:

I had a paragraph here that incorrectly stated that a serializable object required a default constructor and set methods but it was pointed out by Michael Simons‏ @rotnroll666 that this is incorrect. I should have reviewed the documentation that I recommended that you review. Serialization does not require a default constructor or set methods.


public class Book implements Serializable{

    private String isbn;
    private String title;
    private String author;
    private String publisher;
    private int pages;

    /**
     * Default constructor
     */
    public Book() {
        this.isbn = "";
        this.title = "";
        this.author = "";
        this.publisher = "";
        this.pages = 0;
    }

    /**
     * Non-default constructor
     *
     * @param isbn
     * @param title
     * @param author
     * @param publisher
     * @param pages
     */
    public Book(final String isbn, final String title, final String author, final String publisher, final int pages) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.publisher = publisher;
        this.pages = pages;
    }
Basic Bean 2

Notice that all the parameters in the methods are final. A final variable cannot have its value changed. If you pass a reference as an argument to any method that does not declare its parameter as final you can change the address that the argument points to and this can result in an unintended side effect. Bean classes must never change an argument.


An argument is a value or reference passed to a method. A parameter is the place holder in the method signature that will represent the argument’s value in the method.


Primitive argument types such as int or double have no connection to the original value from the caller so final is not required. However, it is a best practice to declare it final as you should not be changing it.

toString

We now have a proper bean class. There are four additional methods that can be added that will make the bean more useful in certain circumstances. The first of these circumstances is when you need to represent the bean as a string. The most common reason is to support debugging by allowing you to examine the value of each field in the bean in a log statement. This is the job of the toString method.

    @Override
    public String toString() {
        return "Book{" + "isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", pages=" + pages + '}';
    }
toString

The toString method is inherited from the superclass Object that every class in Java extends. The annotation @Override, while optional, makes it clear that you are overriding a superclass method. What you put into the string is up to you. For example, when placing an object into GUI tree, the toString method is the default for what should appear on screen in the tree and so may return the value of a single field.

hashCode and equals

The next two methods are hashCode and equals. These should always go together whenever your code must test if two objects have identical values in their fields. It may appear that equals is all you need but there is a performance issue here. Our Book class has 4 String fields. When comparing two Book objects it will be necessary to compare every character in every string to determine if they are equal. The hashCode method creates an integer value called a hash code that represents all the values in the object. This value can be compared to the corresponding value in the object we are comparing to. If the value of the hash code is not the same then we know with certainty that they do not possess the same values.

Hash codes are not unique. It is possible that two objects with different values may return the same hash code. Therefore, if hash codes are equal we must call upon the equals method to be certain they are the same. Hash codes are used in Java collections data structures. If you intend to use such a structure, such as a HashMap or a HashSet then you must have hashCode and equals in the bean.

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 61 * hash + Objects.hashCode(this.isbn);
        hash = 61 * hash + Objects.hashCode(this.title);
        hash = 61 * hash + Objects.hashCode(this.author);
        hash = 61 * hash + Objects.hashCode(this.publisher);
        hash = 61 * hash + this.pages;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Book other = (Book) obj;
        if (this.pages != other.pages) {
            return false;
        }
        if (!Objects.equals(this.isbn, other.isbn)) {
            return false;
        }
        if (!Objects.equals(this.title, other.title)) {
            return false;
        }
        if (!Objects.equals(this.author, other.author)) {
            return false;
        }
        if (!Objects.equals(this.publisher, other.publisher)) {
            return false;
        }
        return true;
    }
hashCode and equals

These two methods were generated by the IDE that I use, NetBeans. Most IDEs such as Eclipse and IntelliJ will generate these methods. You may choose to exclude certain fields from these methods but the fields you are using must be the same in hashCode and equals.


Special Note 2:

It has been mentioned in the comments that as presented this hashCode method is problematic when used in  a Hash data structure. The fields in the class are mutable/changeable and this could result in an object placed in the hash structure that can never be found if a field is changed. This is a type of memory leak. The solution is to make all fields used to construct the hash code final/immutable. 



Special Note 3:

This next section has been rewritten from the first version of this article based on comments from Michael Simons‏ @rotnroll666, Originally I proposed multiple Comparable interfaces and multiple compareTo methods in the bean. Michael pointed out that this will result in code bloat as the bean will keep getting longer with each additional compareTo method. He recommended Comparable objects that exist outside the bean.


Comparable Interface and compareTo

You have two choices for how you can order objects when using sort methods or self sorting collections such as a Map. The first choice is to implement a compareTo method in the bean. This method is required when you implement the Comparable interface. This sorted order that results is called the natural ordering and the compareTo method is referred to as the natural ordering method. You must decide which fields will contribute to the sort order criteria. I wish to be able to sort the books by their title.

    /**
     * Natural comparison method for Title
     *
     * @param book
     * @return negative value, 0, or positive value
     */
    @Override
    public int compareTo(Book book) {
        return this.title.compareTo(book.title);
    }
compareTo method

I am taking advantage of the fact that String objects implement the Comparable interface. If my title, this.title, comes before the title in the Book parameter then the difference in the ASCII codes for the first differing characters is returned as a negative value. If the strings are identical then 0 is returned. If my title comes after the title in the Book parameter then the difference in the ASCII code for the first differing characters is returned as a positive value

Comparator

You can have only one compareTo method that overrides the Comparable interface requirement. This leads to the second approach to comparisons. If you need multiple comparisons each with different fields as the criteria then your best solution is to create Comparable objects. This way you can compare any parts of the objects. You just need a Comparable object for each comparison and the original bean does not change.

package com.kenfogel.book;

import java.util.Comparator;

public class BookPageComparator implements Comparator<Book> {

    /**
     * The interface mandated compare method
     *
     * @param book1
     * @param book2
     * @return negative value, 0, or positive value
     */
    @Override
    public int compare(Book book1, Book book2) {
        return book1.getPages() - book2.getPages();
    }
}
Comparator Class

Comparator lambda

The Comparable interface lends itself to the use of lambda expressions that is demonstrated in the test code. This eliminates the need for a Comparable object. However, if the logic to determine the sorting order is more than three lines long you might be better off with a Comparator object instead. Here is what the the two comparison approaches look like when used to sort an array.

Arrays.sort(myBooks); // uses the Comparable compareTo in the bean
Arrays.sort(myBooks, bookPageComparator); // uses the Comparator object
Arrays.sort(myBooks, (s1, s2) -> {
            return s1.getPublisher().compareTo(s2.getPublisher());
        }); // uses a Comparator lambda
Sorting an array

Java 8 Functional Comparator

Java 8 introduced new methods in the Comparator interface that simplifies comparisons with objects. I wish to sort my books based on the ISBN number. As an integer has a natural order, I can inform the sorting method what Comparator to use by the following.

        Arrays.sort(myBooks, comparing(Book::getIsbn)); // Comparable function

See the test program just below to see how Comparable and Comparator work.

The Complete Bean

Here is the final version of the Book bean.

mport java.io.Serializable;
import java.util.Objects;

public class Book implements Serializable, Comparable<Book> {

    private String isbn;
    private String title;
    private String author;
    private String publisher;
    private int pages;

    /**
     * Default constructor
     */
    public Book() {
        this.isbn = "";
        this.title = "";
        this.author = "";
        this.publisher = "";
        this.pages = 0;
    }

    /**
     * Non-default constructor
     *
     * @param isbn
     * @param title
     * @param author
     * @param publisher
     * @param pages
     */
    public Book(final String isbn, final String title, final String author, final String publisher, final int pages) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.publisher = publisher;
        this.pages = pages;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(final String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(final String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(final String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(final String publisher) {
        this.publisher = publisher;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(final int pages) {
        this.pages = pages;
    }

    @Override
    public String toString() {
        return "Book{" + "isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", pages=" + pages + '}';
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 61 * hash + Objects.hashCode(this.isbn);
        hash = 61 * hash + Objects.hashCode(this.title);
        hash = 61 * hash + Objects.hashCode(this.author);
        hash = 61 * hash + Objects.hashCode(this.publisher);
        hash = 61 * hash + this.pages;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Book other = (Book) obj;
        if (this.pages != other.pages) {
            return false;
        }
        if (!Objects.equals(this.isbn, other.isbn)) {
            return false;
        }
        if (!Objects.equals(this.title, other.title)) {
            return false;
        }
        if (!Objects.equals(this.author, other.author)) {
            return false;
        }
        if (!Objects.equals(this.publisher, other.publisher)) {
            return false;
        }
        return true;
    }

    /**
     * Natural comparison method for Title
     *
     * @param book
     * @return negative value, 0, or positive value
     */
    @Override
    public int compareTo(Book book) {
        return this.title.compareTo(book.title);
    }
}
Complete Bean

The Bean Tester

Here is a test program that demonstrates the two ways that comparisons can be made, The comments describe which approach is used.

// Required for Arrays.sort
import java.util.Arrays;
// Required by the Comparator function
import static java.util.Comparator.comparing;

public class BeanTester {

    /**
     * Here is where I am testing my comparisons
     *
     */
    public void perform() {
        // Lets create four books
        Book b0 = new Book("200", "Xenon", "Hamilton", "Harcourt", 99);
        Book b1 = new Book("500", "Boron", "Bradbury", "Prentice", 108);
        Book b2 = new Book("300", "Radon", "Heinlein", "Thompson", 98);
        Book b3 = new Book("404", "Argon", "Campbell", "Hachette", 102);

        // Using Comparable to compare two books
        System.out.println("Value returned by Comparable");
        System.out.println(b0.getTitle() + " compared to " + b1.getTitle() + ": "
                + b0.compareTo(b1));
        System.out.println();

        // Using Comparator to compare two books
        System.out.println("Value returned by Comparator");
        BookPageComparator bookPageComparator = new BookPageComparator();
        System.out.println(b0.getPages() + " compared to " + b1.getPages() + ": "
                + bookPageComparator.compare(b0, b1));
        System.out.println();

        // Create an array we can sort
        Book[] myBooks = new Book[4];
        myBooks[0] = b0;
        myBooks[1] = b1;
        myBooks[2] = b2;
        myBooks[3] = b3;
        System.out.println("Unsorted");
        displayBooks(myBooks);

        System.out.println("Sorted with Comparable Interface on Title");
        Arrays.sort(myBooks); // uses the Comparable compareTo in the bean
        displayBooks(myBooks);

        System.out.println("Sorted with Comparable Object on Pages");
        Arrays.sort(myBooks, bookPageComparator); // uses the Comparator object
        displayBooks(myBooks);

        System.out.println("Sorted with Comparable lambda expression on Publishers");
        Arrays.sort(myBooks, (s1, s2) -> {
            return s1.getPublisher().compareTo(s2.getPublisher());
        }); // uses the Comparator lambda
        displayBooks(myBooks);

        System.out.println("Sorted with Comparable lambda function on ISBN");
        Arrays.sort(myBooks, comparing(Book::getIsbn)); // Comparable function
        displayBooks(myBooks);
    }

    /**
     * Print the contents of each Book object in the array
     *
     * @param theBooks
     */
    private void displayBooks(Book[] theBooks) {
        for (Book b : theBooks) {
            System.out.print(b.getIsbn() + "\t");
            System.out.print(b.getTitle() + "\t");
            System.out.print(b.getAuthor() + "\t");
            System.out.print(b.getPublisher() + "\t");
            System.out.println(b.getPages());
        }
        System.out.println();
    }

    /**
     * Where it all begins
     *
     * @param args
     */
    public static void main(String[] args) {
        BeanTester bt = new BeanTester();
        bt.perform();
        System.exit(0);
    }
}
Bean Tester

The output of this program will be:

Value returned by Comparable
Xenon compared to Boron: 22

Value returned by Comparator
99 compared to 108: -9

Unsorted
200	Xenon	Hamilton	Harcourt	99
500	Boron	Bradbury	Prentice	108
300	Radon	Heinlein	Thompson	98
404	Argon	Campbell	Hachette	102

Sorted with Comparable Interface on Title
404	Argon	Campbell	Hachette	102
500	Boron	Bradbury	Prentice	108
300	Radon	Heinlein	Thompson	98
200	Xenon	Hamilton	Harcourt	99

Sorted with Comparable Object on Pages
300	Radon	Heinlein	Thompson	98
200	Xenon	Hamilton	Harcourt	99
404	Argon	Campbell	Hachette	102
500	Boron	Bradbury	Prentice	108

Sorted with Comparable lambda expression on Publishers
404	Argon	Campbell	Hachette	102
200	Xenon	Hamilton	Harcourt	99
500	Boron	Bradbury	Prentice	108
300	Radon	Heinlein	Thompson	98

Sorted with Comparable lambda functions based on ISBN
200	Xenon	Hamilton	Harcourt	99
300	Radon	Heinlein	Thompson	98
404	Argon	Campbell	Hachette	102
500	Boron	Bradbury	Prentice	108
Output

Bean classes are required when using several libraries in Java such as Context Dependency Injection (CDI) and Bean Validation. You will also use bean classes to represent data from a database when using Java Database Connectivity (JDBC). Beans that back JavaFX controls are coded differently but are 100% backward compatible with simple bean classes. See my next article on JavaFX beans.

Email this to someoneShare on Google+1Share on Facebook7Tweet about this on Twitter0Share on LinkedIn16

Java EE 7 Web Profile Maven pom.xml Using Arquillian, Selenium, MySQL, Primefaces and EclipseLink

  1. Update: Removed unnecessary eclipselink dependency 2017-02-27 14:46
  2. Update: Changed skipTests value to false in Surefire dependency in the complete pom file 2017-02-27 15:18

If you are not using Maven then you should. If you are using Maven then you are likely cutting and pasting snippets of pom.xml file examples and hoping for the best. In this article I will present the pom.xml file that I require my students to use in an e-commerce project course. Not everything in it is required and you likely have libraries you need that are not in my example. After reviewing my pom.xml you should be able to make all the changes you need. You can find the complete file at the end of this article.

This is my third article on the pom.xml file that I have written. The last time I wrote about it was two years ago and while Maven has not changed I have learned more about the pom.xml. If you are not using Maven because a practical explanation of the elements required in the real world are rare, then hopefully this will change your mind.

Whether you work from the command line or with an IDE such as NetBeans (my favourite) one issue comes up over and over again. How do I make sure all the libraries I need get included in my project? It used to be for me that I needed to track down the web site for every library I wanted to use, download the jar and manually paste it into a location on the classpath or a specific folder in IDE. Packaging an application for distribution was also an issue because I needed to ensure that all the right jars were included in the uber archive, jar or war, I planned to distribute.

There is more to Maven than just including libraries. I use it to upload Java programs to my Raspberry Pi and execute them. I use Maven to control when I want unit testing to occur. There is much, much more it can do. The one task that drives my continual writing about Maven is that I use it in the classroom. I teach software development at Dawson College in the final year of the program. I like teaching coding but I am not fond of teaching the necessary plumbing to make systems work. I use NetBeans in my courses because it does not need to be managed the way Eclipse or IntelliJ needs to be. I use Maven for the same reason. I provide my students with a standard Maven pom.xml file that ensures that they all begin from the same baseline. Here is that pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>

 Every XML document should begin with an XML declaration. While the version has remained 1.0, it is the encoding attribute that is important. UTF-8 means that this document is encoded using the Unicode standard in which the first 128 characters map to Unicode. For more information on UTF-8 I recommend http://www.fileformat.info/info/unicode/utf8.htm


 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  This is the root tag for this XML document. An XML document must be well formed and valid. Well formed means that all tags are properly nested and have a matching closing tag. Valid means that the tags and attributes you are using are part of this specific XML language. Testing for validity requires a schema and that is what is referred to in the root project tag. The schema is also used by the IDE to validate while you enter the tags into the file.


     <!-- Maven version of the xml document currently only 4.0.0 is valid -->
    <modelVersion>4.0.0</modelVersion>
 

      As the comment says, its always 4.0.0.


     <!-- The GAV consists of an arbitrary descriptor that is usually in the
    form of a reverse domain name. -->
    <groupId>com.kfwebstandard</groupId>
 
    <!-- This is the name given to the packaged build -->
    <artifactId>KFWebStandardProject</artifactId>

 Maven manages the thousands of libraries available by using the combination of the groupId and artifactId as a unique identifier for each library. This is commonly called the GAV. These are usually expressed using the naming convention for Java packages or as a reverse domain name but they can be anything. You’ll see a non-package name for the MySQL dependency. When a library is a dependency for a project it is identified by this combination. This is also the directory in your local repository where this jar or other file type is stored.


    <!-- The version of the build. Any value is valid though a number and a
    string are common. SNAPSHOT means a project under development. FINAL is commonly
    used to refer to stable production version -->
    <version> 0.0.1-SNAPSHOT</version>

   The version number for a project is an important piece of data that you should be updating during development. Over time there may may be many versions of a project and other developers may depend on a specific version. The most recent version may contain changes that could break the work of other developers who have a dependency on your work. Two special optional terms are SNAPSHOT for a project in development and FINAL for a production ready project.


    <!-- Default value is jar but may be war or ear -->
    <packaging>war</packaging>

 Select the appropriate archive packaging type, either jar, war or ear.


    <!-- The name given to the project. Unlike groupId and artifactId a name
    may have spaces -->
    <name>${project.artifactId}</name>

I like to use the artifactId for the project name but you can use any name you want. Notice that you can refer to a tag in the file using substitution notation and by appending it to the term ‘project’.


    <!-- A description of the program -->
    <description>Standard starting point for a JEE Web Profile application using Java Server Faces
        for students of Ken Fogel</description>

    <!-- Identifies the programmer or programmers who worked on the project -->
    <developers>
        <developer>
            <id>Enter your school id</id>
            <name>Enter your name</name>
            <email>Enter your email address</email>
        </developer>
    </developers>

    <!-- The company or organization that the programmer(s) work for -->
    <organization>
        <name>Enter school name</name>
    </organization>

 The three sections above are used to identify you. They are optional if you are an amateur. If you are a professional they are mandatory. 


    <!-- Global settings for the project. Settings can be accessed in the pom
    by placing the tag name in ${...} ex. ${endorsed.dir} -->
    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

 Properties represent data that another section of the pom may need access to. This way this data can be stored in one place and not repeated where it is needed. Endorsed represents a directory where files with the same name and type as those present in the Java installation are stored. This way the file in the endorsed folder will be used rather than the one supplied in the Java installation. The encoding of the project appears here as does the version of Java you will be using.


    <!-- Dependencies listed here are usually bom or bill of materials-->
    <!-- The bom lists all the child dependencies that could be used and -->
    <!-- lists the current version number for each -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>1.1.12.Final</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <dependency>
                <groupId>org.jboss.shrinkwrap.resolver</groupId>
                <artifactId>shrinkwrap-resolver-bom</artifactId>
                <version>2.2.6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

 When using Arquillian there are numerous libraries that may be required. Exactly what they are may change from version to version. A dependencyManagement section refers to special files classifid as bill of materials that in turn will include the necessary Arquillian libraries. 


    <!-- Dependencies are libraries that either must be included in the -->
    <!-- jar/war file or are expected to be found in the container such as -->
    <!-- GlassFish -->

 As my comment above says, the dependencies are libraries that must be available to your project. They will all be downloaded to your local repository. This will allow your IDE to ensure you are using classes and methods from these libraries correctly. They are further classified by the scope tag. If there is no scope tag then the file associated with the dependency will be added to your final archive file. If the scope tag shows ‘provided’ then the required files are in the container you will be running in, such as Glassfish/Payara, and do not need to be added to your archive. If the scope is ‘test’ then the files are only added to an archive used for testing such as what Arquillian produces.


    <dependencies>
        <!-- These dependencies are required to run the project on the server -->
        <!-- Java EE 7.0 Web profile dependency -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- MySQL dependency -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
            <scope>provided</scope>
        </dependency>

        <!-- PrimeFaces dependency -->
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>6.0</version>
        </dependency>

        <!-- EclipseLink dependency for the static metamodel generator -->
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.6.4</version>
            <scope>provided</scope>
        </dependency>

 The metamodel generator dependency invokes a process to create meta model classes dynamically. This will allow you to use identifiers rather than strings in certain types of JPA queries so that refactoring (renaming) is supported.

Thanks to BillyTheKid for pointing out that the dependency for eclipselink, now removed, is not needed, only the metamodel dependency is required.


        <!-- These dependencies are required for testing only -->
        <!-- Arquillian dependency for running tests on a remote GlassFish server -->
        <dependency>
            <groupId>org.jboss.arquillian.container</groupId>
            <artifactId>arquillian-glassfish-remote-3.1</artifactId>
            <version>1.0.0.Final</version>
            <scope>test</scope>
        </dependency>

        <!-- Resolves dependencies from the pom.xml when explicitly referred to
        in the Arquillian deploy method -->
        <dependency>
            <groupId>org.jboss.shrinkwrap.resolver</groupId>
            <artifactId>shrinkwrap-resolver-depchain</artifactId>
            <type>pom</type>
            <scope>test</scope>
        </dependency>

 Not every required Arquillian dependency that my students need is in one of the two bom dependencyManagement entries so we need to add these two dependencies. If you are using Arquillian then you need these too.


        <!-- Connects Arquillian to JUnit -->
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>
 
        <!-- JUnit dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- Selenium dependencies -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>htmlunit-driver</artifactId>
            <version>2.25</version>
            <scope>test</scope>
        </dependency>

        <!-- You will need a driver dependency for every browser you use in
        testing. You can find the meven dependencies at
        https://mvnrepository.com/artifact/org.seleniumhq.selenium -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>3.2.0</version>
            <scope>test</scope>
        </dependency>

        <!-- Normally you must download an exe for each browser. This library
        will retrieve the the necessary file and place it in the classpath for
        selenium to use -->
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>1.6.0</version>
            <scope>test</scope>
        </dependency>

 For the first time I will be having my students use Selenium as part of their testing. Selenium is actually an independent system that can even be placed in a Java desktop application. Here it will be run as a unit test. Selenium requires, in addition to the Java library, a standalone executable program to connect it to a specific browser. I found this extremely convenient library, webdrivermanager, that will download all the required executables and run them as required.


        <!-- A better way to write assertions -->
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>1.7.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Selenium uses SLF4J and log4j so these dependencies are needed
        but just for test scope -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.23</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

 Selenium uses slf4j as the interface to log4j. That is why these dependencies are all listed as test scope. A student recently ran into a problem when a library they were using in their project also needed slf4j. The solution was to remove scope so that the libraries were added to both the production and test archive files. 


    </!-- Information for compiling, testing and packaging are define here -->
    <build>
        <testResources>
            <!-- Folders in the project required during testing -->
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
            <testResource>
                <directory>src/test/resources-glassfish-remote</directory>
            </testResource>
        </testResources>

 Here in the build section of the pom.xml. Here you can identify filesor folders folders that are required but are not part of a standard Maven project. 


        <!-- Plugins are components that Maven uses for specific purposes beyond
        the basic tasks -->
        <plugins>
            <!-- Presence of this plugin suppress a warning about the existence 
            of the web.xml file -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

Plugins are modules that add features to Maven. The Maven war plugin is used when we wish to modify how the war file is built. It is not required for the projects my students build. Unfortunately, leaving this plugin out results in a warning that reads “Warning: selected war files include a WEB-INF/web.xml which will be ignored”. This statement is false and the project’s web.xml is properly processed. Adding this plugin without any settings eliminates the warning message. 


            <plugin>
                <!-- Executes JUnit tests and writes the results as an xml and
                txt file Test classes must include one of the following in their
                name: Test* *Test *TestCase -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <argLine>-Dfile.encoding=${project.build.sourceEncoding}</argLine>
                    <skipTests>false</skipTests>
                </configuration>
            </plugin>
        </pluginn>
    </build>
</project>

The Surefire pligin controls running tests and it allows me to easily turn on or off testing with the skipTests tag.

Final Word

In preparing this article I removed two plugins that proved to be redundant and removed unnecessary tags from a third. These plugins were there because the articles that I read in researching Maven showed them. These Maven entries continue to appear on StackOverflow and in other articles. May I suggest that when writing about Maven or answering a question you consider testing your code by removing plugins. Otherwise we will propagate inflated Maven pom.xml files.

Here is the full pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- pom.xml February 2017 version 1.0 -->

    <!-- Maven version of the xml document currently only 4.0.0 is valid -->
    <modelVersion>4.0.0</modelVersion>

    <!-- The GAV consists of an arbitrary descriptor that is usually in the
    form of a reverse domain name. -->
    <groupId>com.kfwebstandard</groupId>

    <!-- This is the name given to the packaged build -->
    <artifactId>KFWebStandardProject</artifactId>

    <!-- The version of the build. Any value is valid though a number and a
    string are common. SNAPSHOT means a project under development. FINAL is commonly
    used to refer to stable production version -->
    <version>0.1</version>

    <!-- Default value is jar but may be war or ear -->
    <packaging>war</packaging>

    <!-- The name given to the project. Unlike groupId and artifactId a name
    may have spaces -->
    <name>${project.artifactId}</name>

    <!-- A description of the program -->
    <description>Standard starting point for a JEE Web Profile application using Java Server Faces
        for students of Ken Fogel</description>

    <!-- Identifies the programmer or programmers who worked on the project -->
    <developers>
        <developer>
            <id>Enter your school id</id>
            <name>Enter your name</name>
            <email>Enter your email address</email>
        </developer>
    </developers>

    <!-- The company or organization that the programmer(s) work for -->
    <organization>
        <name>Enter school name</name>
    </organization>

    <!-- Global settings for the project. Settings can be accessed in the pom
    by placing the tag name in ${...} ex. ${endorsed.dir} -->
    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <!-- Dependencies listed here are usually bom or bill of materials-->
    <!-- The bom lists all the child dependencies that could be used and -->
    <!-- lists the current version number for each -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>1.1.12.Final</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <dependency>
                <groupId>org.jboss.shrinkwrap.resolver</groupId>
                <artifactId>shrinkwrap-resolver-bom</artifactId>
                <version>2.2.6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- Dependencies are libraries that either must be included in the -->
    <!-- jar/war file or are expected to be found in the container such as -->
    <!-- GlassFish -->
    <dependencies>
        <!-- These dependencies are required to run the project on the server -->

        <!-- Java EE 7.0 Web profile dependency -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- MySQL dependency -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
            <scope>provided</scope>
        </dependency>

        <!-- PrimeFaces dependency -->
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>6.0</version>
        </dependency>

        <!-- EclipseLink dependency for the static metamodel generator -->
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.6.4</version>
            <scope>provided</scope>
        </dependency>

        <!-- These dependencies are required for testing only -->

        <!-- Arquillian dependency for running tests on a remote GlassFish server -->
        <dependency>
            <groupId>org.jboss.arquillian.container</groupId>
            <artifactId>arquillian-glassfish-remote-3.1</artifactId>
            <version>1.0.0.Final</version>
            <scope>test</scope>
        </dependency>

        <!-- Resolves dependencies from the pom.xml when explicitly referred to
        in the Arquillian deploy method -->
        <dependency>
            <groupId>org.jboss.shrinkwrap.resolver</groupId>
            <artifactId>shrinkwrap-resolver-depchain</artifactId>
            <type>pom</type>
            <scope>test</scope>
        </dependency>

        <!-- Connects Arquillian to JUnit -->
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- JUnit dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- Selenium dependencies -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>htmlunit-driver</artifactId>
            <version>2.25</version>
            <scope>test</scope>
        </dependency>

        <!-- You will need a driver dependency for every browser you use in
        testing. You can find the meven dependencies at
        https://mvnrepository.com/artifact/org.seleniumhq.selenium -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>3.2.0</version>
            <scope>test</scope>
        </dependency>

        <!-- Normally you must download an exe for each browser. This library
        will retrieve the the necessary file and place it in the classpath for
        selenium to use -->
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>1.6.0</version>
            <scope>test</scope>
        </dependency>

        <!-- A better way to write assertions -->
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>1.7.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Selenium uses SLF4J and log4j so these dependencies are needed
        but just for test scope -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.23</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <!-- Information for compiling, testing and packaging are define here -->
    <build>
        <!-- Folders in the project required during testing -->
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
            <testResource>
                <directory>src/test/resources-glassfish-remote</directory>
            </testResource>
        </testResources>

        <!-- Plugins are components that Maven uses for specific purposes beyond
        the basic tasks -->
        <plugins>
            <!-- Presence of this plugin suppress a warning about the existence
            of the web.xml file -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

            <plugin>
                <!-- Executes JUnit tests and writes the results as an xml and
                txt file Test classes must include one of the following in their
                name: Test* *Test *TestCase -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <argLine>-Dfile.encoding=${project.build.sourceEncoding}</argLine>
                    <skipTests>false</skipTests>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>

 

 

Email this to someoneShare on Google+1Share on Facebook77Tweet about this on Twitter0Share on LinkedIn4