Building RESTful Web Services with Spring 5 - Raja CSP Raman - E-Book

Building RESTful Web Services with Spring 5 E-Book

Raja CSP Raman

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

REST is an architectural style that tackles the challenges of building scalable web services. In today's connected world, APIs have taken a central role on the web. APIs provide the fabric through which systems interact, and REST has become synonymous with APIs.The depth, breadth, and ease of use of Spring makes it one of the most attractive frameworks in the Java ecosystem. Marrying the two technologies is therefore a very natural choice.This book takes you through the design of RESTful web services and leverages the Spring Framework to implement these services. Starting from the basics of the philosophy behind REST, you'll go through the steps of designing and implementing an enterprise-grade RESTful web service. Taking a practical approach, each chapter provides code samples that you can apply to your own circumstances.This second edition brings forth the power of the latest Spring 5.0 release, working with MVC built-in as well as the front end framework. It then goes beyond the use of Spring to explores approaches to tackle resilience, security, and scalability concerns. Improve performance of your applications with the new HTTP 2.0 standards. You'll learn techniques to deal with security in Spring and discover how to implement unit and integration test strategies.Finally, the book ends by walking you through building a Java client for your RESTful web service, along with some scaling techniques using the new Spring Reactive libraries.

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

EPUB
MOBI

Seitenzahl: 195

Veröffentlichungsjahr: 2018

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.



Building RESTful Web Services with Spring 5Second Edition

 

 

 

 

 

 

Leverage the power of Spring 5.0, Java SE 9, and Spring Boot 2.0

 

 

 

 

 

 

 

Raja CSP Raman
Ludovic Dewailly

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Building RESTful Web Services with Spring 5 Second Edition

Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Aaron LazarAcquisition Editor: Chaitanya NairContent Development Editor: Zeeyan PinheiroTechnical Editor: Romy DiasCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Rekha Nair Graphics: Jason MonteiroProduction Coordinator: Shantanu Zagade

First published: October 2015 Second edition: January 2018

Production reference: 1230118

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78847-589-1

www.packtpub.com

To my parents, Raman and Gandhi, for their great support through my tough times and for nurturing me to be prepared for whatever challenges come my way. To my brother and sister for their wishes and guidance throughout my life. 
– Raja CSP Raman
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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.

Contributors

About the authors

Raja CSP Raman has been a software developer for 13 years and is the founder of TalentAccurate, an IT skills validation tool that helps start-ups and small companies filter candidates without going through their resume. He also founded Pointopedia, a website that provides 15 lines of information on any topic, without any images or links. Raja likes photography and watching documentaries on history and science.

I'd like to thank my parents, brother, and sister, who guided and encouraged me to write this book. Also, I'd like to thank my TCE (Thiagarajar College of Engineering) classmates who inspired me and helped me focus on my vision. I especially thank Zeeyan, Romy, and other editors for their wonderful guidance throughout this book! Without them, I wouldn't have done it. 

Ludovic Dewaillyis a senior, hands-on software engineer and development manager with over 12 years of experience in designing and building software solutions on platforms ranging from resource-constrained mobile devices to cloud computing systems. He is currently helping FancyGiving (a social shopping, wishing, and gifting platform) with designing and building their system. Ludovic's interests lie in software architecture and tackling web scale challenges.

About the reviewer

Glenn De Paula is a graduate of the University of the Philippines Integrated School and is a computer science graduate from the University of the Philippines. He has 12 years of industry experience, in the government's ICT institute and the banking industry.

He uses Spring, Grails, and JavaScript for his day-to-day activities. He has developed numerous Java web applications for the government and has been the team leader on several projects.

He is consistently involved in systems analysis and design, source code review, testing, implementation, training, and mentoring.

I would like to thank the author of this book, the editors, and our publisher, Packt Publishing, for giving me this opportunity.I would also like to thank my managers and supervisors for mentoring me and trusting me with projects that helped improve my career. A big thank you to my family and friends for all the support. Especially, I thank my wife, Elaine, for all the love and patience.

 

 

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

