Mastering Spring Application Development - Anjana Mankale - E-Book

Mastering Spring Application Development E-Book

Anjana Mankale

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

If you are a Java developer with experience in developing applications with Spring, then this book is perfect for you. A good working knowledge of Spring programming conventions and applying dependency injections is recommended to make the most of this book.

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

EPUB
MOBI

Seitenzahl: 229

Veröffentlichungsjahr: 2015

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.



Table of Contents

Mastering Spring Application Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Spring Mongo Integration
Installing MongoDB and creating a database
Setting up a batch file for MongoDB
Order use case with Spring and MongoDB
Mapping a Mongo document to Spring Bean
Setting up a Spring-MongoDB project
Application design
Application implementation of Spring with MongoDB
Order management use case
Creating and inserting Order
Controller to handle requests
Adding the @Modelattribute annotation at the Method level
CRUD operations of the OrderController class
JSP files
Summary
2. Messaging with Spring JMS
Types of messaging
Message consumers
Message structure
Message-driven POJOs and listeners
Open source messaging tools
Apache ActiveMQ
Setting up ApacheMQ for point-to-point messaging
Use case for ApacheMq with Spring JmsTemplate
Spring dependency
Implementing the Order Management Messaging System with SpringJMS and ActiveMQ
Configuring dispatcherservlet.xml to use JMS
Working with multiple queues in ApacheMQ
Configuring JMS transactions
Configuring multiple JMS listeners and adapters
JMS transactions
Summary
3. Mailing with Spring Mail
Spring mail message handling process
Interfaces and classes used for sending mails with Spring
Sending mail using the @Configuration annotation
Sending mail using MailSender and SimpleMailMessage with the XML configuration
Sending mails to multiple recipients
Sending MIME messages
Sending attachments with mails
Sending preconfigured mails
Using Spring templates with Velocity to send HTML mails
Sending Spring mails over a different thread
Sending Spring mails with AOP
Summary
4. Jobs with Spring Batch
Introduction to Spring Batch
Use cases for using Spring Batch
Goals of batch processing
Architecture of a batch job
Using an enterprise batch
Dependency for Spring Batch
Key components of Spring Batch
Developing a sample batch application
Creating a sample batch application using the Tasklet interface
Using Spring Batch to read a CSV file
Spring Batch with a Spring scheduler
Configuring Spring Batch with Quartz scheduler
Using Spring Batch to read a file and update a MongoDB database
Using Spring Batch with threads to partition jobs
Intercepting a Spring Batch job with listeners
Unit testing Spring Batch applications
Summary
5. Spring Integration with FTP
Maven dependency
Spring's XSD for FTP
Configuring an outbound channel adapter for FTP
Configuring an inbound channel adapter for FTP
FTPSessionFactory and FTPSSessionFactory
Spring FTP using an outbound channel example
Configuring Spring FTP to read files in subfolders using the gateway
Configuring Spring FTP in Java
Sending files over FTP using the Spring integration
FTP application using the Spring integration and Spring batch
Summary
6. Spring Integration with HTTP
HTTP methods and status codes
HTTP headers
HTTP time-out
HTTP proxy settings in Java
Proxy configuration support in Spring
Spring Integration support for HTTP
Spring Integration support for multipart HTTP requests
Spring Integration support for HTTP responses
Configuring the outbound HTTP messages
Configuring cookies with OutboundGateway
Configuring InboundGateway with both no response and with the response
RequestMapping support for an inbound channel adapter or a gateway
Configuring the RequestMapping using the HTTP inbound endpoint
Configuring the inbound channel adapter to read request information from the URL
Configuring the outbound gateway for HTTP responses
Configuring the outbound adapter for different response types
Mapping URI variables as subelement with an HTTP outbound gateway and an outbound channel adapter
Handling time-out with the HTTP outbound gateway and the HTTP inbound gateway
Spring support for header customizations
Sending multipart HTTP requests using Spring's RestTemplate
Summary
7. Spring with Hadoop
Apache Hadoop modules
Spring namespace for Hadoop
Hadoop Distributed Files System
HBase
Map and Reduce
Creating a configuration object in Spring for Map and Reduce
Map and Reduce jobs with Spring
Dependencies for Maven project
Map and Reduce jobs using Hadoop streaming and Spring DataApache Hadoop
Summary
8. Spring with OSGI
OSGI containers
OSGI usage
Spring integration with OSGI
Spring Dynamic Modules and OSGI
Simple applications with OSGI
Integrating Spring Dynamic Modules with OSGI
Summary
9. Bootstrap your Application with Spring Boot
Setting up Spring Boot
Spring Gradle MVC application
Hot swapping with Spring Boot
Integrating Spring Boot with Spring Security
Cloud Foundry support for Eclipse Spring Boot
RestfulWebService using Spring Boot
Summary
10. Spring Cache
Spring annotations for caching
@Cacheable usage
The @CacheEvict usage
Spring caching repository
The Ehcache popular library
Spring CacheManager
Maven dependency for Spring with caching
Declarative configuration of ehcache
Spring MVC with caching
Implementing your own caching algorithm
Summary
11. Spring with Thymeleaf Integration
Thymeleaf attributes
Spring Thymeleaf dependency
Spring MVC and Thymeleaf
MVC with Spring Thymeleaf
Spring Boot with Thymeleaf and Maven
Reloading Thymeleaf templates
Spring security with Thymeleaf
Summary
12. Spring with Web Service Integration
Spring with JAX-WS
Spring Web Services with JAXB marshalling for request
Writing a client application for Spring Web Services using JAXB unmarshalling for request
Summary
Index

