Enterprise Application Development with Ext JS and Spring - Gerald Gierer - E-Book

Enterprise Application Development with Ext JS and Spring E-Book

Gerald Gierer

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Spring and Ext JS are cutting edge frameworks that allow us to build high performance web applications for modern devices, that are now consuming data at a faster rate than ever before. It is the appropriate time for you to understand how to best leverage these technologies when architecting, designing, and developing large scale web development projects.

This practical guide condenses an approach to web development that was gained from real world projects, and outlines a simple, practical approach to developing high performance, and enterprise grade web applications.

Starting with configuring Java, NetBeans, and MySQL to prepare your development environment, you will then learn how to connect your NetBeans IDE to the MySQL database server. We will then explore the Task Time Tracker (3T) project database structure and populate these tables with test data.

Following on from this, we will examine core JPA concepts after reverse engineering the domain layer with NetBeans. Leveraging the Data Access Object design pattern, you will learn how to build the Java DAO implementation layer assisted by generics in base classes, followed by a Data Transfer Object enabled service layer to encapsulate the business logic of your 3T application.

The final chapters that focus on Java explore how to implement the request handling layer using Spring annotated controllers, and deploy the 3T application to the GlassFish server. We will then configure the Ext JS 4 development environment and introduce key Ext JS 4 concepts, including MVC and practical design conventions.

Covering a variety of important Ext JS 4 strategies and concepts, you will be fully-equipped to implement a variety of different user interfaces using the Ext JS MVC design pattern. Your journey ends by exploring the production build and deployment process using Maven, Sencha Cmd and GlassFish.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 378

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Enterprise Application Development with Ext JS and Spring

Enterprise Application Development with Ext JS and Spring

Copyright © 2013 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: December 2013

Production Reference: 1131213

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78328-545-7

www.packtpub.com

Cover Image by Kerry Thomson (<[email protected]>)

Credits

Author

Gerald Gierer

Reviewers

Eric Mansfield

Justin Rodenbostel

Ernst Schmidt

Alexandre Arcanjo de Queiroz

Acquisition Editor

Joanne Fitzpatrick

Lead Technical Editor

Susmita Panda

Copy Editors

Alisha Aranha

Roshni Banerjee

Sarang Chari

Janbal Dharmaraj

Tanvi Gaitonde

Mradula Hegde

Dipti Kapadia

Gladson Monteiro

Deepa Nambiar

Karuna Narayanan

Kirti Pai

Laxmi Subramanian

Technical Editors

Ritika Singh

Pratish Soman

Harshad Vairat

Project Coordinator

Anugya Khurana

Proofreader

Jonathan Todd

Indexer

Priya Subramani

Graphics

Yuvraj Mannari

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Gerald Gierer has been involved in enterprise web application projects for more than 15 years and continues to find his work challenging and rewarding. He started his software development career working with C, PowerBuilder, and Unix, until the rise of the Internet and Java caught his attention. In 2000, he made a conscious decision to focus on Internet application development using the Java language.

The frustration of working with the first Enterprise JavaBeans (EJB) implementations was the predominant reason he investigated the alternatives that could make enterprise development more productive. In 2004, he first heard of the Spring framework and quickly realized how comprehensive and well-designed an alternative this was to EJB. Since then he has architected and developed many Spring projects using a range of view technologies including JSP, JSF, Struts, Tiles, Freemarker, DWR, and YUI.

In 2009, he became aware of Ext JS and was immediately struck by the power of this JavaScript framework. Having spent countless hours building complex web pages from scratch, Ext JS was a breath of fresh air for the client realm. He has been working with Ext JS ever since.

He lives in Geelong, Australia, but often spends time in Europe, having lived and worked for five years in Munich. In his spare time, he enjoys keeping fit, brewing beer, being outdoors, and rock climbing—a passion that has kept him sane for more than 25 years.

Acknowledgments

Most of all I would like to thank my loving wife Katja for her boundless love and support for everything I do. Without her understanding, patience, and positive encouragement this book would simply not have been possible. Thank you meine Suesse!

To my loving parents, who have given me the gift of seeing the world with a positive outlook that can make such a difference when the going gets tough; you are, and continue to be, an inspiration.