A Few Basics

REST – a basic understanding

Uniform interface

Client and server

Stateless

Cacheable

Layered system

Code on demand (COD)

More on REST

Imperative and Reactive programming

Reactive Streams

Benefits of Reactive programming

Reactive programming in Java and Spring 5

Our RESTful web service architecture

Summary

Building RESTful Web Services in Spring 5 with Maven

Apache Maven

Creating a project with Maven

Viewing a POM file after creating a project

POM file structure

Understanding POM dependencies

Adding Log4j 2.9.1 to POM dependency

Dependency trees

Spring Boot

Developing RESTful web services

Creating a project base

Working with your favorite IDE

Summary

Flux and Mono (Reactor Support) in Spring

Benefits of Reactive programming

Reactive Core and Streams

Back pressures and Reactive Streams

WebFlux

Basic REST API

Flux

Mono

User class with Reactive – REST

Summary

CRUD Operations in Spring REST

CRUD operations in Spring REST 

HTTP methods

Reactive server initialization

Sample values in the repository

getAllUsers – mapping

getAllUsers – implementation in the handler and repository

Testing the endpoint – getAllUsers

getUser – implementation in the handler and repository

Testing the endpoint – getUser

createUser – implementation in the handler and repository

Testing the endpoint – createUser

updateUser – implementation in the handler and repository

Testing the endpoint – updateUser

deleteUser – implementation in the handler and repository

Testing the endpoint – deleteUser

Summary

CRUD Operations in Plain REST (Without Reactive) and File Upload

Mapping CRUD operations to HTTP methods

Creating resources

CRUD operation in Spring 5 (without Reactive)

getAllUsers – implementation

getUser – implementation

createUser – implementation

updateUser – implementation

deleteUser – implementation

File uploads – REST API

Testing the file upload

Summary

Spring Security and JWT (JSON Web Token)

Spring Security

Authentication and authorization

JSON Web Token (JWT)

JWT dependency

Creating a JWT token

Generating a token

Getting a subject from a JWT token

Getting a subject from a token

Summary

Testing RESTful Web Services

JUnit

MockMvc

Testing a single user

Postman

Getting all the users – Postman

Adding a user – Postman

Generating a JWT – Postman

Getting the subject from the token

SoapUI

Getting all the users – SoapUI

Generating JWT SoapUI

Getting the subject from the token – SoapUI

jsoup

Getting a user – jsoup

Adding a user – jsoup

Running the test cases

Summary

Performance

HTTP compression

Content negotiation

Accept-Encoding

Content-Encoding

Server-driven content negotiation

Agent-driven content negotiation

HTTP caching

HTTP cache control

Public caching

Private caching

No-cache

Only-if-cached

Cache validation

ETags

Last-Modified/If-Modified-Since headers

Cache implementation

The REST resource

Caching with ETags

Summary

AOP and Logger Controls

Aspect-oriented programming (AOP)

AOP (@Before) with execution

Testing AOP @Before execution

AOP (@Before) with annotation

Testing AOP @Before annotation

Integrating AOP with JWT

Logger controls

SLF4J, Log4J, and Logback

Logback framework

Logback dependency and configuration

Logging levels

Logback implementation in class

Summary

Building a REST Client and Error Handling

Building a REST client

RestTemplate

Error handling

Customized exception

Summary

Scaling

Clustering

Benefits of clustering

Load balancing

Scaling databases

Vertical scaling

Horizontal scaling

Read replicas

Pool connections

Use multiple masters

Load balancing in DB servers

Database partitioning

Sharding (horizontal partitioning)

Vertical partitioning

Distributed caching

Data-tier caching

First-level caching

Second-level caching

Application-tier caching

Memcached

Redis

Hazelcast

Ehcache

Riak

Aerospike

Infinispan

Cache2k

Other distributed caching

Amazon ElastiCache

Oracle distributed cache (Coherence)

Summary

Microservice Basics

Monolithic architecture and its drawbacks

Introduction to microservices

