0% found this document useful (0 votes)
41 views177 pages

Spring Boot Project Document

The document provides an overview of Spring Boot, detailing its structure, including the project model, services, and microservices. It outlines the implementation of a warehouse project, emphasizing the three-D concept (Domain, Design, Development) and the use of application properties for configuration. Additionally, it covers REST coding, database configuration, and the integration of Swagger for API documentation.

Uploaded by

bhanu_billa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views177 pages

Spring Boot Project Document

The document provides an overview of Spring Boot, detailing its structure, including the project model, services, and microservices. It outlines the implementation of a warehouse project, emphasizing the three-D concept (Domain, Design, Development) and the use of application properties for configuration. Additionally, it covers REST coding, database configuration, and the integration of Swagger for API documentation.

Uploaded by

bhanu_billa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

Raghu Sir [Sathya technologies, Ameerpet]

22 Jan 2018

Spring Boot:-

 Spring Boot is an abstract project which provides common code to


develop
All layers in project.[Presentation Layer,ServiceLayer,Data Access
Layer,Integration Layer].
 Here Boot means providing startup code (Or common Code).
 Spring Boot is a Maven Project which is also called as “Parent Project”.
 Compare to spring f/w, Boot reduces spring configuration code
(ex.<bean/>), also xml code like web.xml, views.xml etc.
 In case of Boot, common code in layers will be generated. We can write
remaining code over generated code.

Spring Boot Project Model:-

 Spring Boot is a Parent Maven project,this will be extended by Child


MavenProject written by programmer.
 Format looks like:

1
Raghu Sir [Sathya technologies, Ameerpet]

Services:-

 A service is a task or a work in application. A project is a collection of


Services. Every project contains some common services which need to
be written by programmer.
 Ex. Email-Service, Authentication Service, OTP Service, Captcha
Generation Service,Currency Conversion Service, Weather Report
Service, Log4j Service, Message Passing Service, Transaction Service,
Connection Pooling Service, Code Generation Service, Data-Export &
Data-Import Service etc.

Micro-Services:-

 A server which has common services for all projects is called “Micro-
Services Server”. [Cloud Server:- Every micro-Service is an
independentservice and small service (few lines of code)].
 Every micro service will be used in our application, with the help of
“Web-Services”. Web-Service works like link between our project to
Micro-Service
 Advantages:-
1. Every micro-serviceis “pre-developed” service so no code
required for development in our application only use/call using
Micro-service.
2. No testing is required to be done by programmer while doing
integration to our project.
3. Every micro-services run in different server (not in our server i.e.
production server) this can also called as “cloud Server”.
4. Micro Service can be integrated easily with our application [easy
link].If we do not required service then unlink can be done easily
without any high level changes in our application. It is also called
as “Plug-in Service”.
5. See the diagram below:-

2
Raghu Sir [Sathya technologies, Ameerpet]

Diagram: - Micro Service

3
Raghu Sir [Sathya technologies, Ameerpet]

Project Implementation:-

To implement one project, we should know three-D concept[3D’s] also


called as
1. Domain:-It indicates project category Or what type of project it is.
Some examples domains are Banking, Medical, Transport,
Govt.Services, Entertainment, shopping, Third Party Wallet Service,
Warehouse, etc.
2. Design:-A graphical representation of a project [images] is called
“Design”.A design may show commonly used designs are
i. UML-Unified Modeling Language works only for OOP’s
E.g.Java, .Net
ii. DFD-Data Flow Diagram gives step by step execution of project
using flow diagram.
E.g. Register->Login->Create Employee->Generate Report-
>Export->Email->Logout.

iii. E-R[Entity Relation] Diagram mainly used to represents DB


tables with their relations and multiplicity[Association
Mapping].

3. Development:- Converting design to code (or Project coding) is


called as “Development”. Here we use Spring Boot to develop the
complete project.

4
Raghu Sir [Sathya technologies, Ameerpet]

Warehouse Project Overview:-

Warehouse is a storage location of items which are purchased from mfg.


companies and sold to end-user via E-commerce application.
It is divided into 3 operations:

1. Basicor Base Operation 2.Inbound operations 3. Outbound Operations

A] Basic Operations are UOM [unit of measurement], Location Item, Vendor


and Customer, shipment Type, Order Method etc.

B] Inbound Operations: - Getting an item into warehouse is called as “Inbound


Operations”.Inbound Operations chain is PO->VI-GRN where PO
Standsfor Purchase Order, VI stands for Vendor Invoice, GRN stands
ForGoods ReceiptNote.
C] Outbound Operations:- Selling an Item to End-user via different channel is
called as “Outbound Operations”.
SO[Sale Order] ->CI[Customer Invoice] ->SHIP[Shipment].

Spring Boot:-
application.properties file:-
This file is input to spring container. Here Spring Boot provides default
configurationfor all concept i.e. <bean> tags , so programmer is not
required to write any <bean> tag for common concept like email,
Database connection, JMS, Log4J,View Resolver etc.

application. Properties must be created under “src/main/resources”.


It stores data in key=value format. Here all keys are pre-defined.
Symbol# indicates comment in properties file.
Example:- application.properties
#Server config
Server.Port = 2018
#View Resolver
spring.mvc.view.prefix = /WEB-INF/views.
spring.mvc.view.suffix = .jsp

Spring Boot Embedded Services:-


5
Raghu Sir [Sathya technologies, Ameerpet]

 Spring Boot has provided 2 Embedded (In Build) serversTomcat and


Jetty
And3 Embedded DatabasesH2, HSQLDB and Apache Derby.
 If we use above embedded services, programmer need not required to
download, install and setup of any web and DB server.
DevTools: - This service is given by spring Boot which performs Post
Development operations automatically when code changes are done in
project. DevTools will perform compile>packing>build>Deploy i.e.
.java>class>.jar>.war place in server and run.

Spring Boot and JPA Programming: -


Classes required to develop : -
1. Model Class (C): -It is a class which indicates DB Tables, design this
using >Hibernate Mapping Annotation >ValidationAnnotation
>Spring Boot Date Annotation (java.util.Date ()).
Design: -

2. Repository Interface: - Use “Crud Repository<T,ID>” which


provides all basic Database operations like save, update, delete, and
select .etc.
Here T=Model class Name, ID = Primary Key Datatype.

Design: -
Write one interface that extends CrudRepository(I).

6
Raghu Sir [Sathya technologies, Ameerpet]

HAS-A Relation: -

Using child class as DataType in parent class and creating variable is called as
“HAS-A” Relation.

Ex. Parent ------<> child

A ----------<> B

Class B{ }

Class A{

B ob; // HAS-A

7
Raghu Sir [Sathya technologies, Ameerpet]

Rest Coding with Spring Boot: -

It provides default configuration for Front Controller (servlet) i.e. Dispatcher


Servlet in web.xml by default. So, programmer not required to code this.

 Auto Conversion is given for JSON <=> Object formats by spring boot.
Just use @RequestBody before param type.
 Use @RestController at class level. Then class behaves as Rest
WebService provider class.
 Make HAS-A Relation with Repository interface (DAL) & apply
@Autowired.
 Define one operation (method) that returns ResponseEntity after
execution.
 @Valid will do model object validations and store then into Errors
object.
(Errors | BindingResult).
 @PostMapping is equals to
@RequestMapping(value=”/url”,method=RequestMethod.POST)

**Design: -

8
Raghu Sir [Sathya technologies, Ameerpet]

JSON: - (Java Script Object Notation)

It is object format in JavaScript programing.

Format: - {Key :value …}

Here Key = variable and value = data.

Key must be quoted and value will be quoted if type String.

Ex: JSON Format: {“empName”:”Smith”, “empSal”:52,”empSal”:25.36}.

Executing Application: -

1. Update Project
Right click on project
Maven
Update Project
2. Clean Project
Right Click on Project Run As Maven Clean
3. Install Project (Pack)
Right click on Project Run As Maven Install
4. Start server
Open Boot Starter class &Run as Main Method class
Run Menu -> Run Option (ctrl+F11).

9
Raghu Sir [Sathya technologies, Ameerpet]

Request Using POSTMAN: -

URLs: -

1. (GET)
http://localhost:2018/emp/getAll
2. (POST)
http://localhost:2018/emp/save

Example: - Screen#1

10
Raghu Sir [Sathya technologies, Ameerpet]

Custom Banner Generator: -

https://devops.datenkollektiv.de/banner.txt/index.html

 Create one file named as “banner.txt” under src/main/resources folder.


 Place copied content to this banner.txt file
 Run startup class.

11
Raghu Sir [Sathya technologies, Ameerpet]

Path Parameter/Path Variable: -

We can send using URL Path variable.

It is by default as String type and can be converted to other types.

Ex: http://localhost:2018/get/25

In application provide URL (Path) using { } symbols for dynamic Path.

Ex: /get/{sid} , Here /get = static path, {sid} = dynamic path using below
format:

@PathVariable(“{path}”)DataType variable

Ex: @PathVariable(“sid”) in eid

12
Raghu Sir [Sathya technologies, Ameerpet]

In application.properties add below line for “context-path” must start with


“/”

Ex: server.context-path=/provider

** default value for context-path is “/”.

In case of spring 4.x Or springBoot 1.x/2.x it provides Front controller as


“DispatcherServlet” which accept request for both PL (Presentation Layer)
and IL (Integration Layer).

**** In spring Boot it has default configuration and mapped with URL “/”

DispatcherServlet (Spring-4) = DispatcherServlet (Spring-3) + Spring


Servlet (Spring-3).

13
Raghu Sir [Sathya technologies, Ameerpet]

External DB Configuration in Spring Boot: -

We can configure database details using “dataSource” and “jpa” properties.

Here programmer not required to write code for DataSource and


SessionFactory impl class obj. These will be auto configured by spring Boot.

We should provide only input details using (key=value) application.properties


file.

**Spring Boot provides by-default “connection Pool” using Apache Tomcat


server.

With default values like init-size=10, max=100 etc.

**To see all default values for connection Pooling goto “PoolProperties” class.

(Use Ctrl+shift+t to open any class in Eclipse).

14
Raghu Sir [Sathya technologies, Ameerpet]

Application.properties: - For DataBase connection

#DataSource Details#

#spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=root

#Hibernate(JPA) Details #

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

spring.jpa.show-sql=true

spring.jpa.hibernate.ddl-auto=create

spring.jpa.properties.hibernate.format_sql=true

#Connection Pooling – Tomcat #

spring.datasource.tomcat.initial-size=5

spring.datasource.tomcat.max-active=5

spring.datasource.tomcat.max-active=20

spring.datasource.tomcat.max-idle=10

spring.datasource.tomcat.min-idle=5

15
Raghu Sir [Sathya technologies, Ameerpet]

** Add mysql dependency in pom.sql

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

**Here scope=runtime means, jar version is taken care by Parent Project.

Import.sql (src/main/resources) >right click> new > other > search for “SQL”
> select “SQL File” > enter name ex: import.sql > finish

** This file can have SQL quieries which will be executed only one time, on
server startup.

ex: SQL code in import.sql file: -

insert into emptab(eid,ename,esal,ectdat,emddat)


values(555,’admin’,9.9,now(),now())

16
Raghu Sir [Sathya technologies, Ameerpet]

SWAGGER 2.x: -

It is a third party tool provided by SpringFox to generate UI in html format


for all Rest services in our application.

It provides complete API in Simple HTML Screen,thatcontains URL’s


Operation Names, Input and Output of operations, sample Input/output
formats Provider details & contact information etc.

** This UI is called as DOCKET. To create this, we must provide,

1. api’s base-package.
2. Common Path for all RestControllers in App.
3. API Information and Contact Details are called as metadata (optional).

** It provides List of operations for Client only for Testing process.

**To see generated Docket type URL with “swagger-ui.html” as suffix.

Ex: http://localhost:2018/swagger-ui.html

We must configure as a Bean in Configuration class with below steps: -

1) create Docket with Documentation Type as SWAGGER2


2) provide selections (select() method)
3) Get the API Details with base package[like super package].
4) Provide commons path as RegExp. (format /path.*)
5) **provide API Information with contact details. (optional)
6) Build Docket.

See SpringBootRestAndCrud pdf…

17
Raghu Sir [Sathya technologies, Ameerpet]

PROJECT DESIGN: -

MaaS: - (Module as a Service)

This design provides one module as one micro service which can be
deployed with project other module or indepdently.

It accept request from any kind of client i.e. Android App, Web Browser,
Installed UI with web services (like ATM), Bulk Input process as
Excel/XML/JSON etc..