To my friend Gabriel Bezas, thank you for showing me the path so many years ago. Your friendship and advice has been invaluable.

To my colleagues over the years I would like to thank (in no particular order) Alfred Merk, Steve Terry, Hans Hochreiter, Karin Langner, Steffen Haigis, Arthur Marschall, Ralf Haeussler, Zoltan Levardy, and Ernst Schmidt. Each of you has contributed to the evolution of this book.

Finally, thanks to the team at Gieman IT Solutions; Adam, Ben, Di (3T logos and design), Jane (book illustrations), Tracy, and Reece. You gave me a reason to write this book.

About the Reviewers

Eric Mansfield has 20 years of development experience at some of the world's largest media and entertainment conglomerates—including Sony Music, Universal, Scripps, Sony Pictures, and MTV—that brings a detailed, practical approach to building high-quality applications. He has been an early adopter of the Spring framework and has a passion for clean, user-friendly design and doing things right the first time. He lives in Austin, Texas with his wife and enjoys golfing and playing the piano.

Justin Rodenbostel is a senior software architect with Redpoint Technologies, based in Chicago, Illinois. He has more than 12 years' experience in full-stack application development using a variety of technologies, including Spring, Grails, Rails, .NET, and various JavaScript frameworks. On the Web, he can be found blogging at http://justinrodenbostel.com. Apart from his work, he stays busy as a husband and father of three, and when he's lucky, can be found brewing beer in his garage.

Ernst Schmidt is a designer and frontend engineer with a focus on rich web applications. He has worked with Sencha frameworks from the very beginning and has an in-depth understanding of Ext JS internals and architecture.

Recently, he is working with Sony Music and Universal Music Group leading the design and implementation of user interface frameworks for digital supply chain applications.

He lives in the Bay Area with his wife and two sons.

Alexandre Arcanjo de Queiroz, a Brazilian software developer, graduated from the Faculty of Technology of São Paulo, a renowned institution of his country. He has experience in developing backend and frontend applications using the Java EE platform in the Unix environment. He is also a GNU/Linux user.

Currently, he is working in Indra Company, a Spanish multinational company present in more than 128 countries, developing applications for the telecommunications segment.

I would like to thank my family who supports me at every moment of my life and my friends who believe in my potential.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

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.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Enterprise application development is an art form rarely acknowledged in this fast-paced technical world. This book describes the patterns and strategies that will simplify large-scale development projects using two of the most popular technologies available: the Spring Framework and Sencha Ext JS. Each chapter defines and builds a concise layer in the enterprise application stack, condensing an approach to web development that was gained from many years of developing real-world projects. We cover quite an extensive conceptual ground, so be prepared for an interesting journey!

This book is not an introduction to Java, JavaScript, or any web development concepts. There are significant amounts of practical code in both Java and JavaScript languages, so an understanding of these technologies is required. If you are not familiar with Java and associated concepts such as object-oriented programming, you may be challenged when following the examples and explanations. The same can be said for Ext JS development; you need to have some experience with the fundamental concepts, including the framework APIs, to follow most examples.

You do not need to be an expert, but beginners may wish to start their journey elsewhere.

Regardless of your experience and background, the practical examples provided in this book are written in a way to thoroughly cover each concept before moving on to the next chapter.

What the book covers

Chapter 1, Preparing Your Development Environment, discusses the installation and configuration for the development environment, including the Java Development Kit, NetBeans, and MySQL. We will also introduce Maven, create a new NetBeans project, and deploy the project to the GlassFish 4 application server.

Chapter 2, The Task Time Tracker Database, defines the Task Time Tracker (3T) database design and helps configure NetBeans as a client of the MySQL server. We create and populate all the tables and identify the possible enhancements that could be appropriate for enterprise use.

Chapter 3, Reverse Engineering the Domain Layer with JPA, helps us reverse engineer the 3T database using the NetBeans IDE to create a domain layer of JPA entities. These entities are explored and refactored as we examine and define core JPA concepts.