Independence and autonomy

Resilience and fault tolerance

Automated environment

Stateless

Benefits of microservices

Microservice components

Configuration server

Load balancer

Service discovery

Circuit breaker

Edge server

Microservice tools

Netflix Eureka

Netflix Zuul

Spring Cloud Netflix

Netflix Ribbon

Netflix Hystrix

Netflix Turbine

HashiCorp Consul

Eclipse MicroProfile

Summary

Ticket Management – Advanced CRUD

Ticket management using CRUD operations

Registration

User types

User POJO

Customer registration

Admin registration

CSR registration

Login and token management

Generating a token

Customer login

Admin login

CSR login

Ticket management

Ticket POJO

Getting a user by token

User Ticket management

Ticket controller

The UserTokenRequired interface

The UserTokenRequiredAspect class

Getting my tickets – customer

Allowing a user to view their single ticket

Allowing a customer to update a ticket

Updating a ticket – service (TicketServiceImpl)

Deleting a ticket

Deleting a service – service (TicketServiceImpl)

Deleting my ticket – API (ticket controller)

Admin Ticket management

Allowing a admin to view all tickets

Getting all tickets – service (TicketServiceImpl)

Getting all tickets – API (ticket controller)

The AdminTokenRequired interface

The AdminTokenRequiredAspect class

Admin updates a ticket

Updating a ticket by admin – service (TicketServiceImpl)

Allowing admin to view a single ticket

Allowing admin to delete tickets

Deleting tickets – service (TicketServiceImpl):

Deleting tickets by admin – API (ticket controller):

CSR Ticket management

CSR updates a ticket

CSRTokenRequired AOP

CSRTokenRequiredAspect

CSR view all tickets

Viewing all tickets by CSR – API (ticket controller)

CSR view single ticket

CSR delete tickets

Deleting tickets – service (TicketServivceImpl)

Deleting tickets by CSR – API (ticket controller)

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

REST is an architectural style that tackles the challenges of building scalable web services. In today's connected world, APIs have taken a central role on the web. APIs provide the fabric through which systems interact, and REST has become synonymous with APIs. The depth, breadth, and ease of use of Spring makes it one of the most attractive frameworks in the Java ecosystem. Marrying the two technologies is, therefore, a very natural choice. Starting from the basics of the philosophy behind REST, this book goes through the necessary steps to design and implement an enterprise-grade RESTful web service. Taking a practical approach, each chapter provides code samples that you can apply to your own circumstances. This second edition brings forth the power of the latest Spring 5.0 release, working with built-in MVC, as well as the frontend framework. You'll learn techniques to deal with security in Spring and discover how to implement unit and integration test strategies.

Finally, the book ends by walking you through building a Java client for your RESTful web service, along with some scaling techniques using the new Spring Reactive libraries.

Who this book is for

This book is intended for those who want to learn to build RESTful web services with the latest Spring Framework 5.0. To make best use of the code samples included in the book, you should have a basic knowledge of the Java language. Previous experience with the Spring Framework will also help you get up and running quickly.

What this book covers

Chapter 1,  A Few Basics, covers a basic understanding of REST, Reactive programming, and their basics, including the benefits of Reactive programming. It also covers Spring 5 basics with Reactive programming and an example RESTful web service as a base for other chapters.

Chapter 2, Building RESTful Web Services in Spring 5 with Maven, covers how to build a RESTful web service with Apache Maven by using either the Eclipse IDE or STS (Spring Tool Suite). The second section of the chapter covers creating a new project in Eclipse/STS and running our basic REST API.

Chapter 3, Flux and Mono (Reactor Support) in Spring, discusses Reactive programming and its benefits. This chapter also covers a little bit about Reactive Core and Reactive Streams. The second section of this chapter covers Flux and Mono in Spring REST, including a basic implementation of the GET and POST methods in Reactive.

Chapter 4, CRUD Operations in Spring REST, covers mapping CRUD operations to HTTP methods and implementation of CRUD operations on User with Reactor support.