Mastering Spring Application Development

Mastering Spring Application Development

Copyright © 2015 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 authors, 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: May 2015

Production reference: 1270515

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-732-0

www.packtpub.com

Credits

Author

Anjana Mankale

Reviewers

Nanda Nachimuthu

Chandan Sharma

Commissioning Editor

Julian Ursell

Acquisition Editor

Sonali Vernekar

Content Development Editor

Athira Laji

Technical Editor

Chinmay S. Puranik

Copy Editors

Sonia Michelle Cheema

Brandt D'Mello

Ulka Manjrekar

Project Coordinator

Harshal Ved

Proofreaders

Stephen Copestake

Safis Editing

Indexer

Monica Ajmera Mehta

Graphics

Disha Haria

Abhinash Sahu

Production Coordinator

Nilesh R. Mohite

Cover Work

Nilesh R. Mohite

About the Author

Anjana Mankale is a tech lead and has 8 years of experience in developing web applications. She has developed applications for healthcare, e-commerce portals, media portals, and content management systems using Spring and Struts2. She is extensively involved in application design and implementation. She has worked on Amazon Cloud and Spring Web Services and has recently been involved in deploying and designing cloud-based multitenant applications. Anjana has also authored a cookbook, Spring Security 3.x Cookbook, Packt Publishing.