Chapter 4, Data Access Made Easy, introduces the Data Access Object (DAO) design pattern and helps implement a robust data access layer using the domain classes we defined in the previous chapter. Java generics and interfaces, the Simple Logging Facade for Java (SLF4J), the JPA EntityManager, and transactional semantics are also introduced.

Chapter 5, Testing the DAO Layer with Spring and JUnit, introduces the configuration of a JUnit testing environment and the development of test cases for several of our DAO implementations. We introduce the Spring Inversion of Control (IoC) container and explore the Spring configuration to integrate Spring-managed JUnit testing with Maven.

Chapter 6, Back to Business – The Service Layer, examines the role of the service layer in enterprise application development. Our 3T business logic is then implemented by the Data Transfer Objects (DTO) design pattern using Value Objects (VO). We also examine writing test cases prior to coding the implementation—a core principle of test-driven development and extreme programming.

Chapter 7, The Web Request Handling Layer, defines a request handling layer for web clients that generates JSON data using the Java API for JSON processing, which is a new API introduced in Java EE 7. We implement the lightweight Spring controllers, introduce Spring handler interceptors, and configure Spring MVC using Java classes.

Chapter 8, Running 3T on GlassFish, completes our Spring configuration and allows us to deploy the 3T application to the GlassFish 4 server. We also configure the GlassFish 4 server to run independently of the NetBeans IDE, as would be the case in enterprise environments.

Chapter 9, Getting Started with Ext JS 4, introduces the powerful Ext JS 4 framework and discusses the core Ext JS 4 MVC concepts and practical design conventions. We install and configure our Ext JS development environment using Sencha Cmd and the Ext JS 4 SDK to generate our 3T application skeleton.

Chapter 10, Logging On and Maintaining Users, helps us develop the Ext JS 4 components that are required for logging on to the 3T application and maintaining users. We will discuss the Ext JS 4 model persistence, build a variety of views, examine application concepts, and develop two Ext JS controllers.

Chapter 11, Building the Task Log User Interface, continues to enhance our understanding of the Ext JS 4 components as we implement the task log user interface.

Chapter 12, 3T Administration Made Easy, enables us to develop the 3T Administration interface and introduces the Ext JS 4 tree component. We examine dynamic tree loading and implement drag-and-drop tree actions.

Chapter 13, Moving Your Application to Production, will help us prepare, build, and deploy our 3T project to the GlassFish server. We introduce Ext JS theming, integrate Sencha Cmd compiling with Maven to automate the Ext JS 4 app-all.js file generation process, and learn how to deploy our production build on the GlassFish server.

Appendix, Introducing Spring Data JPA, provides a very brief introduction to Spring Data JPA as an alternative to the implementation discussed in Chapter 4, Data Access Made Easy.

What you need for this book

The examples in this book can be run on any Windows, Mac, or Linux platform that supports the following software:

Java Development Kit (JDK) 1.7NetBeans 7.4+MySQL 5+Sencha Cmd

All of the software are available for free download at the websites listed in the appropriate chapters.

Who this book is for

This book is particularly relevant to those working in large-scale web application development projects, including application architects, Java developers, and Ext JS developers.

Application architects

Architects understand the big picture from a technical perspective and are responsible for laying out a blueprint for development standards. This book will introduce you to the power of the Spring Framework and Sencha Ext JS and how you can best leverage these technologies when designing your next project.

Java developers

Regardless of your level of understanding, you will learn how the Spring Framework encourages good programming practices. This includes a clean, layered structure that is easy to enhance and maintain. Those new to Spring will be surprised at how little effort is required to achieve significant results. For both new and experienced Spring developers, the focus will be best practices for enterprise web development to allow seamless integration with Sencha Ext JS clients. If you have never worked with Sencha Ext JS, you will be surprised at how quickly powerful UIs can bring backend data to life.

Ext JS developers

Sencha Ext JS is a powerful framework that is used to build enterprise applications that are cross-browser compliant. This book will solve real-world problems right from analysis to providing fully functional solutions. You will see the many stages of development that are usually hidden from Ext JS developers; you will also get introduced to the steps required to produce JSON data for client consumption. The chapters focusing on the Ext JS components will introduce simple strategies for maintainable development based on the latest MVC design patterns.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, folder names, filenames, file extensions, pathnames, dummy URLs, and user input are shown as follows: "The ManageTaskLogs definition is as follows:"