** MaaS Generic design should support, Data Validation, Data Access using
Sorting and Paging with Specification, Multi Type Data Access
(XML/JSON/Excel outputs..), Multi-Language Process
(I18n=Internationalization), Security Configuration with Role based
Authentication (Spring Boot security)

18
Raghu Sir [Sathya technologies, Ameerpet]

Jpa Repository: - It is a spring boot only interface provided to implement DB


operations with pagination and sorting process.

It supports all operations like Hibernate flow.

Ex: Joins, Dynamic Query With Named Parameter, findByVariable DataSelect.

19
Raghu Sir [Sathya technologies, Ameerpet]

Spring Boot Project Setup

1. Create Maven Project (webapp)


2. Add details in pom.xml
3. Provide key=value for Server, Datasource (Connection), Hibernate(JPA)
and
Connection Pool (Tomcat Connection Pool), ViewResolver Details in
“application.properties”.
4. Update JDK and Maven Project
5. Create one folder “views” under “webapp” > “WEB-INF”.
6. Write one SpringBoot starter class.
7. Test process, by running starter class as “Java Application”.

Coding Order: -

1. Model/Entity (C)
2. Repository (I)
3. Service (I) and ServiceImpl (C)
4. UIController (C)
5. JSP Files (Register, Data, DataEdit)
6. Validator (C) UI and ReST
7. Pagination in Data Page
8. Searching and Sorting in Data Page
9. RestController (C)
10. MultipartController
11. Validator (Multipart)
12. Utils and Specification

Basic Layers For Module Design: -

For one module we should design model class with 3 basic layer: Those are

1) Presentation Layer 2) Service Layer 3) Data Access Layer

20
Raghu Sir [Sathya technologies, Ameerpet]

21
Raghu Sir [Sathya technologies, Ameerpet]

UML Notations: -

It is used to provide design for OOP Languages.

1. Class/interface design: -

22
Raghu Sir [Sathya technologies, Ameerpet]

Example: -

Java Code is: -

package com.app;

public class Employee{

private int empId;

private String empName;

protected void show(int){..}

23
Raghu Sir [Sathya technologies, Ameerpet]

Relations Using UML Design: -

1) IS-A (Inheritance):
Use extends or implement keywordfor coding.

Coding order: parent > 1st


Child > 2nd

2) HAS-A (Composition):
Use child as DataType and create one reference variable in Parent. It is
called as HAS-A Relation.

Syntax:

Coding Order: - Child 1st Parent 2nd

24
Raghu Sir [Sathya technologies, Ameerpet]

25
Raghu Sir [Sathya technologies, Ameerpet]

Layers of Module in UML:

Employee Example:-

Equal java code is:

Package com.app.model;

Public class Employee{

Private int empId;

Package com.app.repo;

26
Raghu Sir [Sathya technologies, Ameerpet]

Public interface EmployeeRepository extends


JpaRepository<Employee,Integer>{

Package com.app.service;

Public interface IEmployeeService{…}

Package com.app.service.impl;

Public class EmployeeServiceImpl{

Private EmployeeRepository repo;

Package com.app.controller;

Public class EmployeeController{

Private IEmployeeService service;

27
Raghu Sir [Sathya technologies, Ameerpet]

Admin Example:

Equal java code is:

Package com.app.model;

Public class Admin{

Private int adminId;

Package com.app.repo;

Public interface AdminRepository extends JpaRepository<Admin,Integer>{

Package com.app.service;

Public interface IAdminService{…}

Package com.app.service.impl;

Public class AdminServiceImpl{

Private AdminRepository repo;

}
28
Raghu Sir [Sathya technologies, Ameerpet]

Package com.app.controller;

Public class AdminController{

Private IAdminService service;

29
Raghu Sir [Sathya technologies, Ameerpet]

User Module Example: -

Code Is: -

1) Model Class: -
package com.app.model;
@Entity
@Table(name=”usertab”)
public class User{
@Id
@Column(name=”u_id”)
@GeneratedValue(generator=”user_gen”)
@GenericGenerator(name=”user_gen”,strategy=”increment”)
privateLong userId;
//defConst, set/get, toString
}
2) DAL: Repository

package com.app.repo;

@Repository

Public interface UserRepository extends JpaRepository<User,Long>{

30
Raghu Sir [Sathya technologies, Ameerpet]

3) SL: IService
package com.app.service;
public interface IUserService{

}
4) SL: ServiceImpl
packagecom.app.service.impl;
@Service
public class UserServiceImpl implements IUserService{
@Autowired
privateUserRepository repo;
}
5) PL: Controller
packagecom.app.controller;
@Controller //@RestController
Public class UserController{
@Autowired
privateIUserService service; }

31
Raghu Sir [Sathya technologies, Ameerpet]

ShipmentType Example: -

Code Is: -

1) Model Class: -
package com.app.model;
@Entity
@Table(name=”shipmentTypetab”)
public class ShipmentType{
@Id
@Column(name=”shipment_id”)
@GeneratedValue(generator=”shipment_gen”)
@GenericGenerator(name=”shipment_gen”,strategy=”increment”)
private Long userId;
//defConst, set/get, toString
}
2) DAL: Repository

package com.app.repo;

@Repository

Public interface ShipmentTypeRepository extends


JpaRepository<ShipmentType,Long>{

32
Raghu Sir [Sathya technologies, Ameerpet]

3) SL: IService
package com.app.service;
public interface IShipmentTypeService{

}
4) SL: ServiceImpl
package com.app.service.impl;
@Service
public class ShipmentTypeServiceImpl implements
IShipmentTypeService{
@Autowired
privateShipmentTypeRepository repo;
}
5) PL: Controller
package com.app.controller;
@Controller //@RestController
Public class ShimentTypeController{
@Autowired
privateIShipmentTypeService service;
}

33
Raghu Sir [Sathya technologies, Ameerpet]

UOM (UnitOfMeasurment) Model Class Example: -

Code Is: -

1) Model Class: -
package com.app.model;
@Entity
@Table(name=”uomtab”)
public class Uom{
@Id
@Column(name=”uom_id”)
@GeneratedValue(generator=”uom_gen”)
@GenericGenerator(name=”uom_gen”,strategy=”increment”)
private Long uomId;
//defConst, set/get, toString
}
2) DAL: Repository

package com.app.repo;

@Repository

Public interface UomRepository extends JpaRepository<Uom,Long>{

34
Raghu Sir [Sathya technologies, Ameerpet]

3) SL: IService
package com.app.service;
public interface UomService{

}
4) SL: ServiceImpl
package com.app.service.impl;
@Service
public class UomServiceImpl implements IUomService{
@Autowired
privateUomRepository repo;
}
5) PL: Controller
package com.app.controller;
@Controller //@RestController
Public class UomController{
@Autowired
private IUomService service;
}

35
Raghu Sir [Sathya technologies, Ameerpet]

OrderMethod Module Example: -

Code Is: -

1) Model Class: -
package com.app.model;
@Entity
@Table(name=”orderMethodtab”)
public class OrderMethod{
@Id
@Column(name=”order_id”)
@GeneratedValue(generator=”order_gen”)
@GenericGenerator(name=”order_gen”,strategy=”increment”)
privateInteger orderId;
//defConst, set/get, toString
}
2) DAL: Repository

package com.app.repo;

@Repository

Public interface OrderMethodRepository extends


JpaRepository<OrderMethod,Integer>{

36
Raghu Sir [Sathya technologies, Ameerpet]

3) SL: IService
package com.app.service;
public interface OrderMethodService{

}
4) SL: ServiceImpl
package com.app.service.impl;
@Service
public class OrderMethodServiceImpl implements
IOrderMethodService{
@Autowired
privateOrderMethodRepository repo;
}

5) PL: Controller
package com.app.controller;
@Controller //@RestController
Public class OrderMethodController{
@Autowired
privateIOrderMethodService service;
}

37
Raghu Sir [Sathya technologies, Ameerpet]

A) Uom [Unit of Measurement]: -

#UI Design: -

38
Raghu Sir [Sathya technologies, Ameerpet]

Model Class Annotations and Description: -

1) @Temporal and @TemporalType: - @Temporal annotation is used to


define Date format of a Date class (java.util) class object for Both DB
storage and UI Display.
It supports 3 formats given by TemporalType enum. Those are: DATE,
TIME, TIMESTAMP.
Example values for format:
DATE: 10/02/2018
TIME: 08:36
TIMESTAMP: 10/02/2018 8:36
***Same format is stored in DB and displayed at UI (JSP Page)
Ex code:
@Temporal(TemporalType.DATE)
Private DATE dob;
**This Annotation and enum is from javax.persistency package.
2) @CreatedDate and LastModifiedDate: - These two annotations are
given from Springframework, to work with Date objects.
**On performing insert operation (save() method) both created and
Last modified dates are given by Spring F/w using server Date and
Time.Ie.values are set to object before save.
**These must be activated at Entity class using Its Listeners Ie.
AuditingEntityListener.
**These are from “org.springframework.data.annotation” package.

39
Raghu Sir [Sathya technologies, Ameerpet]

3)@GeneratedValue and @GenericGenerator: -@GeneratedValue says that


primaryKey value will be generated when performing save operations [insert
into..].

**Default generator is SEQUENCE for Oracle and AutoIncrementfor MySQL


DB.

**In our application, we are using “increment” (max+1) generator and applied
with @GenericGenerator.

4)@Entity: - Maps class with table and variables with columns.

5)@Id: - Indicates PrimaryKey.

6)@Table: - To provide table details.

7)@Column: - To provide column detail, like column name.

40
Raghu Sir [Sathya technologies, Ameerpet]

repo.save(obj) : -This method is given from spring f/w data to perform DB


operation that works like saveOrUpdate(obj).

**If Given object primary key value exist in DB table then save() works like
“update table set column..” else works like “insert into…”

41
Raghu Sir [Sathya technologies, Ameerpet]

Presentation Layer Design: -

This layer contains UI(View) and Controller files which exchanges


Model(Data).

Design: - Presentatation-Layer

Here JSTL = JSP Standard Tag Library, EL = Expression Language


${expression}

STL = Spring Tag Library.

Example: - Design-

42
Raghu Sir [Sathya technologies, Ameerpet]

Spring Form Tags: -

To design the form for input data reading, we can use HTMLform or Spring
Form Tag Library (SFTL).

If we use HTML form, then form can be converted to object and given to
controller. [one-way-binding]

If we use Spring Form Tags, form can be converted to object and same
object can be converted to form data. [Two-way-binding]

Spring form tags also supports:-

 Error Bindingto variables.


 Data parsing between input and variables.
 Dynamic UI construction from object data.
 I18N (Multi-language) using spring tag library.
 Supports Easy Integration with any CSS Technology Ex. BootStrap.

Spring Form Tags and Equal HTML Tags: -

1] <form: input path=”variable”>

Equal HTML is: <input type=”text” name=”variable” id=”variable”>

2] <form: passwordpath=”variable”>

Equal HTML is: <input type=”password” name=”variable” id=”variable”>

3] <form: select path=”variable”>

<form:option value=” ”>___</form:option>

Equal HTML is: <select name=”variable” id=”variable”>

<option value=” ”>____</option>

</select>
43
Raghu Sir [Sathya technologies, Ameerpet]

4] <form: checkbox path=”variable”/>

Equal HTML is: <input type=”checkbox” name=”varName”


id=”varName”/>

5]<form: radioButtonpath=”varName”/>

Equal HTML is: <input type=”button” name=”varName” id=”varName”/>

6] <form: hidden path=”varName”/>

Equal HTML is: <input type=”hidden” name=”varName” id=”varName”/>

44
Raghu Sir [Sathya technologies, Ameerpet]

UI and Controller to Uom: -

1)UomRegister.jsp
<%@taglibprefix="form"uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Uom Register Page</title>
</head>
<body>
<h1>Welcome to Uom Register</h1>
<form:formaction="register"method="post"modelAttribute="uom">
<pre>
Uom Type: <form:selectpath="uomType">
<form:optionvalue="">--Select--</form:option>
<form:optionvalue="PACKING">PACKING</form:option>
<form:optionvalue="NO PACKING">NO PACKING</form:option>
<form:optionvalue="NA">-NA-</form:option>
</form:select>
Uom Model: <form:inputpath="uomModel"/>
Description: <form:textareapath="description"/>
<form:errorspath="description"></form:errors>
<inputtype="submit"value="Create Uom"/>
</pre>
</form:form>
${message}
</body>
</html>