Anjana is passionate about blogging (http://jtechspace.blogspot.in/), where she shares her write-ups and technical code that she has worked on.

I would like to thank my husband, Raghavendra S., for providing complete support and encouragement by intimating me about the timelines. This book is dedicated to my father, M. G. Prasad. Lastly, I would like to thank my parents and in-laws for their encouragement in completing this book.

About the Reviewers

Nanda Nachimuthu studied at IIT Kharaghpur and specializes in advanced Internet programming. He has 18 years of IT experience, which includes 10 years as an architect in various technologies, such as J2EE, SOA, ESB, Cloud, big data, and mobility.

He has designed, architected, and delivered many national projects and large-scale commercial projects. He is also involved in product design and development of various products in the insurance, finance, logistics, and life sciences domains.

Chandan Sharma is currently a software program analyst at Mroads, located in the US. It focuses on building the next generation workforce and leverages technology and awareness.. At Mroads, his primary responsibility is designing and implementing solutions that use Liferay, Spring Framework, and Hibernate for Portals, as well as for RESTful/SOAP Web services. Previously, he has worked as a senior consultant for Cignex Datamatics and TransIT mPower Labs. He also likes to coach people in the technology. Due to the experience he's gained throughout his career, he has developed hands-on experience in Liferay with Spring Framework, Hibernate and Liferay Integration with other applications, cloud technology, and so on. He also has his own technical blog at http://codingloading.com.

I would like to thank Packt Publishing for the opportunity given to me to review this book. I would like to thank Gaurav Vaish (author of Getting started with NoSQL, Packt Publishing) who inspired me to review this book. I would like to express my gratitude to my "rakhi" sister, Meenu Gupta, for her support and encouragement while reviewing this book. I am also grateful to my "cracked" group of friends (Monalisa Sahu, Manoj Patro, and Debasis Padhi) for encouraging me to do new things in my life. I would like to especially thank my best friend who helped me review this book.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read 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 a 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 9 entirely free books. Simply use your login credentials for immediate access.

Preface

Spring is an open source Java application development framework that is used to build and deploy systems and applications that run on a JVM. It makes efficiently built modular and testable web applications, by using a Model-View-Controller paradigm and dependency injection. It seamlessly integrates with numerous frameworks (such as Hibernate, MyBatis, Jersey, and so on), and reduces boilerplate code when using standard technologies, such as JDBC, JPA, and JMS.

The purpose of this book is to teach intermediate-level Spring developers to master Java application development with Spring, applying advanced concepts and using additional modules to extend the core framework. This is done to develop more advanced, strongly integrated applications.

What this book covers

Chapter 1, Spring Mongo Integration, demonstrates the integration of a Spring MVC with MongoDB along with installing MongoDB, to create database and collections.

Chapter 2, Messaging with Spring JMS, teaches you to install Apache ActiveMQ and different types of messaging. This chapter also demonstrates the creation of multiple queues and communicating with these queue using Spring templates with the help of screenshots.

Chapter 3, Mailing with Spring Mail, creates a mailing service and configures it using the Spring API, and demonstrates how to send mails with attachments using MIME messages.

Chapter 4, Jobs with Spring Batch, illustrates how Spring Batch can be used to read an XML file,and also how to create Spring-based batch applications to read a CSV file. This chapter also demonstrates how to write simple test cases using Spring Batch.

Chapter 5, Spring Integration with FTP, gives you an overviewof different types of adapters, such as inbound and outbound adapters, with an outbound gateway and its configurations. This chapter also looks into two important classes, FTPSessionFactory and FTPsSessionFactory, by using getter and setter.

Chapter 6, Spring Integration with HTTP, takes you through theuse of a multivalue map to populate a request and put the map in the HTTP header. Also, it will provide you with information about HTTP and Spring integration support, which can be used to access HTTP methods and requests.

Chapter 7, Spring with Hadoop, shows how Spring integrates with Apache Hadoop and provides Map and Reduce processes to search and count data. The chapter also discussed installing a Hadoop instance on Unix machines and configuring Hadoop jobs in a Spring framework.

Chapter 8, Spring with OSGI, develops a simple OSGI application, and also demonstrates how a Spring dynamic module supports OSGI development and reduces the creation of files, thereby making things easier with configuration.

Chapter 9, Bootstrap your Application with Spring Boot, starts with setting up a simple Spring boot project, along with the process of using a Spring Boot to bootstrap applications. This chapter also gives information about how a Spring Boot supports a cloud foundry server and helps to deploy applications on cloud.

Chapter 10, Spring Cache, implements our own caching algorithm and teaches you to make a generic algorithm. This chapter also discusses the classes and interface that support a caching mechanism in a Spring Framework.

Chapter 11, Spring with Thymeleaf Integration, integrates the Thymeleaf templating engine into a Spring MVC application, and also uses a Spring Boot to start Spring with a Thymeleaf application.

Chapter 12, Spring with Web Service Integration, integrates JAX_WS with Spring Web Service. It demonstrates how to create spring Web services and an endpoint class, accessing the web service by accessing the WSDL URL.

What you need for this book

A computer with Mac OS, Ubuntu, or Windows is needed. To build Spring applications, you will need at least Java and Maven 3.

Who this book is for

If you are a Java developer with experience in developing applications with Spring, then this book is perfect for you. A good working knowledge of Spring programming conventions and applying dependency injection is recommended to make the most of this book.

Conventions

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

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We have used the @Controller annotation to indicate that the ProductController.java class is a controller class."

A block of code is set as follows:

@Controller public class ProductController { @Autowired private ProductRepository respository; private List <Product>productList; public ProductController() { super(); }

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

public class MailAdvice { public void advice (final ProceedingJoinPoint proceedingJoinPoint) { new Thread(new Runnable() { public void run() {

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

cd E:\MONGODB\mongo\binmongod -dbpath e:\mongodata\db

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The next step is to create a rest controller to send a mail; to do so, click on Submit."

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 disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

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 from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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 could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Spring Mongo Integration

MongoDB is a popular NoSQL database and is a document-based one too. It is written using the popular and powerful C++ language, which makes it a document-oriented database. Queries are also document-based, and it also provides indexing using JSON style to store and retrieve data. MongoDB works on the concept of collection and documentation.

Let's look at few terminology differences between MySQL and MongoDB:

MySQL

MongoDB

Table

Collection

Row

Document

Column

Field

Joins

Embedded documents linking

In MongoDB, a collection is a set or a group of documents. It is the same as RDBMS tables.

In this chapter, we shall start by setting up a MongoDB NoSQL database and will integrate a spring application with MongoDB to perform CRUD operations. The first example demonstrates updating single document values. The second example considers an order use case where it requires two document references to be stored in the collection. It demonstrates the flexibility in referencing different documents of MongoDB using objectId references.

We need to go for a NoSQL database only if the applications have heavy write operations. MongoDB also suits the cloud environment very well, where we can take copies of databases easily.

In the next section, we shall see how we can get started with MongoDB, beginning with installing it, using the Spring Framework, and integrating MongoDB. To get started, we shall show basic Create, Retrieve, Update, and Delete (CRUD) operations with various use cases.

Installing MongoDB and creating a database

In this section we shall install MongoDB and create a database:

Download the MongoDB database at http://www.mongodb.org/downloads.Configure the data folder by executing the following command in the bin folder:
>mongod.exe -dbpath e:\mongodata\db
Start mongod.exe in another Command Prompt.Execute the following command:
>show databaseExecute

The >show dbs command also works fine with MongoDB.

Execute the following command to create a new database, namely eshopdb.
>use new-eshopdb
Executing > show dbs will still show that eshopdb hasn't been created yet; this is because it doesn't contain any collections. Let's add some collections in the next step, once a collection is added.Execute the following snippet in the Command Prompt. The following snippets will insert sample documents into the collection:
db.eshopdb.insert({cust_id:1,name:"kishore",address:"jayangar"})db.eshopdb.insert({cust_id:2,name:"bapi",address:"HAL Layout"})db.eshopdb.insert({cust_id:3,name:"srini",address:"abbigere street"})db.eshopdb.insert({cust_id:4,name:"sangamesha",address: "Kattarigupee layout"})

Setting up a batch file for MongoDB

It's always easy to create a batch file to start MongoDB, and it's best to create a script file to start Mongo. This way, we won't have an error with the configuration. This would also save us a lot of time.

Create a mongodbstart.bat file. Edit the file and type in the following command and save it:
cd E:\MONGODB\mongo\binmongod -dbpath e:\mongodata\db

The next time you want to start MongoDB, just click on the batch file.

Order use case with Spring and MongoDB

Let us look at the Order use case to implement a simple CRUD operation using Spring and MongoDB. We are performing CRUD operations on Product, Customer, and Order documents. The scenario is this: a customer selects a product and places an order.

Following is the Order use case. The actor is the application user and will have the following options:

CRUD operation on Product DocumentCRUD operation on Customer DocumentCRUD operation on Order by selecting Product and CustomerSaving the Product Document Object ID and Customer Document Object ID in Order Document

Mapping a Mongo document to Spring Bean

Spring provides a simple way to map Mongo documents. The following table depicts the mapping of Bean with MongoDB collections:

Bean

Mongo Collections

Customer.java

db.customer.find()

Order.java

db.order.find()

Product.java

db.product.find()