A block of code is set as follows:

Ext.define('TTT.store.Task', { extend: 'Ext.data.Store', requires: ['TTT.model.Task'], model: 'TTT.model.Task', proxy: { type: 'ajax', url:'task/findAll.json', reader: { type: 'json', root: 'data' } } });

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

controllers: [ 'MainController', 'UserController', 'TaskLogController' ], models: [ 'User', 'Project', 'Task', 'TaskLog' ], stores: [ 'User', 'Project', 'Task', 'TaskLog' ]

Any command-line input or output is written as follows:

sencha –sdk ext compile -classpath=app page -yui -in index.html -out build/index.html

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Adding a new task log will preserve the currently selected Date and Project, if present:".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via 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 on www.packtpub.com/authors.

Customer support

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.

Downloading the example code

You can download the example code files for all Packt books you have purchased 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.

Errata

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 would 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 erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Preparing Your Development Environment

This chapter will install and configure your development environment. The Rapid Application Development (RAD) tool is NetBeans, an open source, cross-platform Integrated Development Environment (IDE) that can be used for creating visual desktop, mobile, web, and Service-Oriented Architecture (SOA) applications. NetBeans officially supports Java, PHP, JavaScript, and C/C++ programming languages, but it is best known for providing a complete toolset for all the latest Java Enterprise Edition (Java EE) standards (currently Java EE 7).

The database of choice for this book is MySQL, the world's most widely used open source Relational Database Management System (RDBMS). MySQL is the most popular choice of database for web applications hosted on Linux platforms and continues to deliver outstanding performance in a multitude of applications. Its small footprint and ease of use makes it perfect for development use on a single computer.

The application server used in this book is GlassFish 4, which comes bundled with the NetBeans download. GlassFish is installed as part of the NetBeans installation, and the tight integration between the two makes configuring GlassFish a simple process. GlassFish is an open source, production-quality application server that implements all the Java EE 7 features. It has enterprise-grade reliability and is considered by many to be the best open source application server available. GlassFish 4 is the Reference Implementation (RI) for the Java EE 7 specification, a full description of which can be found at https://glassfish.java.net/downloads/ri/.

All of these development tools are freely available for PC, Mac, and Linux. Each tool has extensive examples, comprehensive tutorials, and online support forums available.

It should be noted that although this chapter focuses on NetBeans, MySQL, and GlassFish, it is possible for you to configure any appropriate combination of tools that they are familiar with. The development tasks outlined in this book can just as easily be followed using Eclipse, Oracle, and JBoss—although some described configuration details may require minor modifications.

In this chapter, we will perform the following tasks:

Install the MySQL Database serverInstall the Java SDKInstall and configure the NetBeans IDECreate the application project and explore MavenRun the project in GlassFish

Installing MySQL

MySQL can be downloaded from http://www.mysql.com/downloads/mysql. Select the appropriate MySQL Community server for your operating system and architecture. It is important to follow the instructions, making note of installation directories and paths for future reference. After downloading and running the setup file, you should select the Developer Default installation for this book.

Choosing the default settings is best unless you are familiar with MySQL. This will include setting the default port to 3306, enabling TCP/IP networking, and opening the required firewall port for network access (not strictly required for a developer machine where all apps are running on the same environment, but required if you are configuring a dedicated MySQL server).

Regardless of the environment, it is important to set a root user password during the installation process. We will use the root user to connect to the running MySQL server to execute commands.

Note

The rest of this book will assume the root user has the password adminadmin. This is not a very secure password but should be easy to remember!

We recommend that the MySQL server is configured to start when the operating system starts. How this is done will depend on your environment, but it is usually performed at the end of the Initial Configuration action. Windows users will have the option to start the MySQL server at system startup. Mac users will need to install the MySQL Startup Item after the server has been installed.

Should you decide not to start MySQL when the operating system starts, you will need to start the MySQL server manually whenever required. How this is done will once again depend on your environment, but you should start your server now to confirm that the installation was successful.

Note