Chapter 5, CRUD Operations in Plain REST (Without Reactive) and File Upload, covers mapping CRUD operations to HTTP methods and implementation of CRUD operations on User (Create, Read, Update, and Delete) without Reactor support. Also, this chapter covers file uploading in Spring.

Chapter 6, Spring Security and JWT (JSON Web Token), covers Spring Security, JWT (JSON Web Token), and JWT generation. The second section of this chapter covers getting details from the generated token and also restricting service calls by JWT security.

Chapter 7, Testing RESTful Web Services, talks about various testing strategies to test our existing RESTful web services, including JUnit and MockMvc-like unit test cases, and clients such as Postman, SoapUI, and jsoup web reader.

Chapter 8, Performance, discusses different performance-related topics, including HTTP compression, HTTP caching, and HTTP control. The second section of the chapter covers cache implementation and HTTP headers such as If-Modified-Since and ETag.

Chapter 9, AOP and Logger Controls, covers Spring AOP, including its theory, implementation, and logging controls.

Chapter 10, Building a REST Client and Error Handling, covers RestTemplate in Spring, the basic setup for building a RESTful service client with Spring, and calling the RESTful service from the client side. The second section of the chapter covers error handling, including defining an error handler and using it.

Chapter 11, Scaling, covers the techniques, libraries, and tools used for application scaling purposes. It includes clustering and the benefits of clustering. This chapter also covers load balancing, scaling a database, and distributed caching.

Chapter 12, Microservice Basics, talks about microservices, the benefits of microservices, and the basic characteristics of microservices. It also covers various microservice components.

Chapter 13, Ticket Management - Advanced CRUD, covers advanced CRUD operations on tickets, including creating and updating a ticket through a customer, updating a ticket by CSR, and updating a ticket by admin. This chapter also talks about deleting multiple tickets by CSR and admin.

To get the most out of this book

The following is a descriptive list of the requirements to test all the code in this book:

Hardware: 64-bit machine with minimum 2 GB RAM and min 5 GB of free hard disk space

Software: Java 9, Maven 3.3.9, STS (Spring Tool Suite) 3.9.2 

Java 9: All code is tested on Java 9

SoapUI: SoapUI 5.2.1 (free version) is used for REST API calls

Postman: For REST client testing, Postman 5.0.4 is used

 

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Building-RESTful-Web-Services-with-Spring-5-Second-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/BuildingRESTfulWebServiceswithSpring5_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

A Few Basics

As the world has moved into the big data era, collecting and dealing with data alone has become the main part of most of our web applications, and web services, too, as web services deal only with data, not the other parts of the user experience, look, and feel. Even though user experience is very important for all web applications, web services play a major role in dealing with data by consuming services from the client side.

In the early days of web services, Simple Object Access Protocol (SOAP) was the default choice for all backend developers who dealt with web service consumption. SOAP was mainly used in HTTP and Simple Mail Transfer Protocol (SMTP) for message transmission across the same or different platforms. When there was no JavaScript Object Notation (JSON) format available for web services, XML used to be the only available format SOAP could use for the web service consumption.

However, in the JSON era, Representational State Transfer (REST) started dominating web service based applications, as it supports multiple formats, including JSON, XML, and other formats. REST is simpler than SOAP, and the REST standards are easy to implement and consume. Also, REST is lightweight as compared to SOAP.

In this chapter, we will cover the following topics:

REST—a basic understanding

Reactive programming and its basics, including the benefits of Reactive programming

Spring 5 basics with Reactive programming

A sample RESTful web service that will be used as a base for the rest of the book

REST – a basic understanding

Contrary to popular belief, REST is not a protocol, but an architectural principle for managing state information. It's mainly used in web applications. REST was introduced by Roy Fielding to overcome implementation difficulties in SOAP. Roy's doctoral dissertation made for an easy way to retrieve data, regardless of the platform used. You will see all the components of RESTful web services in the following sections.

Uniform interface

In REST principles, all resources are identified by the Uniform Resource Identifier (URI).