2)Controller Code: -
@Controller
@RequestMapping("/uom")
publicclass UomController {

@Autowired
private IUomService service;

/**
* 1. To Show Register Page */
@GetMapping("/register")
public String showRegister(ModelMap map) {
// Send ModelAttribute to form
map.addAttribute("uom",new Uom());
//Specify UI Page Name
return"UomRegister";
}

/**
* 2. save Data to DB */
@PostMapping("/register")
public String saveData(@ModelAttribute Uom uom,Errorserrors,ModelMapmap)

45
Raghu Sir [Sathya technologies, Ameerpet]
//Save Data to DB using service Layer
Long uomId = service.save(uom);
//Clear form (model Object) after save
map.addAttribute("uom",new Uom());
//Send Message to UI After save
map.addAttribute("message","Uom created with ID: "+ uomId);
return"UomRegister";
}
}

46
Raghu Sir [Sathya technologies, Ameerpet]

Validator Coding: -

Validator is used to verify the input data on save or update operation. Before
performing operation in controller first invoke to validator which returns
errors.

If (hasErrors()) then show errors at UI using <form:errors


path=”varName”>else perform save/update operation using IService.

Validation messages are loaded from “messages.properties”file which is


placed under src/main/resources in key=value .

Steps:

1) Write one class that implements “Validator(I)” given by spring


org.springframework.Validation.
2) Override two unimplemented methods.
3) Provide model class details in support method.
4) Check field validation using “ValidationUtils(C)” given by spring, use
“rejectXXX()” methodwith key (code), which will be loaded from
“messages.properties” file.
5) Make “HAS-A” between controller and our Validator class.
6) Call validate(model,error) before save().
7) If hasErrors() send to UI else save().
8) Display Errors at UI using <form:errors path=”varName”>

#1.messages.properties
uom.reg.type.error=Select one UomType
uom.reg.model.error=Enter Uom Model
uom.reg.desc.error=Enter Description

#2.UomValidator class
publicclassUomValidatorimplements Validator {

@Override
publicboolean supports(Class<?>clazz) {
returnUom.class.equals(clazz);

47
Raghu Sir [Sathya technologies, Ameerpet]
}
@Override
publicvoid validate(Object target, Errors errors) {

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "uomType", "uom.reg.type.error");


ValidationUtils.rejectIfEmptyOrWhitespace(errors, "uomModel","uom.reg.model.error");
ValidationUtils.rejectIfEmptyOrWhitespace(errors,"description","uom.reg.desc.error");
}
}

#3.UomController (Code to be added modified)


@Autowired
privateUomValidatorvalidator;

/**
* 2. save Data to DB */
@PostMapping("/register")
public String saveData(@ModelAttribute Uom uom,Errorserrors,ModelMapmap) {
// Before save do validation
validator.validate(uom, errors);
if(!errors.hasErrors()) {
//if no errors
//Save Data to DB using service Layer
Long uomId = service.save(uom);
//Clear form (model Object) after save
map.addAttribute("uom",new Uom());
//Send Message to UI After save
map.addAttribute("message","Uom created with ID: "+ uomId);
}
return"UomRegister";
}

#4.In UomRegister.jsp display errors using:

<form:errors path=”uomType”/>

<form:errors path=”uomModel”/>

<form:errors path=”description”/>
48
Raghu Sir [Sathya technologies, Ameerpet]

Fetching All rows From DB table: -

49
Raghu Sir [Sathya technologies, Ameerpet]

Here, use JpaRepositoryfindAll() method which executes “select (*)count from


<table>” and gets data in List<T> (T=model class) ( one row in DB table=one
Object in List ).

This List display at UI using JSTL <forEach/> tag also use EL  “${key}”in
HTML Table format.

In Controller define one method to get List from Service Layer. We can sort
based on any variable using comparator (I) also.

#1 Anonymous Inner class Syntax:

(Nameless class and Nameless object) new <interfaceName>(){

// override all methods …

Ex: interface Comparator <T> {

int compare(T a1, T a2);

#Anonymous Code:

50
Raghu Sir [Sathya technologies, Ameerpet]

new Comparator<Uom> (){

public int compare (Uom o1, Uom o2){

return…(logic here);

Display List Using forEach loop: -

Java code:

List<Uom> uomList=….

for(Uom uom: uomList){ Sysout (uom); }

JSTL Code:

<c: forEach items=”$uomList” var=”uom”>

<c:out value=”${uom}”>

</c:forEach>

Code#1-Add method in UomService

public List<Uom> getAll();

Code#2-Add Unimlemented method in UomServiceImpl

public List<Uom> getAll() {

List<Uom> uomList=repo.findAll();

Collections.sort(uomList,new Comparator<Uom>() {

@Override

51
Raghu Sir [Sathya technologies, Ameerpet]

public int compare(Uom o1, Uom o2) {

return
o1.getUomModel().compareToIgnoreCase(o2.getUomModel());

}//method

}); //anonymous Inner class

return uomList;

}//method

52
Raghu Sir [Sathya technologies, Ameerpet]

Code#3-Add below method in UomController

* 3.show All Uom Records */

@GetMapping("/all")

public String getAll(ModelMap map) {

map.addAttribute("uomList", service.getAll());

return "UomData";

Code#4-Create “UomData.jsp” in views folder

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>UomData Page</title>

</head>

<body>

<h1>Welcome To UomData</h1>

<table border="1">

<tr>

<th>ID</th>

53
Raghu Sir [Sathya technologies, Ameerpet]

<th>Type</th>

<th>MODEL</th>

<th>DESC</th>

<th>CREATED</th>

<th>MODIFIED</th>

</tr>

<c:forEach items="${uomList}" var="uom">

<tr>

<td><c:out value="${uom.uomId}" /></td>

<td><c:out value="${uom.uomType}" /></td>

<td><c:out value="${uom.uomModel}" /></td>

<td><c:out value="${uom.description}" /></td>

<td><c:out value="${uom.createdOn}" /></td>

<td><c:out value="${uom.modifiedOn}" /></td>

</tr>

</c:forEach>

</table>

</body>

</html>

54
Raghu Sir [Sathya technologies, Ameerpet]

Code#5-Add below line at UomController

Class level

@RequestMapping(“/uom”)

@Controller

Public class UomController{……..}

55
Raghu Sir [Sathya technologies, Ameerpet]

Delete Record By Primary Key (Uom): -

#1.Create one Hyperlink using static Path and Dynamic


Path(URLRewriting).

That looks as below: -

<a href=”delete?uomId=${uom.uomId}”>DELETE</a>

#2.Add abovecode in UomData.jsp under <c:forEach> as a <td> at last looks as

<tr>

<c:forEach items=…>

<td><a href=”delete?uomId=${uom.uomId}”>DELETE</a></td>

</tr>

</c:forEach>

#3. Add belowmethod in UomController

//4.Detele one uom by Id

@GetMapping(“/delete”)

publicString delete(@RequestParam long uomId)

service.delete(uomId);

return “redirect:all”;

Control Flow: -
56
Raghu Sir [Sathya technologies, Ameerpet]

UomData.jsp

<html>

<head>………

<link rel=”stylesheet” href=”../bootstrap/css/bootstrap.min.css”/>

<link rel=”stylesheet” href=”../bootstrap/css/bootstrap-grid.min.css”/>

<script type=”text/javascript”
src=”../bootstrap/js/bootstrap.bundle.min.js”/>

<script type=”text/javascript” src=”../bootstrap/js/bootstrap.min.js”/>

<script type=”text/javascript” src=”../bootstrap/js/jquery-3.2.1.slim.min.js”/>

<script type=”text/javascript” src=”../bootstrap/js/popper.min.js”/>

</head>

<div class=”container”>

<div class=”card”>

<div class=”card-header bg-primary text-white”>

<h2>WELCOME TO UOM DATA PAGE</h2>

</div><!-- CARD HEAD END -->

57
Raghu Sir [Sathya technologies, Ameerpet]

<div class=”card-body”>

<table class=”table table-hover”>

<trclass=”thead-dark”>

..ID, TYPE, MODEL, DATES, DESC, LINKS.

</tr>

<c:forEach …> . . . . </c:forEach>

</table>

</div><!-- CARD BODY END -->

<div class=”card-footer bg-secondary text-white”>

<h3> PAGINATION UNDER CONSTRUCTION </h3>

</div><!-- CARD END -->

</div><!—Container End -->

</body>

</html>

Code:-

58
Raghu Sir [Sathya technologies, Ameerpet]

UomRegister.jsp

<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>

<html><head>…...</head><body>

<div class=”container”>

<div class=”card”>

<div class=”card-headerbg-primary text-white”>

<h2>WELCOME TO UOM REGISTER PAGE </h2>

</div>

<div class=”card-body”>

<form:form action=”…” modelAttribute=…>

<div class=”form-group”>

<label for=”uomType” class=”control-label col-sm-4>UOM Type </label>

<form:select path=”uomType” cssClass=”form-control col-sm-4”>

<form:option value=””>--Select--</form:option>

//PACKING, No-PACKING, NA…</form:select>

<form:errors path=”uomType” cssClass=”text-danger”/>

</div>

<div class=”form-group”>

<label for=”uomModel” class=”control-label col-sm-4”>UOM Model</label>

<form:input path=”uomModel” cssClass=”form-control col-sm-4”/>

<form:errors path=”uomModel” cssClass=”text-danger”/>

</div>

59
Raghu Sir [Sathya technologies, Ameerpet]

<div class=”form-group”>

<label for=”description” class=”control-label col-sm-4”>Description</label>

<form:textarea path=”description” cssClass=”form-control col-sm-4”/>

<form:errors path=”description” cssClass=”text-danger”/>

</div>

<input type=”submit” value=”Create UOM” class=”btnbtn-success”/>

</form:form>

</div><!—CARD BODY END -->

<c:if test=”${null!=message}”>

<div class=”card-footer bg-success text-white”><b>${message}</b>

</div><!—CARD FOOTER END -->

</c:if>

</div><!—CARD END -->

</div><!—Container END -->

</body>

</html>

UomDataEdit Design: -

60
Raghu Sir [Sathya technologies, Ameerpet]

#1: In UomData.jsp, add below line inside forEach

<td><a href=”edit?uomId=${uom.uomId}” class=”btnbtn-info”>EDIT</a>

#2: Add two methods in UomController

//5. Show Uom Edit Page

@GetMapping(“/edit”)

Public String edit(@RequestParam Long uomId, ModelMap map){

Uom uom = service.getOne(uomId);

map.addAtribute(“uom”,uom);

return “UomDataEdit”;

//6. Update Uom Data to DB

@PostMapping(“/update”)

Public String update(@ModelAttribute Uom uom){

service.update(uom);

61
Raghu Sir [Sathya technologies, Ameerpet]

return “redirect:all”;

UomDataEdit.jsp

<%@taglib prefix=”form” uri=”http://www.sf.org/tags/form” %>

<html><head>…<head>

<body>……….

<form:form action=”update” method=”post” modelAttribute=”uom”>

<pre>

Uom Id: <form:input path=”uomId” readonly=”true”/>

Uom Type: <form:select path=”uomType”>

<form:option value=””>--select--</form:option>

<form:option value=”PACKING”>PACKING</form:option>

<form:option value=”NO PACKING”>NO PACKING</form:option>

<form:option value=”NA”>-NA-</form:option>

</form:select>

Uom Model: <form:input path=”uomModel”/>

Description: <form:textarea path=”description”/>

<input type=”submit” value=”Update UOM”/>

</pre></form:form></body></html>

Warehouse Project Flow: -

62
Raghu Sir [Sathya technologies, Ameerpet]

This project has 3 types of Operations.

i. Basic operations also called as “Basic Modules”.

Here Basic Modules are


a. Unit of Measurement (UOM)
b. Shipment Type
c. Order Method
d. WHUserType (Vendor & Customer)
e. Item

These modules are used in Inbound and Outbound operations.

ii. Inbound operations:


These operations are used to perform “getting an Item into warehouse
Location”. It is a combination of 3 modules.
a. Purchase Order (PO)
b. Vendor Invoice (VI) [PDF]
c. Goods Receive Note (GRN)

iii. Outbound operations:

63
Raghu Sir [Sathya technologies, Ameerpet]

These operations are used to all sell an item to customer [End Customer,
A shop, Online Service]. These module are:
a. Sales order
b. Customer Invoice
c. Shipping SHP

Dynamic UI Construction Using Spring Form Tags: -


64
Raghu Sir [Sathya technologies, Ameerpet]

A List created in Util (C) or Created from DB (using SL and DAL) can be sent to
UI which can be shown as: . Drop Down options 2.Radio Buttons 3.Check
BoxesNo.of values in List will be shown as No. of Options.

Example Flow Design is:

Step 1: Util Class Creation:

I. Create one util class and apply @Component at class level.


II. Add one method that returns List type.
III. Create List object which must be converted to UI Component at JSP.

Step 2: Controller Code:

I. Make HAS-A Between Controller and Util Controller is Parent and Utils
is child Controller ---------<> Util
II. Add map.attribute(__,__) line in Controller methods that returns
__Register or __DataEdit

Step 3: UI Code:

I. Use #key provided in ModelMap and consider that as items key.


II. Select one UI Component and apply key as items.

65
Raghu Sir [Sathya technologies, Ameerpet]

Code: 1#: UomUtil.java

packagecom.ramssoft.BootApp.util;

@Component

public class UomList {

public List<String> getUomTypes(){

return Arrays.asList(“PACKING”,”NO PACKING”,”—NA--”);

/*List<String> list = new ArrayList<String>();

list.add(“PACKING”); list.add(“NO PACKING”); list.add(“—NA--”);

return list; */

Code: 2#:In UomController.java

@Controller

Public class UomController{

….

@Autowired

Private UomUtil util;

(In showRegister(),saveData(),edit() update these methods add below line


before return stmt )

map.addAttribute(“uomTypes”,util.getUomTypes());

66
Raghu Sir [Sathya technologies, Ameerpet]

Code: 3#: In UomRegister.jsp and UomDataEdit.jsp remove <form:option


value=””> tags, for 3 options “PACKING”, “NO PACKING”, and “NA” and replace
with below line:

<form:options items=”${uomTypes}”/>

67
Raghu Sir [Sathya technologies, Ameerpet]

Implementing ReST WebServices in Application: -

Spring Boot support default configuration for “ReST Web Services” also called
as “AutoConfiguration” of “FrontController” mapped to “/”.

Here FC is “DispatcherServlet”.

Our warehouse application can be integrated to 3rd party application using


ReST Web Services.

Like Vendors = small Scale and Medium Scale applications, Factory Outlets,
etc.

Customer = E-Commerce (Flipkart, Amazon) and VDM (Vendor-Data


Management-controllers) etc.

ReSTController supports Data conversion in JSON (Java Script Object


Notation).

Using @RequestBody and #ResponseBody JSON Conversions are done.

Here ReST Controller makes HAS-A with IService, Util, Validator.

68
Raghu Sir [Sathya technologies, Ameerpet]

Uom Rest Controller: -

Use @RestController at class level, so that class behaves like Rest Web
Service which can make relations (HAS-A) with IService and Validator.

Format of Rest Controller with basic method:

@RestController

publicclass _________{

@GetMapping(“/url”) // OR

@PostMapping(“/url”)

publicResponseEntity<?> ______(…){

return ResponseEntity;

UomRestController Code:-

Package com.ramssoft.BootApp.rest;

@RestController

@RequestMapping(“/rest/uom”)

public class UomRestController{

//HAS-A with IService, Validator

@Autowired

private IUomService service;


69
Raghu Sir [Sathya technologies, Ameerpet]

@Autowired

privateUomValidator validator;

//1) save Uom Data

@PostMapping(“/save”)

Public ResponseEntity<?>save(@RequestBody Uom uom,Errors


errors){

Validator.validate(uom,errors);

if(errors.hasErrors()){

returnResponseEntity.badRequest().body(errors.getAllErrors());

}else{

Long uomId = service.save(uom);

return ResponseEntity.ok(“Uom Created With Id:”+uomId);

}//method

}//class

PostManScreenShotFor Request:

70
Raghu Sir [Sathya technologies, Ameerpet]

Selecting One OR All Records: -

71
Raghu Sir [Sathya technologies, Ameerpet]

While Implementing web services operations we must choose method types


based on operation type.Few examples are given below:

**) Uom Rest Controller operations

// 2. Get All records

@GetMapping(“/all”)

publicResponseEntity<Object> getAll(){

Object response=null;

List<Uom> uomList = service.getAll();

If(uomList==null || uomList.size()==0){

response = “No Uom Records Exists.”;

}else{

response = uomList;

return ResponseEntity.ok(response);

//3. U pdate operation


72
Raghu Sir [Sathya technologies, Ameerpet]

@PutMapping(“/update”)

public ResponseEntity<Object> update(@RequestBody Uom uom,Errors


errors){

Object response = null;

validator.validate(uom, errors);

if(errors.hasErrors()){

response=errors.getAllErrors();

returnResponseEntity.badRequest().body(response);

}else{

service.update(uom);

response=”Uom updated with Id:”+uom.getUomId();

returnReponseEntity.ok(response);

POSTMAN SCREEN: -

73
Raghu Sir [Sathya technologies, Ameerpet]

Reading A Parameter/Variable in Spring: -

74
Raghu Sir [Sathya technologies, Ameerpet]

To read one value from URL(request) in case of

1-UI (JSP) Controller go for Query Parameter also called as RequestParam


in Spring.

If URL looks like,

…/rest/uom/delete?uomId=6

Then code to read in Controller “@RequestParam Long uomId”

2-If we are using ReST Controller, then go for Path Parameter also called as
“PathVariable in Spring”.

If URL looks like,

…/rest/uom/delete/6

Then code to read to Controller, “@PathVariable Long uomId”

***Implementing Delete Operation in UomRestController: -

#1.Add below method in IUomService

publicboolean isExist(Long uomId);

#2.Implement in UomServiceImpl using repo

publicboolean isExist(Long uomId){

returnrepo.exists(uomId);

#3.Add below method in UomRestController

@DeleteMapping(“/delete/{uomId}”)

publicResponseEntity<Object>delete(@PathVariable Long uomId){

Object response = null;

boolean exist = service.isExist(uomId);

75
Raghu Sir [Sathya technologies, Ameerpet]

if(!exist){

response = “Uom ‘”+uomId”’ not exist”;

}else{

service.delete(uomId);

response = “Uom ‘”+uomId”’ is deleted”;

returnResponseEntity.ok(response);

POSTMAN SCREEN: -

DELETE ^ http://localhost:2018/uom/delete/6 Send

SWAGGER WITH SPRING BOOT: -

76
Raghu Sir [Sathya technologies, Ameerpet]

Swagger is a 3rd party API, given by “Spring Fox”. It is used to generate HTML
UI for all our webservices, that contains,

1. Service Provider URLs, Inputs (Parameters), Outputs,


MediaType(XML/JSON),MethodType(GET/POST/DELETE/PUT),etc.

2.It is also works like tool, to make request and to see response.

3.It provides sample inputs, sample outputs input dataTypes etc..

**Swagger is used create UI for all webservices in application.

Steps:-

77
Raghu Sir [Sathya technologies, Ameerpet]

1.Configure one Docket with DocumentationType as SWAGGER 2.x

2.specify select operations (select() method)

3.Provideapiswith basePackages

4.Providerpaths with regex format

5.Build Docket and return

6.(optional) Provide apiInfo like Provider name, Title, Contact, URL, Email
Licence details etc.

7.start application and type url end as “swagger-ui.html”

Ex: http:localhost:2018/swagger-ui.html

Coding: -

78
Raghu Sir [Sathya technologies, Ameerpet]

1. Add below dependencies in pom.xml file

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.6.1</version>

<scope>compile</scope>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.6.1</version>

<scope>compile</scope>

</dependency>

2. create a Swagger Configuration class

Package com.ramssoft.app.config;

@Configuration

@EnableSwagger2

Public class SwaggerConfig{

@Bean

79
Raghu Sir [Sathya technologies, Ameerpet]

Public Docket productApi(){

return new Docket(DocumentationType.SWAGGER_2)

.select()

.apis(RequestHandlerSelectors.basePackages(“com.ramssoft.app.rest”))

.paths(PathSelectors.regex(“/rest.*”))

.build();

PAGINATION: -

80
Raghu Sir [Sathya technologies, Ameerpet]

To display data on UI [Screen] step by step few records (instead of displaying


all) we use Pagination.

It will not load all DB rows at a time. It selects rows with limit. Ex size = 10.

It improves performance by using memory and execution time properly.

It displays the data in readable format to end user and search can be done
easy.

PAGINATION USING SPRING BOOT: -

Pagination Implementation: -

tr =Total Row in DB Table

ps = page Size

np = no of pages = tr/ps + (tr%ps>0?1:0)

Page number starts with zero (0) ends with np-1 or n-1.

Ex: tr = 35 , ps = 10

np = no of pages = 35/10 + 35%10 > 0 ? 1 : 0

= 3 + 5 >0 ?1 : 0

=3+1

= 4.

PAGINATION API IN SPRING BOOT: -

81
Raghu Sir [Sathya technologies, Ameerpet]

API Files are: - Page (I), Slice(I), @PageableDefault and Pageable(I).

-------------Methods In Slice and Page--------------------

getTotalPages(): returns total pages (tr).

getNumber(): return current page number

getContent(): Data in List<T>

isFirst(): true if current page is first page

hasNext(): true if next page exist

hasPrevious(): true if previous page exist.

PAGINATION DESIGN USING SPRING BOOT: -

82
Raghu Sir [Sathya technologies, Ameerpet]

Code For UOM module: -

1]Add below method in IUomService.java

public Page<Uom> findAll(Pageable p);

83
Raghu Sir [Sathya technologies, Ameerpet]

2]Implement above method in UomServiceImpl.java

Public Page<Uom> (Pageable p) {

returnrepo.findAll(p);

3]Add below code in UomController.java

(*** remove getAllRecords method in controller and write below method)

@GetMapping(“/all”)

Public String getAllRecords(@PageableDefault(size=4,sort=”uomId”,

direction=Direction.DESC)Pageable p, ModelMap map ){

Page<Uom> p = service.findAll(pageable);

map.addAttribute(“page”,page);

return “UomData”;

4]Add below code in UomData.jsp

(Under card Footer)

<div class=”card-footer text-white”>

<ul class=”pagination”>

<c:if test=”${!page.isFirst()}”>

<li class=”page-item”>

<a class=”page-link” href=”?page=0”>First</a></li>

</c:if>

<c:if test=”${page.hasNext()}”>

84
Raghu Sir [Sathya technologies, Ameerpet]

<li class=”page-item”>

<a class=”page-link” href=”?page=${page.getNumber()+1}”>Next</a></li>

</c:if>

<c:forEach begin=”0” end=”${page.getTotalPages()-1}” var=”i”>

<li class=”page-item”>

<a class=”page-link” href=”?page=${i}”>${i+1}</a></li>

</c:forEach>

<c:if test=”${page.hasPrevoius()}”>

<li class=”page-item”>

<a class=”page-link” href=”?page=${page.getNumber()-


1}”>Previous</a></li>

</c:if>

<c:if test=”${!page.isLast()}”>

<li class=”page-item”>

<a class=”page-link” href=”?page=${page.getTotalPages()-


1}”>Last</a></li>

</c:if>

</ul>

</div>

***Also modify in UomData.jsp

From: <c:forEach items=”${uomList}…”>

To: <c:forEach items=”${page.getContent()}….”>

85
Raghu Sir [Sathya technologies, Ameerpet]

*** choose –when – otherwise

When test=”${page.getNumber() eq i}”

Then add active in class

<li class=”page-item active”>

<a class=”page-link” href=#>${i+1}</a></li>

contains() check in Collections: -

contains(element):boolean

86
Raghu Sir [Sathya technologies, Ameerpet]

This method is used to check given input (element) exist in collection or not?

If exist returns true, else returns false.

Example: -

String str = “A”;

List<String> al = Arrays.asList(“A”,”B”,”C”,”D”);

boolean exist = al.containes(str);

Sysout(exist);

Pattern Check For Given String: -

A Pattern provides format of input String , it checks given String is following


given format or Not? By using “Pattern API”, also called as “Regular
Expression API”.

Example: -

87
Raghu Sir [Sathya technologies, Ameerpet]

String input = “HEHEHE”;

//1.Create one pattern

Pattern p = Pattern.compile(“[A-Z]{4,8}”);

//2.Add Matcher to Pattern

Matcher m = p.matcher(input);

//3.Execute Matcher

Boolean b = m.matches();

Sysout(b);-java.util.regex;

Sysout(Pattern.compile(“[A-Z]{4,8}”).matcher(“RAM”).matches());

Examples Patterns: -

\d  only numbers are accepted.

\D  only non-numeric are accepted.

[ ]  specific chars are accepted.

*- min=0 max= no limit(n)

+ min=1 max = n

? min=0 max = 1

{4}  exactly 4

{4,}  min=4, max=n

{4,6}  min=4, max=6 chars accepted

\w  any word [a-zA-Z_0-9] are accepted

Example: - [a-z]*

Inputs: ram(valid)

88
Raghu Sir [Sathya technologies, Ameerpet]

rahim(valid) Ajay(invalid)

HELLO(invalid) 98653(Invalid)

Ex: [a-zA-Z]{4,}

rahim(valid) Ajay(Invalid)

HELLO(Valid) 98653(Invalid)

Ex: [0-9]{4,8}

rahim(invalid) Ajay(invalid)

HELLO(invalid) 98653(Valid)

Uom Validations (Advanced): -

Code:

#1 Add below method in UomRepository(I)

@Query(“select count(uomId) from com.ramssoft.app.model.Uom where


uomTypes=?1 and uomModel=?2”)
89
Raghu Sir [Sathya technologies, Ameerpet]

public long countUomTypeAndModel(String uomTypes,String uomModel);

#2 Add below method in IUomService(I)

public boolean isUomTypeAndModelExist(String uomTypes,String


uomModel);

#3 Implement method in UomServiceImpl(C)

public boolean isUomTypeAndModelExist(String uomTypes,String


uomModel){

long count = repo.countUomTypeAndModel(uomType,uomModel);

if(count==0) return false;

else return true;

#4 UomValidator (new Code)

packagecom.ramssoft.app.validator;

@Component

public class UomValidator implements Validator{

@Autowired

private UomUtil uomUtil;

@Autowired

private IUomService uomService;

@Override

Public boolean supports(Class<?> clazz){

returnUom.class.equals(clazz);

90
Raghu Sir [Sathya technologies, Ameerpet]

@Override

public void validate(Object target,Errors errors){

Uom uom = (Uom)target;

if(!uomUtil.getUomTypes.contains(uom.getUomTypes)){

errors.rejectValue(“uomType”,””,”Please choose valid Uom


Type”);

If(!Pattern.compile(“[A-
Z]{4,8}”).matcher(uom.getUomModel()).matches()){

errors.rejectValue(“uomModel”,””,”Enter 4-8 Uppercase letters only”);

If(!Pattern.compile(“[a-zA-Z]{10-
255}”).matcher(uom.getDescription()).matches()){

errors.rejectValue(“description”,””,”Chars only 10-255 accepted”);

If(uomService.isUomTypeAndModelExist(uom.getUomType(),uom.getU
omModel)){

errors.rejectValue(“uomModel”,””,”Uom ‘”+uom.getUomModel()+”’with
‘”+uom.getUomType()+”’ exist ”);} } }

Multipart Controller: -

This controller is used to work with Bulk Operations (Export/Import Huge


Data).

It will get Request from a File [Excel File] having extension .xlsx.

In Excel One row = In Our App One Object = In DB Table one Row.

91
Raghu Sir [Sathya technologies, Ameerpet]

Spring Boot Provides default Configurations File Bulk Operations using


Multipart Controller.

Spring Boot Supports saving bulk Objects using repo.save (List<T>).

By default Multipart is enabled is spring.

One File = MultipartFile

Apache POI Excel Design: -

One Excel File = 1 work-Book

One Book contains = multiple sheets

Every Sheet is identified using = unique Name

Sheet Contains = rows start from zero

Every Row contains = cells start from zero

92
Raghu Sir [Sathya technologies, Ameerpet]

Add Below details in pom.xml

#1] pom.xml-> dependency

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi.ooxml</artifactId>

<version>3.9</version>

</dependency>

#2] application.properties

# Multipart Details #

spring.http.multipart.max-file-size=10MB

spring.http.multipart.max-request-size=20MB

93
Raghu Sir [Sathya technologies, Ameerpet]

Converting Excel Data to DB Data: -

#1. Load .xlsx file from System into MultipartFile format.

#2. Use “getInputStream()” method and convert .xlsx data into WorkBook
(XSSFWorkBook).

#3. Read Sheet from WorkBook using SheetName (XSSFSheet)

#4. Use “iterator()” to get one by one row from sheet.

#5. Skip row zero

#6. Convert Row to Uom object using Uom Param const.

#7. Add this object to one List. (ArrayList<Uom>)

#8. Return List to Controller and save List using service method.

Internal Flow: -

Coding:

#1. Add one 3-parameterised constructor in Uom.java file.

94
Raghu Sir [Sathya technologies, Ameerpet]

public Uom(String uomTypes,String uomModel,String description){

this.uomType = uomType;

this.uomModel=uomModel;

this.description=description;

#2.Add below method in IUomService to save list of Uoms

public void save(List<Uom> uoms);

#3. Implement this method in UomServiceImpl

public void save(List<Uom> uom) ){ repo.save(uoms);}

#4. Define One method in UomUtil to convert MultipartFile to List<Uom>

public List<Uom> processMultipart(MultipartFile uomFile){

List<Uom> uomList = null;

if(uomFile!=null){

try{

uomList = new ArrayList<Uom>();

InputStream is = uomFile.getInputStream();

XSSFWorkBook book = new XSSFWorkBook(is);

XSSFSheet sheet = book.getSheet(“uoms”);

Iterator<Row> rows = sheet.iterator();

while(rows.hasNext()){

Row row = rows.next();

if(row.getRowNum()==0) continue;

95
Raghu Sir [Sathya technologies, Ameerpet]

Uom uom = new Uom(

row.getCell(0).getStringCellValue(),

row.getCell(1).getStringCellValue(),

row.getCell(2).getStringCellValue(),

);

uomList.add(uom);

}// while loop end

}catch(IOException e){Sysout(e);}

}//if end

return uomList;

}//method end

#5 Create one class MultipartController for Uom Multipart Process

package com.ramssoft.app.controller.multipart;

@Controller

@RequestMapping(“/uommultipart”)

public class UomMultipartController {

@Autowired

private UomUtil util;

@Autowired

private IUomService service;

//1. To show Uom Multipart JSP Page

@GetMapping(“/show”)

96
Raghu Sir [Sathya technologies, Ameerpet]

public String showMultipartPage(){

Return “UomMultipart”;

//2. On click Import Button

@PostMapping(“/uomImport”)

Public String importUoms(@RequestParam MultipartFile


uomFile,ModelMap map){

List<Uom> uomList = util.processMultipart(uomFile);

if(uomList.isEmpty()){

map.addAttribute(“message”,”No rows found”);

}else{

service.save(uomList);

map.addAttribute(“message”,”Success”);

return “UomMultipart”;

}//controller end

#6. Create Jsp File: UomMultipart.jsp

<html><body><h1>Uom Bulk Upload/Download Screen</h1>

<form action=”uomImport” method=”post” enctype=”multipart/form-data”>

<pre>Screen File:<input type=”file” name=”uomFile”/>

<input type=”submit” value=”Import UOMs”>

</pre></form>${message} </body></html>
97
Raghu Sir [Sathya technologies, Ameerpet]

Execution:

#1 Start Application

#2 Enter URL like (in Browser)

http://localhost:2018/uommultipart/show

#3 Create one excel file with any name but Sheet name must be “uoms”

Hint: double click to modify sheet Name

#4 Enter few rows in Excel Sheet

Example

#5 Upload Sheet in Application

#6 Typehttp://localhost:2018/uom/all

And view uploaded rows

Multipart Validator For Uom Upload: -

This validator is designed to check errors in uploaded Excel Sheet. That is


works on List<Uom> objects.

98
Raghu Sir [Sathya technologies, Ameerpet]

It returns Error (if exist) in “Map<String,List<String>>”.

Example Map looks like:

Code: #1)UomMultipart Validator: -

Package com.app.controller.multipart.validator;

@Component

public class UomMultipartValidator{

@Autowired

99
Raghu Sir [Sathya technologies, Ameerpet]

private UomUtil util;

@Autowired

private IUomService service;

public Map<String,List<String>> validateUoms(List<Uom> uoms){

Map<String,List<String>> errorsMap = new


LinkedHashMap<String,List<String>>();

int i = 1;

for(Uom uom:uoms){

List<String>errorsList = new ArrayList<String>();

//check one by one obj

if(StringUtils.isEmpty(uom.getUomType())){

errorsList.add(“Uom Type cannot be empty”);

}else if(!util.getUomTypes.contains(uom.getUomType())){

errorsList.add(“Uom Type must be one `


of:”+util.getUomTypes().toString());

if(StringUtils.isEmpty(uom.getUomModel())){

errorsList.add(“Uom Model cannot be empty”);

}else if(!Pattern.compile(“[A-
Z]{4,8}”).matcher(uom.getUomModel()).matches()){

errorsList.add(“UomModel must be 4-8 Uppercase Letters only”);

}if(StringUtils.isEmpty(uom.getDescription())){

errorsList.add(“Description cannot be empty”);

100
Raghu Sir [Sathya technologies, Ameerpet]

} else if(!Pattern.compile(“[a-zA-
Z]{10,255}”).matcher(uom.getDescription()).matches()){

errorsList.add(“Description must be 10-255 Chars only”);

}if(service.isUomTypeAndModelExist(uom.getUomType(),uom.getUom
Model())){

errorsList.add(“Uom ‘”+uom.getUomModel()+”’ already exist with Type


‘”+uom.getUomType()+”’ ”);

}if(!errorsList.isEmpty()){

errorsMap.put(“Errors at Row# ”+i,errorsList);

i++;

return errorsMap;

#2 UomMultipart Controller: replace code of “importUoms method” with


given one. (delete old logic and write this)

*** Here make HAS-A relation between

UomMultipartController ---<> UomMultipartValidator

@PostMapping(“/uomimport”)

public String importUoms(@RequestParam MultipartFile uomFile,ModelMap


map){

//check uploaded one is valid file ?

if(uomFile==null || !uomFile.getOriginalFilename().contains(“.xlsx”)){

101
Raghu Sir [Sathya technologies, Ameerpet]

map.addAttribute(“message”,”Invalid File”);

}else{

List<Uom> uomList = util.processMultipart(uomFile);

if(uomList.isEmpty()){

map.addAttribute(“message”,”No rows found in sheet”);

}else{

Map<String,List<String>>errorMap =
validator.validateUoms(uomList);

if(errorMap.isEmpty()){

service.save(uomList);

map.addAttribute(“message”,”Success”);

}else{

map.addAttribute(“errorsMap”,errorMap);

return “UomMultipart”;

#3 Add below Code in UomMultipart.jsp

<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>

……..(after <form> tag closed)

<c:if test=”${!empty message}”>

<c:out value=”${message}”>
102
Raghu Sir [Sathya technologies, Ameerpet]

</c:if>

<c:if test=${!empty errorsMap}>

<table border=”1”>

<tr>

<th>#</th>

<th>Errors</th>

</tr>

<c:forEach items=”${errorsMap}” var=”e”>

<tr>

<td><c:out value=”${e.key}”></td>

<td><c:out value=”${e.value}”></td>

</tr>

</c:forEach>

</table>

</c:if>

</body>

</html>

103
Raghu Sir [Sathya technologies, Ameerpet]

Specification in Spring Boot: -

In Spring Boot Data JPA, Specification is a process of constructing one select


query with Predicate.

Specification always returns (generates) one select SQL. Example looks like

*) Specification in short called as “Spec”.

Specification generates Query at runtime with or without where clause, based


on input provided by End User.

One Spec = 1 select query + 1 Predicate

One Predicate = 1 where clause with conditions or

one Predicate = multiple expressions

One expressions = one conditions.

104
Raghu Sir [Sathya technologies, Ameerpet]

UomSpecification Design: -

Construct one Search screen (looks like Registration Form) in UomData.jsp

#2 On click Search button, after entering details Form should be Converted to


ModelAttribute and given to Uomcontroller.

Ex: Model Attribute looks like:

#3 Define one class that implements “Specification<T>” interface. Also


override “toPredicate():Predicate” method.

#4 This Impl Spec object return to controller and pass in findAll/getAll


method as 1stparam along with Pageable object as 2ndparam.

Like, Page<Uom> uoms = service.getAll(spec,pageable);

#5 Service is call repository findAll(spec,pageable). But this method is not in


JpaRepository, which is available in “JpaSpecificationExecutor<T>”.

105
Raghu Sir [Sathya technologies, Ameerpet]

So, our UomRepository interface should also extends


“JpaSpecificationExecutor<T>” interface.

#6 findAll(spec,pageable) returns matching record as a Page<T>. This data


must be returned to UI using ModelMap in Controller.

106
Raghu Sir [Sathya technologies, Ameerpet]

Specification Steps: -

#1 In DAL, UomRepo should extends JpaSpecificationExecutor<Uom>

#2 Define one method in IUomService and Implement in UomServiceImpl


,which has spec and pageable params.

public Page<Uom> findAll(Specification<Uom> spec,Pageable pageable);

#3 write one new class UomSpecification that should extends one interface
Specification<Uom> and override toPredicate():Predicate method

Public class UomSpecification implements Specification<Uom>{

……..

#4 Modify “getAll” or “all” mapped method in UomController for


Specifications also call service.findAll(spec,pageable).

#5 Define one Search (Spring Form) Screen in UomData.jsp also add <script>
given in document.

#6 Modify pagination code lines as below:

EX#1:

(From:)

<a href=”?page=0”..>First</a>

(To:)

<a href=”#” onclick=”setParam(‘page’,0)”>First</a>

EX#2:

From:

<a href=”?page=${page.getNumber()-1}”..>${i}</a>
107
Raghu Sir [Sathya technologies, Ameerpet]

To:

<a href=”#” onclick=”setParam(‘page’, page.getNumber()-1)”> ${i}</a>

108
Raghu Sir [Sathya technologies, Ameerpet]

Bug: -

It is a problem in application, it can be a logical problem or may be exception.

Debug: -

Executing code step by step (block by block) to find problems in application is


called as “Debug”.

To do debug, Eclipse should be changed to “Debug” perspective.

Eclipse ShortCuts: -

Key Description

F5 Step into (Go inside method body from method call)

F6 Step over (Execute current line and goto next line)

F7 Step Return (Come back from method body to method call)

F8 Resume/Stop/Next nearest break point

F11 Start Debug

Ctrl+shift+i Inspect (Check Expression value)

Ctrl+F11 Run application

Break Points: -

It is starting point for debug process. We can create multiple breakpoints in


eclipse to skip block of code execution step by step.

To create break point double click on blue color bar in editor inside
eclipse,even same double click to remove breakpoint.

Skip All Break Point: -

To disable all breakpoints for some time use this option.

109
Raghu Sir [Sathya technologies, Ameerpet]

Date Format Problem in Model Class: -

110
Raghu Sir [Sathya technologies, Ameerpet]

Write in Model Class Date Variable level as:

@DateTimeFormat(Pattern=”yyyy-MM-dd hh:mm:ss”)

Also add below code in UomDataEdit.jsp

(In form)

<div class=”form-group”>

<label for=”createdOn” class=”..”>Created Date</label>

<form:textarea path=”createdOn” cssClass=”..” readOnly=”true”></div>

111
Raghu Sir [Sathya technologies, Ameerpet]

Data Export Using Multipart Coding: -

(Example module: UOM)

Database table can have multiple rows, these rows are loaded into application
and exported to Excel WorkBook as one Sheet.

In this Sheet rows are constructed from Object (Model class objects).

Design:

Coding Steps#

112
Raghu Sir [Sathya technologies, Ameerpet]

#1 Create one hyperlink in UomMultipart.jsp “Export/Download Data”.

#2 Define one method in MultipartController which gets data from DB as List


and returns to ____XlsxView class as ModelAndView.

Here ModelAndView should have Xlsx view object and List as Param value.

#3 Define one class _____XlsxView that extends “AbstractXlsxView” (C) also


override abstract method bulidExcelDocument().

View Class Format:

publicclass UomXlsxView extends AbstractXlsxView{

@Override

Protected void buildExcelDocument(…){

private void setHead(..){}

private void setBody(..){}

#1)create Uom Export for current Page Data.

Sol:

Step#1: create one hyperlink in UomData.jsp as

<href=”uomExcel?page=${page.getNumber}”>Export Page </a>

113
Raghu Sir [Sathya technologies, Ameerpet]

Step#2: define controller method in UomController and return ModelAndView


by calling UomXlsxView with List

*** write UomXlsxView (C) only one time.

114
Raghu Sir [Sathya technologies, Ameerpet]

OrderMethod/ShipmentType Module: -

115
Raghu Sir [Sathya technologies, Ameerpet]

Model Class (_________)

Repository (_______Repository)

IService(I________Service)

ServiceImpl(_______ServiceImpl)

UIController (________UIController)

Util (_____Util)

JSP(__Register/__Data/__DataEdit/__ViewData)

RestController (________RestController)

Validator(____Validator)

Pagination and Specification(_______Specification)

MultipartController (____MultipartController)

JSP(____Multipart)

MultipartValidator(__MultipartValidator)

Here _____ = module name

116
Raghu Sir [Sathya technologies, Ameerpet]

Notes: -

1] In DB, table names and column names are case in-sensitive.

i.e. emptab, EMPTAB, emptab, are same.

Ex: select eid from emptab and

SELECT EID FROM EMPTAB are same.

2] If UI (JSP) input type is

**Checkbox **Multi-select dropdown

Then variable type in model class is List<String> type.

3] If variable is List type in model class then, one child table is created with 3
columns (Key column, index column, element column).

Util, Validator, Controller

Jsp ____Register.jsp,

117
Raghu Sir [Sathya technologies, Ameerpet]

View Page Coding Design: -

In __Data.jsp page do not display all fields, show only few important field.

**In Data.jsp create one hyperlink (using URL-ReWriting concept).

** On click link it should get only that object data using Primary Key and
display all values as a HTML Table.

118
Raghu Sir [Sathya technologies, Ameerpet]

Service:

A service is a special application or code which provides extra function to


existed project.

Ex: Java Example Services : Java mail, Java Securing (Jaas = Java Authentication
and Authorization) ,CODEC (COding and DECoding), Java design Generators
(JFreeCharts) , Java File Operations (Upload and Download) , Java
cryptography, Java unique key Generation, etc.

Microservices:

A service must run independent and it should be re-usable, implemented


using less coding(small part) is called as “Micro Service”.

*Every Re-usable service can be converted to micro services.

Note: A Micro Service should be

I] Reusable Service

II] Independent (must be run in diff server)

III] Plug-in (Link using Web-services Or Parent project concept).

119
Raghu Sir [Sathya technologies, Ameerpet]

Module (Implementation) as a Service (MaaS):

We must implement one module which supports operation using

1] UI Forms and Tables in PL

2] Web service calls for different client and Integration Apps (Ex: Andriod,
Third party apps, Service Engine) etc.

3] Bulk Operations (Data upload and Download also called as Export and
Import using Excel sheets).

For all these programming logic should be written only one time (in common
layer i.e. Service Layer).

This Service layer can connect to Data Access Layer and even Utils (Support
classes). Use Server side (Service Side) validator for all Request Processing.

MaaS has a standard Design for module implementations which are reusable
for all types of Application, changes will be at PL (Presentation Layer) or IL
(Integration Layer).

**Calculations and common logics are written in SL and its Utils.

**Common validations are written in Validator class level.

120
Raghu Sir [Sathya technologies, Ameerpet]

Design of MaaS:

121
Raghu Sir [Sathya technologies, Ameerpet]

Uom: -(Unit Of Measurment)

To identify one item, it should be measured using one UOM.

Possible UOMs are: Piece, box, pallet,rack

Every Uom will be one of type PACKED ITEM, NON PACKED ITEM, Not
APPLICABLE

TV = PACKED ITEM

COMPUTER Items (to be assembled) = NA

CLOTHES = NON PACKED ITEMS

BOX = SMALL, MEDIUM, LARGE, EXTRA LARGE

Indicated using BOXA, BOXB, BOXC, BOXD

In same way PALLETA, PALLETB, PALLETEC and PALLETED.

RACKing process is given to LEVEL1,2,3,4 so they are called as RACKA = (1)

RACKB = (2), RACKC = (3), RACKD = (4).

**Pallet is a wooden holder which contains Items on top of it.

**Pallets (Items) are moved using “fork Lifters”

ShipmentType: -
122
Raghu Sir [Sathya technologies, Ameerpet]

It is used in outbound operation (Sending an Item from warehouse to end


customer/E-commerce Application).

Possible Shipping Types are:

AIR (Cargo Flight)

Ship (Ship Container)

Train (Goods Train)

Truck (Tempo,DCM).

Every ShipmentType identified using one unique code based on contractor.

Ex: SG-558, VV-586 (Ship)- VayuVega, GarudaVega.

Shipment must be enabled (YES must be checked) for usage. If contract is


broken then shipment will be disabled (not deleted)

Every Shipment Type must be granted based on Security/Insurance/Faster


Delivery.

Ex: Grade A = Secured and Faster

Grade B = Faster

Grade C = Secured

Grade D = Normal

Warehouse UserType: -

123
Raghu Sir [Sathya technologies, Ameerpet]

Here we have two types of users in warehouse concept.

1. Vendor: One who gets an item into warehouse. Person details used in
inbound operation.
2. Customer: One who gets an item out of warehouse. Person details used
in outbound operation.

It is like complete info of User (User Registration process) Name, Email,


Address, Id details, unique code, Type (Vendor/Customer).

**One Item will be connected to multiple vendors and customers (at least
one).

**To perform inbound operation, must choose one vendor. Then only those
vendor connected items will be used to create in order process.

**In same way for outbound operation, must choose one customer, only that
customer items will be used to create SaleOrder.

**User For (input) is an auto fill input(use JQuery or Java Script)

on click “Vendor” type it should have value “Purchase” also for “Customer”
type value is “Sale”.

**In same way if ID Type is “Other” then

124
Raghu Sir [Sathya technologies, Ameerpet]

*If Other (input) must be enabled else it should be read only input

WhUserType Module Special Case: -

125
Raghu Sir [Sathya technologies, Ameerpet]

Process#1: On Change “UserType”

If UserType = “Vendor”

thenuserFor value should be “Purchase Type”

else if UserType = “Customer” then

userFor value should be “Sale Type”

Process #2On Change “UserIdType”

If userIdType = “Others” then

ifOther should be set “readOnly=false”

else

ifOther should be set “setOnly=true”

and clear input field.

126
Raghu Sir [Sathya technologies, Ameerpet]

Code: WhUserTypeRegister.jsp

Step#1 make fields readOnly=true

<form:form…….>

User For : <form:input path=”userFor” readOnly=”true”/>

……….

If Other :<form:input path=”ifOther” readOnly=”true”/>

Step#2 In same page under <head> tag add below script

<head>…

<script type=”text/javascript”>

$(document).ready(function(){

$(‘input[type=radio][name=userType]’).change(function(){

If(this.value==’Vendor’){

$(“#userFor”).val(“Purchase Type”);

Else if (this.value==’Customer’){

$(“#userFor”).val(“Sale Type”);

});

$(function(){

$(“#userIdType”).change(function(){

If(this.value=’OTHERS’){

$(“#ifOther”).prop(“readonly”,false);

127
Raghu Sir [Sathya technologies, Ameerpet]

Else{

$(“#ifOther”).val(“”).prop(“readonly”,true);

}});});});

Importing Project Into Eclipse Workspace: -

#1 Download project (as .zip or .rar).

#2 Extract it and Import using import project option in Eclipse.

#3 Chang in application.properties file DB connection details.

#4 Update maven.

**Master Page Design: -

To handle common data, ex: menu bar, logo details, footer, etc. in each and
every jsp, define one new JSP and write code there.

128
Raghu Sir [Sathya technologies, Ameerpet]

Link this new JSP to all existed JSP’s using <%@include file=”Master.jsp”%>

Getting Common Url For Links in Menubar: -

Step#1 Get complete (Current open file) URL using JSTL and create Variable

Code: <c:set var=”base”>${pageContext.request.requestURL}</c:set>

Ex output:

http://localhost:2018/WEB-INF/views/UomData.jsp

129
Raghu Sir [Sathya technologies, Ameerpet]

Step#2 Remove URI from above URL and replace place contextpath
(projectname) if exist.

Code:

<c:set var=”url” value=”${fn:replace(base,pageContext.request.requestURI)},

pageContext.request.contextPath”/>

Ex: output: http://localhost:2018 (if project name exist then)

http://localhost:2018/projname

Step#3 use var=”url” in menu bar <a>(Hyperlinks) with EL.

Ex: <a href=”${url}/uom/all”>View All </a>

Project Name (Context Path):-

server.servlet.context-path=/

JDK [Compiler and JVM] Version Change for Spring Boot Project in
Eclipse: -

Step#1 Update in pom.xml

 Open pom.xml in source mode


 Goto <java.version> tag
 Modify JDK version ex: 1.8 > 1.7

130
Raghu Sir [Sathya technologies, Ameerpet]

 Update Maven Project

Step#2 Buildpath change

 Right click on project


 Build path > configure build path
 Library Tab > click JRE System Lib
 Edit > Choose Workspace default > OK
 Finish

Step#3 Project Compiler version change

 Right Click on project


 Choose last Option properties
 Search “Java Compiler” and select same
 Change version (ex:1.8 to 1.7)
 Apply and finish

Step#4 Facets version change for Project.

 Click on window menu.


 Choose show view > Navigator option
 Expand project
 Open “.settings” folder
 Open below file in source mode
“org.eclipse.wst.common.project.facet.core.xml”.
 Modify (facet=”java” version=”1.7”).
 Update Maven Project.

Item Module: -

Model Class Design:

131
Raghu Sir [Sathya technologies, Ameerpet]

Integration of Module Coding Order:

1.FindByMethods

2.ModelClassCoding

3.RepoCode

4.ServiceCode

5.UtilCode Has-A with child services & UI components

6.Controller

7.JSP

**findBy() Methods in Spring Boot Data JPA: -

132
Raghu Sir [Sathya technologies, Ameerpet]

These methods are used to fetch data based on any column(variable) by


making it where clause condition.

findBy equal SQL meaning is:

select * from <table> where <column>=?;

**These methods must be defined in Repository(I) only.

**These are abstract methods.

Implementation will be given by “spring boot data JPA” only.

**Returns our expected model class data.

*Syntax to write findBy methods

List<T> findBy<varName>(DataType varName);

Ex:1] in WhUserTypeRepository (I) add

//select * from whuser where type=?

List<WhUserType>findByUserType(String userType);

Ex:2] in OrderMethodRepository(I) add

//select * from omtab where mode=?

List<OrderMethod>findByOrderMode(String orderMode);

**Variable name should exist in model class and datatype must be matched.

**In method variable name first letter should be in upper case.

Multiplicities: -

Connecting one table rows with another table rows is called as “Multiplicities”.

133
Raghu Sir [Sathya technologies, Ameerpet]

These are 4 types in database tables:

1]One-to-one (1…1)

2]One-to-many (1…*)

3]Many-to-one (*…1)

4]Many-to-many (*…*)

Note: a)To connect two tables with multiplicity one table PK should be taken
as another table FK column.

b)Hint: always many(*) side extra FK column is created.

c)In case of many-to-many one extra table with two FK column is created.

d)In case of one-to-one use many-to-one and Many side “unique” condition.

e)Here,

1…1 and *…1 are non-collection type.

1…* and *…* are Collection Type.

Use List/Set for HAS-A variable.

 Hibernate divided these multiplicities into 2 types.


1. Non-Collection Based
2. Collection Based

 In case of 1…1 use *(unique) …1 and


 For *…*3rd table will be created with 2FK Columns.

134
Raghu Sir [Sathya technologies, Ameerpet]

Tables with multiplicities: -

135
Raghu Sir [Sathya technologies, Ameerpet]

Examples: Multiplicity Code

Steps#

1]Define classes with HAS-A Relation

2]Check for Collection Type

3]Apply Multiplicity annotations

136
Raghu Sir [Sathya technologies, Ameerpet]

Class Item{ class OrderMethod

@ManyToOne

@JoinColumn(name=”itemIdFK”)

List<OrderMethod> orderMethod;

} }
137
Raghu Sir [Sathya technologies, Ameerpet]

Class Item{ class OrderMethod

@OneToMany(mappedBy=”orderMode”,name=”Purchase”)

@JoinColumn(name=”itemIdFK”)

List<OrderMethod> orderMethod;

} }

//Module Integration Code

//Item---------------<>Uom

1…*

Class Item{ class Uom

@OneToMany

@JoinColumn(name=”uomIdFK”)

private Uomuom;

} }

Class Item{ class WhUserType

@ManyToMany

@JoinTable(name=”itemtab”,

JoinColumns=@JoinColumn (name=”itemIdFK”),

inverseJoinColumns (@JoinColumn(name=”whuserIdFK”))

138
Raghu Sir [Sathya technologies, Ameerpet]

List<WhUserType>whVendor;

} }

Class Item{ class WhUserType

@ManyToMany

@JoinTable(name=”itemtab”,

JoinColumns=@JoinColumn (name=”itemIdFK”),

inverseJoinColumns (@JoinColumn(name=”whuserIdFK”))

List<WhUserType> whCustomer;

} }

Converting DB Table Data to UI Component as

139
Raghu Sir [Sathya technologies, Ameerpet]

UomCode is Label and

ID is Value.

Here, <option value=””> should have PK value and between <options> tags it
should have Code or any equal word of model data.

Example:

To get above output, should be written as

<form:options items=”${ CollectionName}”

itemLabel=”CodeVar”

itemValue=”idVar”/>

** To get multi-select dropdown Spring form tag code is:

<form:select path=”” multiple=”true”>

</form: select>

140
Raghu Sir [Sathya technologies, Ameerpet]

ShortCut:

Ctrl+1 Enter: - To Create Selected Method Declaration

Integration Steps: -

141
Raghu Sir [Sathya technologies, Ameerpet]

1.Model Class

Apply HAS-A between parent and child modules and write multiplicity
annotations code.

2.Util Code:

In Parent module Util write child IService type as HAS-A type, get data from
find methods and add to ModelMap.

3.UI Code:

Here write <form:options items=”${key}” itemLabel=”codeVar”


itemValue=”idVar”>

Ex: Item---------------<>Uom

*…1

Coding Steps#

1.class Item{

@ManyToOne

@JoinColumn(“uomIdFK”)

private Uom uom = new Uom();

2.ItemUtil

@Component

Class ItemUtil{

@Autowired

private IUomService uomService;

public void addUiComponents(ModelMap map){

142
Raghu Sir [Sathya technologies, Ameerpet]

map.addAtttribute(“uoms”,uomService.findAll());

3.ItemRegister.jsp

<form:form>

Item Uom: <form:select path=”uom”>

<form:options items=”${uoms}” itemLabel=”uomModel”


itemValue=”uomId”>

</form:select>

Item Module UI Design: -

143
Raghu Sir [Sathya technologies, Ameerpet]

Sample Code For Item Module: -


144
Raghu Sir [Sathya technologies, Ameerpet]

#1. Add findBy methods to child modules repo and IServices.

Code:

A] Add below method in OrderMethodRepo(I)

List<OrderMethod>findByOrderMode(String orderMode);

B] Add same method in IService and implementation in ServiceImpl (Impl


code is)

public List<OrderMethod> findByOrderMode(String orderMode){

return repo.findByOrderMode(orderMode);

C] Also write findBy method for WhUserTypein both repo and service

public List<WhUserType> findByUserType(String userType);

#2.Define Item Model class with basic UI input and multiplicity inputs

Code:

package com.app.model;

public class Item{

id,code,width,len,hght,cost,curr,etc.

@ManyToOne

@JoinColumn(name=”uomIdFK”)

private Uomuom = new Uom();

@ManyToOne

@JoinColumn(name=”omIdSaleFK”)

privateOrderMethod omSale = new OrderMethod();

@ManyToOne

145
Raghu Sir [Sathya technologies, Ameerpet]

@JoinColumn(name=”omIdPurchaseFK”)

private OrderMethod omPurchase = new OrderMethod();

@ManyToMany

@JoinTable(name=”itm_ven_tab”),joinColumns=

@JoinColumn(name=”itm_idFK”),inverseJoinColumns=

@JoinColumn (name=”ven_idFK”)

privateList<WhUserType>vendors = new ArrayList<WhUserType>();

@ManyToMany

@JoinTable(name=”itm_cust_tab”),joinColumns=

@JoinColumn(name=”itm_idFK”),inverseJoinColumns=

@JoinColumn(name=”cust_idFK”)

private List<WhUserType>customers = new ArrayList<WhUserType>();

#3.ItemUtil Code

@Component

public class ItemUtil{

//HAS-A with IUomService,

//IOrderMethodServiec,IWhUserTypeService

//add UIComponent methods like

146
Raghu Sir [Sathya technologies, Ameerpet]

Public void addUiComponents(ModelMap m){

m.addAttribute (“itemBseCurncies”,getBaseCurrencies());

m.addAttribute(“uoms”,uomService.getAll());

m.addAttribute(“omsales”,omService.findByOrderMode(“Sale”));
m.addAttribute(“ompurchases”,omService.findByOrderMode(“Purchase
”));

m.addAttribute(“whVendors”,whUserTypeService.findByUserType(“Ve
ndors”));

m.addAttribute(“whCustomers”,whUserTypeService.findByUserType(“Custo
mer”));

#4.Add below code under <form> in ItemRegister.jsp

<form:form…>

//code,Currency,Cost,W,L,H..

Item UOM:<form:select path=”uom”>

<form:option value=””>--Select--<form:option>

<form:options items=”${uoms}” itemLabel=”uomModel”


itemValue=”uomId”>

</form:select>

Order Method Sale:<form:select path=”omSale”>

<form:option value=””>--Select--</form:option>

<form:options items=”${omsales}” itemLabel=”orderCode”

147
Raghu Sir [Sathya technologies, Ameerpet]

itemValue=”orderMethdId”/>

</form:select>

Order Method Purchase:<form: select path=”omPurchase”>

<form:option value=””>--Select--</form:option>

<form:options
items=”${ompurchases}”itemLabel=”orderCode”

itemValue=”orderMethdId”/>

</form:select>

Item Vendors: <form:select path=”vendors” multiple=”true”>

<form:options items=”${whVendors}” itemLabel=”userCode”

itemValue=”whUserTypeId”>

</form:select>

Item Customers: <form:select path=”customers” multiple=”true”>

<form:options items=”${whCustomers}” itemLabel=”userCode”

itemValue=”whUserTypeId”>

</form:select>

</form:form>

Item Validator Code:

148
Raghu Sir [Sathya technologies, Ameerpet]

#1 Create one Validator class and implements Validator(I) given by Spring.

Also override 2 methods.

#2 HAS-A Between validate and util. ItemValidator--------------<>ItemUtil

#3 write below code in validate() method.

Item item = (Item)target;

if(!Pattern.compile(“[A-Z]{4,8}”).matcher(item.getItemCode()).matches()){

errors.rejectValue(“itemCode”,””,”Enter 4-8 Upper Chars Only”);

if(item.getItemBaseCost()==null || item.getBaseCost<=0){

Errors.rejectValue(“itemBaseCost”,””,”Enter Base Cost For Item”);

if(!util.getBaseCurrenencies().contains(item.getItemBseCurncy())){

errors.rejectValue(“itemBseCurncy”,””,”Select Base Currency”);

if(item.getUom() == null ||
StringUtils.isEmpty(item.getUom().getUomModel())){

errors.rejectValue(“uom”,””,”Choose one UOM”);

if(item.getOmSale() == null ||
StringUtils.isEmpty(item.getOmSale().getOrderCode())){

errors.rejectValue(“omSale”,””,”Choose one Sale Type”);

149
Raghu Sir [Sathya technologies, Ameerpet]

if(item.getOmPurchase() == null || StringUtils.isEmpty(item.getOmPurchase


().getOrderCode())){

errors.rejectValue(“omPurchase”,””,”Choose one Purchase Type”);

if (item.getVendors() == null || item.getVendors().isEmpty())){

errors.rejectValue (“vendors”,””,”Choose atleast one Vendor”);

if (item.getCustomers() == null || item.getCustomers().isEmpty())){

errors.rejectValue (“customers”,””,”Choose atleast one Customer”);

150
Raghu Sir [Sathya technologies, Ameerpet]

Joins: -

Joins are used to fetch data from multiple connected tables (PK-FK).

**Based on SQL type Joins are:

1) Equal Join (=)


2) Cross Join (X)
3) Self Join (=><=)
4) Inner Join (Connected Rows)
5) Outer Join
a) Left Outer Join | Left Join
b) Right Outer Join| Right Join
c) Full Outer Join | Full Join

** HQL supports only Inner Joins and Outer Joins.

Joins are applicable for all multiplicities.

Consider, below example Tables and output of every join,

Consider equal Model Class For above tables are:

Class Employee{ class Address {

151
Raghu Sir [Sathya technologies, Ameerpet]

Int empId; int locId;

String empName; String locName;

Double empSal; long pinCode;

Address addrs;-Child Var

} }

The HQL Joins Syntax is:

selectp.variables,c.variables from ParentClass p

[Join Type]

p.childVar c

where<condition>

Ex: select e.empName, a.locName from com.app.Employee

e inner join e.addrs a empId=11;

152
Raghu Sir [Sathya technologies, Ameerpet]

To implement Item Multipart Controller, add below methods (findBy)


in:-

#1)Uom: (Repo,IService,ServiceImpl)

Uom findByUomModel(String uomModel);

#2)OrderMethod: (Repo,Iservice,ServiceImpl)

OrderMethod findByOrderCode(String orderCode)

#3)WhUserType:

WhUserType findByUserCode(String userCode)

**These methods are used to convert String input(given from Excel sheet)

To their respected model class object.

Step#1 Write Item MultipartController

Step#2 Write process method in ItemUtil.

153
Raghu Sir [Sathya technologies, Ameerpet]

Edit Data Flag: -

#1 Create one boolean properly in Validator class with set method.

Ex: private booleanisEdit;

//set method

#2 use this as “!isEdit” to avoid any validation check at the time of edit.

Ex: data already exist conditions

#3 set this isEdit as false in register and true in update methods in Controller.

#4 ItemValidator:

In ItemValidator check object null or obj.getId() == null (remove StringUtil).


isEmpty for uom, order methods)

#5 Sample JSON for Item Creation using RestController swagger UI:

“baseCost”: 2.2,

“baseCurrency”: “INR”,

“description”:”String”,

“itemCode”:”String”

“itemHgth”:2.2,

“itemLnth”:3.3,

“itemWdth”:4.4,

“uom”:{ “uomId”:2,”uomModel”:”BOXA”},

“omPurchase”:{“orderMethdId”:2,”orderCode”:”SALEONE”},

“omSale”:{“orderMethdId”:1,”orderCode”:”SALEONE”},

“whCustomers”:[{“whUserTypeId”:2}],“whVendors”:[{“whUserTypeId”:3}] }

154
Raghu Sir [Sathya technologies, Ameerpet]

INBOUND OPERATIONS

Purchase Order MODULE: -

To place one order EndUser should provide main details and item details.

Main Details are called as “PurchaseOrderHeader (PoHdr)”.

It is given as Screen#1.

It contains information like OrderCode, ShipmentMode, VendorCode, RefNo,


QuallityCheckStatus, default status (OPEN).

If PO (Purchase Order) main details is created, then user can selects Items,

One line is called as One PoDtl (Purchase Order Details). Every PoDtl contains
slno, ItemCode, BaseCost, Qty.

Model class relations are given as:

155
Raghu Sir [Sathya technologies, Ameerpet]

Purchase Order Status Codes: -

OPEN: - It is default status, on creating POHdr it will be assigned.

PICKING: - If atleast one item is added to Po using PoDtl Screen then status
will be PICKING.

**If all items are removed from PoDtl then status will be OPEN.

**In PoHdr, “vendor” can be editable if PoHdr status is “OPEN”. Else readonly.

ORDERED: -No more picking items to PO. It says Order is completed.

INVOICED: -After generating bill for Vendor as a PDF then PO status should be
INVOCED. Only ORDERED Status PO can be used in Vendor Invoice process.

156
Raghu Sir [Sathya technologies, Ameerpet]

RECEIVED: -If GRN is done for PO having status INVOICED then it will be
changed to RECEIVED.

Screen#1: Purchase Order Hdr

157
Raghu Sir [Sathya technologies, Ameerpet]

Screen#2: Purchase Order Dtl

Screen#3: Vendor Invoice

158
Raghu Sir [Sathya technologies, Ameerpet]

Goods Receive Note (GRN)

Screen#1:

Screen#2:

159
Raghu Sir [Sathya technologies, Ameerpet]

Cascading In Multiplicity: -

On performing operation over parent object, if we want to apply same


operation on child object without writing extra code, then use Cascading.

**It works only for non-select operations.

Ex: saveParent --- automatically saveChild

deleteParent -----automatically deleteChild

updateParent ---- automatically updateChild

Fetch [FetchType]: -

On selecting parent object if we want all it’s child objects to be loaded at same
time, then use “EAGER” Fetch Type.

On reading child object get data from DB then use “LAZY” Fetch type.

Ex:

public class PurchaseOrderHdr{

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)

@JoinColumn(name=”poHdrId”)

Private List<PurchaseOrderDtl> poDtls=new


ArrayList<PurchaseOrderDtl>();

160
Raghu Sir [Sathya technologies, Ameerpet]

JAAS [Java Authenticated &Authorisation Service]

This is Java EE concept, used to specify Security (access level) to one URL.

Every URL falls under one of below level:

1] No Security (permit all)

No login to requireaccessing this URL.

2] Only Authenticated (only Login)

End User/AppUser, must be logged-in before accessing this URL.

3] Only Authorized (Login + Role)

End User must be logged-in and also he/she has matching Role to access
the URL.

Java

Authentication ------------------------------ login checks

Authorization -------------------------------- roles checks

Service

Example:

161
Raghu Sir [Sathya technologies, Ameerpet]

Spring Security Using JAAS:

Define one class that has both authentication and authorization code by
following

Below steps:

#1 Write one java class with any name

#2 this class must extends “WebSecurityConfigurerAdapter”.

#3 Apply Annotations on class

@Configuration and

@EnableWebSecurity

#4 Specify two methods in above class:

configureGlobal(): for Authentication

configure(): for Authorization

162
Raghu Sir [Sathya technologies, Ameerpet]

In “configure()” method specify URLs and their access levels by writing code
like

#1 antMatchers(“/urlPattern”).permitAll()

#2 antMatchers(“/urlPattern”).hasAuthority(“ROLE”)

--OR—

antMatchers(“/urlPattern”).hasAnyAuthority(“ROLE-1”,”ROLE-2”)

#3 anyRequest().authenticated();

Here, url Pattern can have symbols like

*= any character

**= multi-level path + any character

Ex: url pattern = /uom*

163
Raghu Sir [Sathya technologies, Ameerpet]

/uomData (valid)

/uomExport (valid)

/dataUom (Invalid)

/uom/abc (Invalid)

Ex: Url Pattern = /uom**

/uom/all (Valid)

/uom (valid)

/uomData (Valid)

/uom/one/app/xy (valid)

164
Raghu Sir [Sathya technologies, Ameerpet]

User/Admin Registration Process:

#1 Define Register.jsp as shown below for both user and admin register
process

#2 On click submit data will be converted to object format. So, store data
model class design is given below

User----------------------<>Role

(com.app.model.User) *…*(com.app.model.Role)

165
Raghu Sir [Sathya technologies, Ameerpet]

@Entity

publicclass User{

privatelong userId;

private String username;

private String userEmail;

private String userPwd;

private int active;

@ManyToMany(fetch=FetchType.EAGER)

@JoinTable(name=”usr_role_tab”,

joinColumns=@JoinColumn(name=”uidFk”),

inverseJoinColumns=@JoinColumn(name=”ridFk”))

private List< Role > roles = new ArrayList<Role>(0);

166
Raghu Sir [Sathya technologies, Ameerpet]

#3 In Controller method

>read ModelAttribute (User)

>encode password (un-readable format)

>check email id exist in DB using findByUserEmail

>if exist return to UI with error msg

>else save data into user table

> send email to userEmail (id,pwd,msg)

> send success message to UI

167
Raghu Sir [Sathya technologies, Ameerpet]

User Login Flow: -

#1 In browser Enter URL /login (GET)

#2 Define one method in UserController for /login(GET) that should return


Login.jsp (looks as below)

#3 On click login button, /login(POST) request should be made.

Here, programmer should define one impl class for spring interface
“UserDetailsService” which converts User(Model Object) to User (Spring
framework) object.

#4 This User (Spring f/w) object is given to “WebSecurityConfigurerAdapter”


impl class for next level checking.

168
Raghu Sir [Sathya technologies, Ameerpet]

Step#1 Define One class that should implements UserDetailsService


(org.sf.security.core.userdetails) given by spring framework.

Step#2 override method in our class loadUserByUsername(..)

Step#3 Define logic in it,that converts model class “User” to F/w “User” as

169
Raghu Sir [Sathya technologies, Ameerpet]

In Spring Role is represented using GrantedAuthority(I) for this Impl class is


SimpleGrantedAuthority(C).

**Refer UserDetailsServiceImpl class

Step#4 Define one class for SecurityConfiguration that extends


WebSecurityConfigurationAdapter class also provide HAS-A with

--<>UserDetailsService

--<>BCryptPasswordEncoder

Step#5 Define two methods one for authentication and another for
authorization

Refer: WebSecurityConfig.java class

--------===================

Define AdminPage Operations in Application on Admin Login we should show


this Page. Here display all User Details with status. Admin can make them
active and inactive. Here Active=1 and InActive=0

170
Raghu Sir [Sathya technologies, Ameerpet]

Hint:

**On entering pwd 3 times wrong make User Account Locked.

**After 30 days make user account should be expired.

Hint: use findAll in repo/service, /controller, send data to UI Using ModelMap

<c:if test=”${user.active==0}”>

<td> IN-ACTIVE </td>

<a href=”userStatChg=>status=1”></a>

</c:if>

**use User(un,pwd,ActExp, lock,pwdExp,auths) constructor

171
Raghu Sir [Sathya technologies, Ameerpet]

Spring Email Service: -

Basic “Email API” is given by SUN (Oracle) as “MailAPI” to send email from any
domain (host).

This API is simplified by Spring f/w using POJI-POJO and Helper class pattern.

Here, POJO-POJI given by Spring f/w

We should also define one POJI-POJO in application. Here we write method to


send email, this method can be re-used in complete application.

Use Helper class “MimeMessageHelper” (MIME->Multipurpose Internet Mail


extension) to write code in less time which supports simple email(text,subject
and attachment email).

172
Raghu Sir [Sathya technologies, Ameerpet]

Spring Cloud Foundry/Pivotal Cloud Foundry(pivotal.io): -

This is one cloud based Deployment Environment, which runs in cloud


network.

Link for Register New Account:

http://account.run.pivotal.io

1. Register with details

2. Verify Email and mobile number

3. Create one org name (ex:abcd-org) next-next-finish.

Execution steps:

Project#1:

>Right click on Project Maven->Update

>Right click on project

Run As -> Maven Clean

>Right click on project

Run As -> Maven install

**Now maven uses spring-boot-maven-plugin for building .war file and it


will be placed under ”target”folder in project.

Setup PCF#2:

>Login to PCF Account:

http://console.run.pivotal.io

>Click on “Pivotal Web Services” if multiple options are shown.

>Click on “Tools” shown at left menu.

>Download and install “cf-cli.exe”

173
Raghu Sir [Sathya technologies, Ameerpet]

**It will downloaded as .zip

**Extract and install

Login PCF#3:

>Right click on Project “target” folder in eclipse.

>choose “Properties” option

>Copy location

>open cmd promt

>Change location to target folder like

C:/>cd d:/myapp/springBoot/target

C:/>cd (press enter)

d:/myapp/springBoot/target>

>now type “cf login” in cmd promt

d:/../target>cf login

Email > _______(enter key)

Password>__________(enter key)

Push Application#4:

d:/../target> cf push warehouseApp –p BootApp-1.0.war

Wait for success message.

Syntax:

cf push projName –p fileName.war

Login:

cf login –a api.run.pivotal.io

174
Raghu Sir [Sathya technologies, Ameerpet]

Logout

cf logout

Push Code: (maven clean and install)

cf push “appName” –p file-name.war

Refresh and Access#5:

>Go to PCF (internet) account.

>Refresh URL (F5)

>Click on “org name”

>Click on “development”

>click On Apps

>Observe services and click on Route (Route means final link)

Ex:https://whapp.cfapps.io

175
Raghu Sir [Sathya technologies, Ameerpet]

Spring boot Actuator Endpoint:

This is a Pre-defined web services defined by spring boot which supports


“Production Environment”.

I.e. production ready environments

Endpoint: an URL path to execute one (web) service which is developed and
added to one application also running in server.

Enable Actuator in Application:

#1 in pom.xml add Spring boot dependency

<dependency>

<groupId>org.springframwork.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependecy>

#2 Actuator is built on top of spring Security and web services. So, AppUser
should have Role “ACTUATOR” Then only he can access end points.

#3 Here endpoint are sensitive (means secured) so AppUser must login before
accessing them.

#4 Once login is done access end point by typing “url/<endpoint>”.

176
Raghu Sir [Sathya technologies, Ameerpet]

Ex: few examples of actuator end points

https://whapp.cfapps.io/beans,env,auditevents,configprops,loggers,healt
h,logfile,metrics,mappings,sessions,info,

/beans: To see object created in Spring container and their details like name,
scope, dependencies, etc.

/logfile: To see custom logfile config by developer.

/loggers: To see App logs configured by Actuator.

/auditevents:To see Failure/Success details

/health:To know status of Supportive Service. Ex: DB Status:UP Email Service:


UP

/env:To know current profile application properties.

/configgroup: To know server details

/mappings: To see URL mappings given in application.

What is Profile in Spring Boot?

A) application.properties provides complete environment details. Instead


of deleting all details for new environment just we link to new
application.properties file ex: cloud.properties

24 Apr,2018.

177

You might also like