Unix and Linux users will need to install MySQL as appropriate for their operating system. This may include the use of Advanced Packaging Tool (APT) or Yet another Setup Tool (YaST), or even the installation of MySQL from source. There are detailed instructions for various operating systems found at http://dev.mysql.com/doc/refman/5.7/en/installing.html.

At the end of the configuration process, you will have a running MySQL server ready to be used in Chapter 2, The Task Time Tracker Database.

Installing the Java SE Development Kit (JDK)

The Java SE Development Kit (JDK) can be downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index.html. You may choose to skip this step if you already have the JDK 7 Update 45 (or later) installed on your system.

Note

Do not select the NetBeans bundle as it does not contain the GlassFish server.

You will need to accept the JDK 7 License Agreement before selecting the appropriate distribution. After downloading the JDK, run the setup program and follow the instructions and prompts.

Installing the NetBeans IDE

NetBeans can be downloaded from https://netbeans.org/downloads/. The distribution requires a valid JDK to be already installed on your platform. At the time of this writing, I used JDK 7 Update 45, but any JDK 7 (or higher) version would be fine. There are several distribution bundles; you will need to select the Java EE bundle.

The latest version at the time of this writing was NetBeans 7.4, which introduced significant new features, including extended HTML5 and JavaScript support. For the first time, NetBeans also included editing and code completion support for the Ext JS framework.

To install the software, simply download and follow the detailed instructions available from the NetBeans website. This will take you through a sequence of setup screens as follows:

The GlassFish 4 server is automatically selected. You do not need to install Tomcat.Accept the terms in the license agreement.Accept the terms of the JUnit license agreement. JUnit is used for testing in Chapter 5, Testing the DAO Layer with Spring and JUnit.Note the installation path of the NetBeans IDE for future reference. Select the appropriate JDK that was installed previously (if there is more than one JDK on your system).Note the installation path for the GlassFish 4 server for future reference.The final screen summarizes the installation. Ensure to Check for Updates before clicking on Install to start the process.

The process may take several minutes depending on your platform and hardware.

When the installation is complete, you can run NetBeans for the first time. If you had a previous version of NetBeans installed, you may be prompted to Import Settings. The default opening screen will then be displayed as follows:

The most useful panels can now be opened from the menu:

Projects: This panel is the main entry point to your project sources. It shows a logical view of important project content, grouped into appropriate contexts.Files: This panel shows the actual file structure of the project node as it exists on your filesystem.Services: This panel displays your runtime resources. It shows a logical view of important runtime resources such as the servers and databases that are registered with the IDE.

At this stage, the first two panels will be empty but the Services panel will have several entries. Opening the Servers panel will display the installed GlassFish 4 Server as seen in the following screenshot:

Introducing Maven

Apache Maven is a tool that is used for building and managing Java-based projects. It is an open source project hosted at http://maven.apache.org and comes bundled with the NetBeans IDE. Maven simplifies many steps common to all Java development projects and provides numerous features, including the following:

The provision of convention over configuration. Maven comes with a series of predefined targets for performing certain well-defined tasks including compilation, testing, and packaging of projects. All tasks are managed through a single configuration file: pom.xml.A consistent coding structure and project framework. Each Maven project has the same directory structure and location for source files, test files, build files, and project resources. This common structure brings us easily up to speed with projects.A consistent build system with numerous plugins to make common tasks easy.The ability to execute tests as part of the build process.A highly flexible and powerful dependency management system. This allows software developers to publish information and share Java libraries through (external or remote) Maven repositories hosted on the Internet. Libraries are then downloaded and cached locally by Maven for use in the project.

We encourage you to visit the Maven website to explore the many features available. NetBeans will use Maven to create and manage the web application project.

Creating the Maven Web Application project

A NetBeans project encapsulates all the source code and related components required to maintain and develop an application. Navigate to File | New Project from the menu to start the process:

Select Maven in the Categories listing and Web Application from the Projects listing, as shown in the preceding screenshot, before selecting the Next button. This will present you with the project configuration screen with the following fields:

Project Name: This specifies the display name of the project in the project window. This name is also used to create the project folder and must not contain spaces.

Note

Our project is called Task Time Tracker. This tool will allow users to manage the time spent on different tasks for different projects. The project name field is the lowercase, nonspaced translation of the name of the project: task-time-tracker.

Project Location: This specifies the filesystem root folder where you want to store the project metadata and source code. We normally create a project-specific folder at the root level of a drive, rather than burying it deep within a folder structure under NetBeans. This makes it easier to find and copy files into the project.

Note

Windows users should create a project folder under c:\projects. Mac users may wish to replace this with /Users/{username}/projects and Unix users with /home/{username}/projects. The rest of the book will refer to this location in all examples as the project folder.

Project Folder: The project folder is read-only and generated based on the name of the project and the project location.Artifact Id: This is a read-only Maven-specific property to identify the project and is based on the project name.Group Id: This is another Maven property that represents a top-level container for multiple artifacts. It usually represents the Top-Level Domain (TLD) of the organization owning the project.

Note

The Group Id for the project is com.gieman, the company of the author.

Version: This is another Maven property that represents the version of the artifact. The default version is 1.0-SNAPSHOT, which we will change to 1.0. As projects evolve and new versions are released, Maven will keep track of the different builds based on their versions.Package: The IDE will automatically create a Java source package structure based on this field. We will use the package com.gieman.tttracker.

You should now have entered the following project details:

Click on the Next button to view the final screen. Do not change the default GlassFish Server 4.0 and Java EE 7 settings before clicking on the Finish button. You will now see activity in the Project Creation output tab as the project is created and configured. Opening the Project and Files panels will allow you to see the project structure:

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased 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.

Right-clicking on the project name in either tab will allow you to select the Properties for the project. This will display all properties and paths relevant to the project under different categories:

You should not need to change these properties for the remainder of the book.

Understanding the POM and dependency management

Each Maven project has a pom.xml configuration file at the root level of the NetBeans project. Click on the Files view and double-click on the pom.xml file to open it in the editor:

Note

You should see the Navigator window open in the bottom-left panel. This displays an outline of the file being edited and is very helpful when navigating through large files. Double-clicking on a node in the Navigator will position the cursor at the appropriate line in the editor.

If the Navigator window does not open (or has been closed), you can open it manually by navigating to Window | Navigating | Navigator from the menu.

The Project Object Model (POM) fully defines the project and all required Maven properties and build behaviors. There is only one dependency shown in pom.xml:

<dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> </dependencies>

This dependency identifies that the project requires Java EE 7 for building. This entry ensures the full Java EE 7 APIs are available for Java coding in the Task Time Tracker project. Our project also requires the Spring Framework, which must now be added as additional dependencies. Typing in the editor will result in autocompletion help to determine the correct dependencies. After adding the Spring Framework groupId and artifactId entries, as shown in the following screenshot, the Ctrl + Space bar keyboard shortcut will open the available matching entries for the artifactId starting with the text spring:

If this autocomplete list is not available, it may be due to the Maven repository being indexed for the first time. In this situation you will then see the following screenshot at the bottom of the editor:

Be patient and in a few minutes the indexing will be finished and the autocomplete will become available. Indexing is required to download available entries from the Maven repository.

The required Spring Framework components are as follows:

spring-context: This is the central artifact required for Spring's dependency injection containerspring-tx: This is the transaction management abstraction required for implementing transactional behaviorspring-context-support: These are various application context utilities, including Ehcache, JavaMail, Quartz, and FreeMarker integrationspring-jdbc: This is the JDBC data access libraryspring-orm: This is the Object-to-Relation-Mapping (ORM) integration for JPA developmentspring-instrument: This is for the weaving of classesspring-webmvc: This is the Spring Model-View-Controller (MVC) for Servlet environmentsspring-test: This is the support for testing Spring applications with JUnit

To add these dependencies using the latest Spring release version (3.2.4) requires the following additions to the pom.xml file:

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.4.RELEASE</version> </dependency>

Understanding dependency scope

The final Spring Framework dependency is only required for testing. We can define this by adding a scope attribute with value test. This tells Maven that the dependency is only required when running the testing phase of the build and is not required for deployment.

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.4.RELEASE</version> <scope>test</scope> </dependency>

The javaee-web-api dependency that was automatically created by NetBeans has a scope of provided. This means the dependency is not required for deployment and is provided by the target server. The GlassFish 4 server itself is the provider of this dependency.

If the scope attribute has not been included, the dependency JAR will be included in the final build. This is the equivalent of providing a scope entry of compile. As a result, all the Spring Framework dependency JARs will be included in the final build file.

A full explanation of the Maven dependency mechanism and scoping can be found at http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html.

Defining Maven properties

The Spring Framework dependencies defined in pom.xml all have the same version (3.2.4.RELEASE). This duplication is not ideal, especially when we wish to upgrade to a newer version at a later time. Changes would be required in multiple places, one for each Spring dependency. A simple solution is to add a property to hold the release version value as shown in the following code:

<properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.2.4.RELEASE</spring.version> </properties>

This custom property, which we have named spring.version, can now be used to replace the multiple duplicates as follows:

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency>

The ${spring.version} placeholder will then be substituted with the properties value during the build process.

Understanding Maven-build plugins

The Maven build process executes each defined build plugin during the appropriate build phase. A full list of build plugins can be found at http://maven.apache.org/plugins/index.html. We will introduce plugins as needed in subsequent chapters, but the default plugins created by the NetBeans IDE are of interest now.

The maven-compiler-plugin controls and executes the compilation of Java source files. This plugin allows you to specify both the source and target Java versions for compilation as shown in the following code:

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <compilerArguments> <endorseddirs>${endorsed.dir}</endorseddirs> </compilerArguments> </configuration> </plugin>

Changing these values to 1.6 may be required when compiling projects for older Java servers running on the earlier versions of Java.

The maven-war-plugin builds a WAR file for the project as follows:

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin>

The default generated WAR filename is {artifactId}-{version}.war, which can be changed by including the warName configuration property. We will be adding properties to this plugin when building the project for production release in the final chapter. A full list of maven-war-plugin options may be found at http://maven.apache.org/plugins/maven-war-plugin/war-mojo.html.

The maven-dependency-plugin copies dependency JAR files to the defined output directory as shown in the following code:

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.6</version> <executions> <execution> <phase>validate</phase> <goals> <goal>copy</goal> </goals> <configuration> <outputDirectory>${endorsed.dir}</outputDirectory> <silent>true</silent> <artifactItems> <artifactItem> <groupId>javax</groupId> <artifactId>javaee-endorsed-api</artifactId> <version>7.0</version> <type>jar</type> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin>

This is useful to see which JARs are used by the project and to identify what transitive dependencies are required (dependencies of dependencies).

We will modify this plugin to copy all compile-time dependencies of the project to a directory in ${project.build.directory}. This special build directory is under the root folder of the project and is named target, the target destination of the build process. The updated entry will now look as follows:

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.1</version> <executions> <execution> <id>copy-endorsed</id> <phase>validate</phase> <goals> <goal>copy</goal> </goals> <configuration> <outputDirectory>${endorsed.dir}</outputDirectory> <silent>true</silent> <artifactItems> <artifactItem> <groupId>javax</groupId> <artifactId>javaee-endorsed-api</artifactId> <version>7.0</version> <type>jar</type> </artifactItem> </artifactItems> </configuration> </execution> <execution> <id>copy-all-dependencies</id> <phase>compile</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib </outputDirectory> <includeScope>compile</includeScope> </configuration> </execution> </executions> </plugin>

As we are now performing two executions in the single plugin, each execution needs its own <id>. The second execution, with ID copy-all-dependencies, will copy all dependent JARs with the scope compile to the target/lib directory.

Executing the Maven build

The simplest way to execute a build is to click on the Clean and Build Project button in the toolbar. You can also right-click on the project node in the Projects tab and select Clean and Build from the menu. The build process will then execute each defined phase in the POM, resulting in Java code compilation, dependency resolution (and copying), and finally, WAR file generation. Opening the target directory structure will display the build result as follows:

Even though we have not written a single line of code, the generated WAR file task-time-tracker-1.0.war can now be deployed to the GlassFish server.

Starting the GlassFish 4 server

Opening the Services tab and expanding the Servers