0% found this document useful (0 votes)
2 views

Archit ITS Report

This Industrial Training Report provides an overview of the author's training experience with Java, Spring Boot, and Object-Oriented Programming (OOP) concepts. It highlights the skills acquired during the training, including proficiency in core Java, multithreading, and microservices, while emphasizing the importance of user-centered design principles. The report serves as a comprehensive documentation of the training undertaken in partial fulfillment of a Bachelor of Technology degree in Computer Science and Engineering.

Uploaded by

19architmathur
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)
2 views

Archit ITS Report

This Industrial Training Report provides an overview of the author's training experience with Java, Spring Boot, and Object-Oriented Programming (OOP) concepts. It highlights the skills acquired during the training, including proficiency in core Java, multithreading, and microservices, while emphasizing the importance of user-centered design principles. The report serves as a comprehensive documentation of the training undertaken in partial fulfillment of a Bachelor of Technology degree in Computer Science and Engineering.

Uploaded by

19architmathur
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/ 37

An

Industrial Training Report


On
“Java, Spring boot and OOPS”
Submitted in partial fulfilment for the award of degree of
Bachelor of Technology
In
Computer Science and Engineering

Submitted
Dr. to:Jha
Pradeep Submitted
Archit to:
Mathur
Head of Department
CSE/IT/AI&DS 22EGJCS037

Certificate
IMs.
takeKangana
this opportunity
Saini, Institute
Assistant
Acknowledgement
to express my deep
Professor sense of gratitude
Department of Computerto myScience
coordinatorand
Engineering
and Global
cooperation throughout of
the Technology,
Practical Jaipur,
training for
work. his
He valuable
provided guidance
constant
Encouragement
Work. WePracticaland unceasing
are grateful enthusiasm
to ourperiod.
respected Dr. at
ICevery stagePrincipal
Sharma, of the practical
GIT for training
guiding
us
We during
express our Training
indebtedness to Dr. Pradeep Jha, Head of Department of for
Computer
providing Science
metimely and Engineering,
ampleguidance,
support during Global Institute
my Practical of Technology,
Training period. Jaipur
Without their
support
seemed and
a farfetched dream. Inthe completion
this respect we offind
our Practical
ourselves Training
lucky to would
have have
mentors
Place ofsuch
– GIT a great potential.
Jaipur Archit Mathur
B Tech 5th Semester,22EGJCS037
3rd year
This Industrial Training Seminargained
(ITS) report Abstract
provides
extensive
Technology
Technology, handsome
program
Jaipur. experience
in
The Computer
report Science
documents during
and
a the thirdanyear
Engineering
comprehensive
overview
ofGlobalofInstitute
the ofof
the Bachelor
atexploration of
Java, Springthe
Throughout
technologies,
Loops,
Boot and Microservices
training,
including
patterns, the
Core
Functions, student
Java
Object
on the
acquired
topics
Oriented
internet.
proficiency
including basic
Programming in a wide
variables,
language array
– of Core
conditions
Inheritance,
Objects, File
Multithreading Polymorphism,
Handling,
Spring, Encapsulation,
Exception
Spring Boot,Handling, Abstraction;
Collections,
Microservices. Interfaces, Classes &
Generics,through real
The
worldreport
create outlines
projects,
inbuilding the practical
emphasizing
next-generation applications
their role in of
Backend
applications. these
Theandtechnologies
the
training opportunities
has not onlythey
equipped
the student
understanding withinvaluable
of the technical skillsItconcludes
but has alsobyfostered a deeper
and
for user-centered
further
student's growth
future andsignificanceof
web
career design
exploration
aspirations. inversion
principles.
the fieldcontrol, collaborative
oftechnology and itsdevelopment,
reflecting impact on the
Chapter – 11.1
Basics
Table Of Contents
............................................................................................................ 1
................................................................................................................... 1
1.2
1.3 Datatypes
Variables
Conditionals ........................................................................................................
.........................................................................................................
.................................................................................................... 11
1.4
1.5 Methods
Loops
Object .......................................................................................................
..............................................................................................................
Oriented .....................................................................................................
Programming 1
............................................................................. 22
2.1
2.3 Inheritance
2.2Encapsulation
Polymorphism
Abstraction ...............................................................................................
....................................................................................................
2.4 .................................................................................................
Interfaces................................................................................................................ 2
Exception
Multithreading
Spring Handling...................................................................................................... 4356
..............................................................................................
....................................................................................................................
Boot ............................................................................................................7
Fine - Grained Authentication .............................................................................. 8
What is Permit .......................................................................... 9
Prerequisites .............................................................................10
What is Fine-Grained Authorization? ..................................... 11
How to Implement FGA in Java and Spring Boot....................12
Setting Up the E-commerce Application.................................13

Conclusion ...............................................................................14
Chapter – 1
Introduction Basics
Java is one of the most popular and widely used programming language and
platform. A platform is an environment that helps to develop and run
programs written in any programming language. Java is fast, reliable and
secure. From desktop to web applications, scientific supercomputers to
gaming consoles, cell phones to the Internet, Java is used in every nook and
corner.

However to become proficient in any programming language, one Firstly


needs to understand the basics of that language.

Therefore, below are the basics of Java in the format in which it will help you
the most to get the headstart:

Java Environment: The programming environment of Java consists of three


components mainly:
JDK
JRE
JVM
Java Basic Syntax : Every programming language has its own set of rules to
declare, define and work on its components. Reading and learning about all
of them together is difficult. Therefore here is a simple task of printing “Hello
World” in Java . During this process, major components and their syntaxes
are explained clearly.
Comments in Java : In a program, comments take part in making the program
become more human-readable by placing the detail of code involved and
proper use of comments makes maintenance easier and finding bugs easily.
Comments are ignored by the compiler while compiling the code.
1.1 Datatypes
Data types in Java are of different sizes and values that can be stored in the
variable that is made as per convenience and circumstances to cover up all test
cases. Java has two categories in which data types are segregated

Primitive Data Type: such as boolean, char, int, short, byte, long, float, and
double. The Boolean with uppercase B is a wrapper class for the primitive
data type boolean in Java.
Non-Primitive (Reference) Data Types
The Non-Primitive (Reference) Data Types will contain a memory address
of variable values because the reference types won’t store the variable value
directly in memory. They are strings, objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a


character array and a string in Java is, that the string is designed to hold a
sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities. Unlike C/C++, Java strings are not
terminated with a null character.

1.2 Conditions
The Java if statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of statements will be
executed or not i.e. if a certain condition is true then a block of statements is
executed otherwise not.

Example:

Advantages of If else statement

1. Conditional execution: The if-else statement allows code to be


executed conditionally based on the result of a Boolean expression.
This provides a way to make decisions and control the flow of a
program based on different inputs and conditions.
2. Readability: The if-else statement makes code more readable by
clearly indicating when a particular block of code should be executed.
This makes it easier for others to understand and maintain the code.
3. Reusability: By using if-else statements, developers can write code
that can be reused in different parts of the program. This reduces the
amount of code that needs to be written and maintained, making the
development process more efficient
1.3 Variables
Variables are the containers for storing the data values or you can also call it
a memory location name for the data. Every variable has a:

• Data Type – The kind of data that it can hold. For example, int, string,
float, char, etc.
• Variable Name – To identify the variable uniquely within the scope.
• Value – The data assigned to the variable.
There are three types of variables in Java – Local, Instance, and Static.

How to Initialize Java Variables?


It can be perceived with the help of 3 components explained -

Example:
// Declaring float variable
float simpleInterest;

// Declaring and initializing integer variable


int time = 10, speed = 20;

// Declaring and initializing character variable


char var = 'h';
Variables are the basic units of storage in Java. For a deeper understanding of
variable types, scope, and memory management, the Java Programming
Course provides a thorough exploration with hands-on coding tasks.

Types of Java Variables


Now let us discuss different types of variables which are listed as follows:

1. Local Variables
2. Instance Variables
3. Static Variables

1.3 Input Class

Using Scanner Class for Taking Input in Java

It is an advanced version of BufferedReader which was added in later versions


of Java. The scanner can read formatted input. It has different functions for
different types of data types.

• The scanner is much easier to read as we don’t have to write throws as


there is no exception thrown by it.
• It was added in later versions of Java
• It contains predefined functions to read an Integer, Character, and other
data types as well.

Syntax of Scanner class:

Scanner scn = new Scanner(System.in);


Importing Scanner Class:

‘To use the Scanner we need to import the Scanner class from the util package
as
import java.util.Scanner;

1.4 Methods
Jav Met
The method in Java or Methods of Java is a collection of statements that perform
some specific tasks and return the result to the caller. A Java method can perform
some specific tasks without returning anything. Java Methods allows us to reuse the
code without retyping the code. In Java, every method must be part of some class that
is different from languages like C, C++, and Python.
• A method is like a function i.e. used to expose the behavior of an object.
• It is a set of codes that perform a particular task.

Syntax of Method:

<access_modifier> <return_type> <method_name>( list_of_parameters)


{
//body
}
Advantage of Method:
• Code Reusability
• Code Optimization
Note: Methods are time savers and help us to reuse the code without retyping the
code.

Method Declaration

In general, method declarations have 6 components:

1. Modifier: It defines the access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 types of access specifiers.

• public: It is accessible in all classes in your application.


• protected: It is accessible within the class in which it is defined and in
its subclasses.
• private: It is accessible only within the class in which it is defined.
• default: It is declared/defined without using any modifier. It is
accessible within the same class and package within which its class is
defined.
• Note: It is Optional in syntax.
• 2. The return type: The data type of the value returned by the method
or void if does not return a value. It is Mandatory in syntax.
• 3. Method Name: the rules for field names apply to method names as
well, but the convention is a little different. It is Mandatory in syntax.
• 4. Parameter list: Comma-separated list of the input parameters is
defined, preceded by their data type, within the enclosed parenthesis. If
there are no parameters, you must use empty parentheses (). It is
Optional in syntax.
• 5. Exception list: The exceptions you expect by the method can throw;
you can specify these exception(s). It is Optional in syntax.
• 6. Method body: it is enclosed between braces. The code you need to
be executed to perform your intended operations. It is Optional in
syntax.

1.5 Loops
Loops in Java come into use when we need to repeatedly execute a block of
statements. Java for loop provides a concise way of writing the loop
structure. The for statement consumes the initialization, condition, and
increment/decrement in one line thereby providing a shorter, easy-to-debug
structure of looping. Let us understand Java for loop with Examples.

Syntax:
for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}

Parts of Java For Loop


Java for loop is divided into various parts as mentioned below:

• Initialization Expression
• Test Expression
• Update Expression

1. Initialization Expression

In this expression, we have to initialize the loop counter to some value.

Example:
int i=1;

2. Test Expression

In this expression, we have to test the condition. If the condition evaluates to


true then, we will execute the body of the loop and go to the update
expression. Otherwise, we will exit from the for a loop.

Example:
i <= 10
3. Update Expression:

After executing the loop body, this expression increments/decrements the


loop variable by some value.

Example:
i++;

Chapter – 2
Object Oriented Programming
Object-Oriented Programming or Java OOPs concept refers to languages
that use objects in programming, they use objects as a primary source to
implement what is to happen in the code. Objects are seen by the viewer or
user, performing tasks you assign.

Object-oriented programming aims to implement real-world entities like


inheritance, hiding, polymorphism, etc. in programming. The main aim of
OOPs is to bind together the data and the functions that operate on them so
that no other part of the code can access this data except that function.
Object-Oriented Programming is the backbone of Java. Mastering OOP
concepts like inheritance, encapsulation, and polymorphism is critical for
writing scalable Java code.

Inheritance

Inheritance is an important pillar of OOP (Object Oriented Programming). It is


the mechanism in Java by which one class is allowed to inherit the features
(fields and methods) of another class. We are achieving inheritance by using
extends keyword. Inheritance is also known as “is-a” relationship.

Let us discuss some frequently used important terminologies:

• Superclass: The class whose features are inherited is known as


superclass (also known as base or parent class).
• Subclass: The class that inherits the other class is known as subclass
(also known as derived or extended or child class). The subclass can
add its own fields and methods in addition to the superclass fields and
methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Below is the implementation of Inheritance in Java:

Java
1
//base class or parent class or super class
2
class A{
3
//parent class methods
4
void method1(){}
5
void method2(){}
6
}
7

8
//derived class or child class or base class
9
class B extends A{ //Inherits parent class methods
10
//child class methods
11
void method3(){}
12
void method4(){}
13
}

Polymorphism

It refers to the ability of object-oriented programming languages to


differentiate between entities with the same name efficiently. This is done by
Java with the help of the signature and declaration of these entities. The ability
to appear in many forms is called polymorphism.

Below is the implementation of the Polymorphism:

Java
1
sleep(1000) //millis
2
sleep(1000,2000) //millis,nanos
Types of Polymorphism
Polymorphism in Java is mainly of 2 types as mentioned below:

1. Method Overloading
2. Method Overriding
Method Overloading and Method Overriding

1. Method Overloading: Also, known as compile-time polymorphism, is the


concept of Polymorphism where more than one method share the same
name with different signature(Parameters) in a class. The return type of
these methods can or cannot be same.

2. Method Overriding: Also, known as run-time polymorphism, is the


concept of Polymorphism where method in the child class has the same
name, return-type and parameters as in parent class. The child class provides
the implementation in the method already written.

Encapsulation

It is defined as the wrapping up of data under a single unit. It is the


mechanism that binds together the code and the data it manipulates.
Another way to think about encapsulation is that it is a protective shield that
prevents the data from being accessed by the code outside this shield.

• Technically, in encapsulation, the variables or the data in a class is


hidden from any other class and can be accessed only through any
member function of the class in which they are declared.
• In encapsulation, the data in a class is hidden from other classes, which
is similar to what data-hiding does. So, the terms “encapsulation” and
“data-hiding” are used interchangeably.
Abstraction

Data Abstraction is the property by virtue of which only the essential details
are displayed to the user. The trivial or non-essential units are not displayed
to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object, ignoring the irrelevant details. The
properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the object.

Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will
stop the car, but he does not know how on pressing the accelerator, the speed
is actually increasing. He does not know about the inner mechanism of the car
or the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.

Java Classes
A class in Java is a set of objects which shares common characteristics/
behavior and common properties/ attributes. It is a user-defined blueprint or
prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.

Properties of Java Classes

1. Class is not a real-world entity. It is just a template or blueprint or


prototype from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of
methods.
Ch – 3 Classes & Objects

4. A class in Java is a set of objects which shares common characteristics/


behavior and common properties/ attributes. It is a user-defined
blueprint or prototype from which objects are created. For example,
Student is a class while a particular student named Ravi is an object.

5. Properties of Java Classes

6. Class is not a real-world entity. It is just a template or blueprint or


prototype from which objects are created.
7. Class does not occupy memory.
8. Class is a group of variables of different data types and a group of
methods.
9. A Class in Java can contain:
a. Data member
b. Method
c. Constructor
d. Nested Class
e. Interface
If you’re looking to gain a deeper understanding of Java and its object-
oriented principles, exploring a comprehensive Java Programming Online
course can be a valuable step. It will help you master the core concepts of
classes and objects, and how to effectively use them in building robust Java
applications.
Class Declaration in Java

access_modifier class <class_name>


{
data member;
method;
constructor;
nested class;
interface;
}

Java Objects
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that are
created to use the attributes and methods of a class. A typical Java program
creates many objects, which as you know, interact by invoking methods. An
object consists of :

1. State : It is represented by attributes of an object. It also reflects the


properties of an object.
2. Behavior : It is represented by the methods of an object. It also reflects
the response of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to
interact with other objects.
Example of an object: dog
Ch -4 Interfaces

What are Interfaces in Java?


The
and interface
interface
public, could
static,
multiple
methods
IS-A that in
andJava
only
inheritances
other
relationship. is variables
have
final
classesa mechanism
abstract
in
must by to achieve
Inmethods
default.
Java.implement.
other words,
Java isabstraction.
It(methods
used
interfaces
Interface Traditionally,
towithout
achieve
primarily
also an
a abstraction
body) and
define
represents the
To declare
abstraction.
empty
default.
methods body an interface,
That
andthat
Adeclared
implements class means
are
keyword. use
the all
in public the
and
implements interface
the methods
allanTo
interface. fields keyword.
in an
are
interface public,
implementmust It is
interface used
static,
implement
the to
areand
interface, provide
declared
final
all
usetheby
the total
with an

Uses of Interfaces in Java


Uses of Interfaces in Java are mentioned below:
It is
Since used
java to achieve
does not total
support abstraction.
multiple inheritances in the case ofclasses?
class,
So,••the
by
Anyisusing
class
interfaces.
It also
Interfaces
question an
used interface
can
are extend
to
used
arises itonly
achieve
to
why can achieve
one
loose
implement
use multiple
class, but
coupling. caninheritances.
abstraction.
interfaces when implement
we have multiple
abstract
The reason
variables in is,
theabstract
interfaceclasses maypublic,
are final, contain
andnon-final
static. variables, whereas
//
{
} Aint
simple
interface
final interface
Player
int id = 10;
move();
Relationship Between Class and Interface
A class can
another
reverse extendHowever,
interface.
(an another
interface class,
only aand
implementing similarly,
class anallowed.
interface
canisimplement
a class) not can extend
an interface, and the

Difference Between Class and Interface


Although
between
an Class
Classes
interface and
andInterface seem
Interface.
are mentioned Thethe
below: same
major there have
differences certain adifferences
between class and

Class Interface

In an interface, you must initialize


In class, you can instantiate variables
variables as they are final but you can’t
and create an object.
create an object.

A class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods.
The access specifiers used with
In Interface only one specifier is used-
classes are private, protected, and
Public.
public.
Implementation: To implement an interface, we Ch
implements use –5
theException
keyword Handling
Exception Handling in Java is one of the effective means to handle runtime errors so
that the regular flow of the application can be preserved. Java Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.

What are Java Exceptions?


In Java, Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the program’s
instructions. Exceptions can be caught and handled by the program. When an exception
occurs within a method, it creates an object. This object is called the exception object.
It contains information about the exception, such as the name and description of the
exception and the state of the program when the exception occurred.

Major reasons why an exception Occurs

• Invalid user input


• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Out of bound
• Null reference
• Type mismatch
• Opening an unavailable file
• Database errors
• Arithmetic errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running
out of memory, memory leaks, stack overflow errors, library incompatibility, infinite
recursion, etc. Errors are usually beyond the control of the programmer, and we should
not try to handle errors.
Difference between Error and Exception

Let us discuss the most important part which is the differences between Error and
Exception that is as follows:
• Error: An Error indicates a serious problem that a reasonable application
should not try to catch.
• Exception: Exception indicates conditions that a reasonable application might
try to catch.

An Exception is an unwanted or unexpected event, which occurs during the


execution of a program i.e at run-time, that disrupts the normal flow of the
program’s instructions. Exception handling is used to handle runtime errors. It
helps to maintain the normal flow of the program.
In any object-oriented programming language, Overriding is a feature that
allows a subclass or child class to provide a specific implementation of a
method that is already provided by one of its super-classes or parent classes.
When a method in a subclass has the same name, same parameters or
signature, and same return type(or sub-type) as a method in its super-class,
then the method in the subclass is said to override the method in the super-
class.

Ch – 6 Multithreading
2

Threads are the backbone of multithreading. We are living in a real world which in itself
is caught on the web surrounded by lots of applications. With the advancement in
technologies, we cannot achieve the speed required to run them simultaneously unless
we introduce the concept of multi-tasking efficiently. It is achieved by the concept of
thread.
Real-life Example of Java Multithreading
Suppose you are using two tasks at a time on the computer, be it using Microsoft Word
and listening to music. These two tasks are called processes . So you start typing in
Word and at the same time start music app, this is called multitasking . Now you
committed a mistake in a Word and spell check shows exception, this means Word is a
process that is broken down into sub-processes. Now if a machine is dual-core then one
process or task is been handled by one core and music is been handled by another core.
In the above example, we come across both multiprocessing and multithreading. These
are somehow indirectly used to achieve multitasking. In this way the mechanism of
dividing the tasks is called multithreading in which every process or task is called by a
thread where a thread is responsible for when to execute, when to stop and how long to
be in a waiting state. Hence, a thread is the smallest unit of processing whereas
multitasking is a process of executing multiple tasks at a time.

Multitasking is being achieved in two ways :

1. Multiprocessing : Process-based multitasking is a heavyweight process and


occupies different address spaces in memory. Hence, while switching from one
process to another, it will require some time be it very small, causing a lag
because of switching. This happens as registers will be loaded in memory maps
and the list will be updated.
2. Multithreading : Thread-based multitasking is a lightweight process and
occupies the same address space. Hence, while switching cost of
communication will be very less.

Below is the Lifecycle of a Thread been illustrated

1. New : When a thread is just created.


2. Runnable : When a start() method is called over thread processed by the thread
scheduler.
Case A: Can be a running thread
Case B: Can not be a running thread
3. Running : When it hits case 1 means the scheduler has selected it to be run the
thread from runnable state to run state.
4. Blocked : When it hits case 2 meaning the scheduler has selected not to allow a
thread to change state from runnable to run.
5. Terminated : When the run() method exists or stop() method is called over a
thread.
Two Ways to Implement Multithreading
Using Thread Class
Using Runnable Interface
Method 1: Using Thread Class
Java provides Thread class to achieve programming invoking threads thereby
some major methods of thread class are shown below in the tabular format
with which we deal frequently along the action performed by them.

Method Action Performed


s

start() It starts the execution of the thread

It does the executable operations statements in the body of this


run()
method over a thread

It is a static method that puts the thread to sleep for a certain time
sleep()
been passed as an argument to it

wait() It sets the thread back in waiting state.

notify() It gives out a notification to one thread that is in waiting state

notifyAl
It gives out a notification to all the thread in the waiting state
l()
setDae
It set the current thread as Daemon thread
mon()

stop() It is used to stop the execution of the thread

Ch- 7 File Handling


File Handling in Jav6 Nov, 202
In Java, with the help of File Class, we can work with files. This File Class is inside
the java.io package. The File class can be used by creating an object of the class and
then specifying the name of the file.
Why File Handling is Required?
• File Handling is an integral part of any programming language as file handling
enables us to store the output of any particular program in a file and allows us
to perform certain operations on it.
• In simple words, file handling means reading and writing data to a file.
In Java, the concept Stream is used in order to perform I/O operations on a file. So at
first, let us get acquainted with a concept known as Stream in Java.

Streams in Java

• In Java, a sequence of data is known as a stream.


• This concept is used to perform I/O operations on a file.
• There are two types of streams :
1. Input Stream:
The Java InputStream class is the superclass of all input streams. The input stream is
used to read data from numerous input devices like the keyboard, network, etc.
InputStream is an abstract class, and because of this, it is not useful by itself.
However, its subclasses are used to read data.
There are several subclasses of the InputStream class, which are as follows:
1. AudioInputStream
2. ByteArrayInputStream
3. FileInputStream
4. FilterInputStream
5. StringBufferInputStream
6. ObjectInputStream
Creating an InputStream
// Creating an InputStream
InputStream obj = new FileInputStream();
Here, an input stream is created using FileInputStream.
Note: We can create an input stream from other subclasses as well as InputStream.
2. Output Stream:
The output stream is used to write data to numerous output devices like the monitor,
file, etc. OutputStream is an abstract superclass that represents an output stream.
OutputStream is an abstract class and because of this, it is not useful by itself.
However, its subclasses are used to write data.
There are several subclasses of the OutputStream class which are as follows:
1. ByteArrayOutputStream
2. FileOutputStream
3. StringBufferOutputStream
4. ObjectOutputStream
5. DataOutputStream
6. PrintStream
Creating an OutputStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Here, an output stream is created using FileOutputStream.
Note: We can create an output stream from other subclasses as well as OutputStream.
Ch – 8 Spring
What is Spring Framework?
Spring is a lightweight and popular open-source Java-based framework
developed by Rod Johnson in 2003. It is used to develop enterprise-level
applications. It provides support to many other frameworks such as
Hibernate, Tapestry, EJB, JSF, Struts, etc. so it is also called a framework of
frameworks. It’s an application framework and IOC (Inversion of Control)
container for the Java platform. The spring contains several modules like IOC,
AOP, DAO, Context, WEB MVC, etc.

Why to use Spring?


Spring framework is a Java platform that is open source. Rod Johnson created
it, and it was first released under the Apache 2.0 license in June 2003. When
it comes to size and transparency, Spring is a featherweight. Spring
framework’s basic version is about 2MB in size. The Spring Framework’s core
capabilities can be used to create any Java program, however there are
modifications for constructing web applications on top of the Java EE
platform. By offering a POJO-based programming model, the Spring
framework aims to make J2EE development easier to use and to promote
good programming habits.

Applications of Spring
1. POJO Based: Spring allows developers to use POJOs to create
enterprise-class apps. The advantage of using simply POJOs is that
you don’t require an EJB container product like an application server;
instead, you may use a powerful servlet container like Tomcat or a
commercial product.
2. Modular : Spring is set up in a modular approach. Even if there are a lot
of packages and classes, you only need to worry about the ones you
need and ignore the rest.
3. Integration with Existing Frameworks: Spring does not reinvent the
wheel; rather, it makes extensive use of existing technologies such as
numerous ORM frameworks, logging frameworks, JEE, Quartz, and JDK
timers, and other view technologies.
4. Testability: Because environment-dependent code is put into this
framework, testing a Spring-written application is trivial. Furthermore,
using JavaBeanstyle POJOs makes it easier to employ dependency
injection for injecting test data.
5. Web MVC: Spring’s web framework is a well-designed web MVC
framework that is an excellent alternative to web frameworks like
Struts and other over-engineered or less popular web frameworks.
6. Central Exception Handling: Spring provides a handy API for
converting technology-specific exceptions (such as those raised by
JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.
7. Lightweight: IoC containers are typically lightweight, especially when
compared to EJB containers, for example. This is useful for creating and
distributing programmers on systems with limited memory and CPU
resources.
8. Features of the Spring Framework
9. The features of the Spring framework such as IoC, AOP, and
transaction management, make it unique among the list of frameworks.
Some of the most important features of the Spring framework are as
follows:
10. IoC container:
Refers to the core container that uses the DI or IoC pattern to implicitly
provide an object reference in a class during runtime. This pattern acts
as an alternative to the service locator pattern. The IoC container
contains assembler code that handles the configuration management
of application objects.
The Spring framework provides two packages, namely org.spring
framework.beans and org.springframework.context which helps in
providing the functionality of the IoC container.
11. Data access framework:
Allows the developers to use persistence APIs, such as JDBC and
Hibernate, for storing persistence data in database. It helps in solving
various problems of the developer, such as how to interact with a
database connection, how to make sure that the connection is closed,
how to deal with exceptions, and how to implement transaction
management It also enables the developers to easily write code to
access the persistence data throughout the application.
12. Spring MVC framework:
Allows you to build Web applications based on MVC architecture. All
the requests made by a user first go through the controller and are
then dispatched to different views, that is, to different JSP pages or
Servlets. The form handling and form validating features of the Spring
MVC framework can be easily integrated with all popular view
technologies such as ISP, Jasper Report, FreeMarker, and Velocity.
13. Transaction management:
Helps in handling transaction management of an application without
affecting its code. This framework provides Java Transaction API (JTA)
for global transactions managed by an application server and local
transactions managed by using the JDBC Hibernate, Java Data Objects
(JDO), or other data access APIs. It enables the developer to model a
wide range of transactions on the basis of Spring’s declarative and
programmatic transaction management.
14. Spring Web Service:
Generates Web service endpoints and definitions based on Java
classes, but it is difficult to manage them in an application.
Ch - 9 Spring Boot
What is Spring Boot?
Spring Boot is an open-source Java framework used to create a Micro Service.
Spring boot is developed by Pivotal Team, and it provides a faster way to set
up and an easier, configure, and run both simple and web-based applications.
It is a combination of Spring Framework and Embedded Servers. The main goal
of Spring Boot is to reduce development, unit test, and integration test time
and in Spring Boot, there is no requirement for XML configuration.

Prerequisite of Spring Boot


Understanding of Java syntax and core concepts such as classes, objects,
inheritance, interfaces, and exception handling
Basic understanding of the Spring framework
Knowledge of Web Technologies
Ch – Fine Grained Authorization
What is Fine-Grained Authorization?

FGA allows you to set up detailed access controls that specify


who can do what and under which conditions.
In this tutorial, you will learn how to implement fine-grained
authorization in Java and Spring Boot using Permit.io.

Setting Up the E-commerce Application


To set up the e-commerce application and git clone the source
code.

git clone https://github.com/tyaga001/java-


spring-fine-grained-auth.git

💡
Then open the code in your Java IDE. I used JetBrains for all my
work.
Installing Permit package SDK
To install the Permit package SDK, you add the SDK under the
dependencies block in the build.graddle file.

## Dependencies

To set up the necessary dependencies for your


Spring Boot project, include the following in your

`build.gradle` file:

```groovy
dependencies {
implementation
'org.springframework.boot:spring-boot-starter-
web'
implementation 'org.springdoc:springdoc-
openapi-starter-webmvc-ui:2.3.0'
developmentOnly
'org.springframework.boot:spring-boot-devtools'
testImplementation
'org.springframework.boot:spring-boot-starter-
test'
testRuntimeOnly 'org.junit.platform:junit-
platform-launcher'
// Add this line to install the Permit.io Java SDK in your project

implementation 'io.permit:permit-sdk-
java:2.0.0'
}

Initializing the Permit SDK


You can initialize the Permit SDK Client using the code below:

package com.boostmytool.store.config;

import io.permit.sdk.Permit;
import io.permit.sdk.PermitConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration // Marks this class as a configuration class for Spring IoC


public class PermitClientConfig {

@Value("${permit.api-key}") // Inject Permit API key from application


properties

private String apiKey;


@Value("${permit.pdp-url}") // Inject Permit PDP (Policy Decision
Point) URL from application properties

private String pdpUrl;


/**
* Creates a Permit client bean with custom configuration
* @return Permit client instance
*/
@Bean
public Permit permit() {
return new Permit(

new PermitConfig.Builder( apiKey) // Initialize


PermitConfig with API key
.withPdpAddress(pdpUrl) // Set
the PDP address
.withDebugMode(true) // Enable
debug mode for detailed logging
.build()
// Build the PermitConfig object
);
}
}

Syncing Users with SDK


To start enforcing permissions, you should first sync a user to
Permit, and then assign them a role.

In the code below, the UserService class provides methods for


user login, signup, role assignment, and authorization, with
exception handling for possible errors when interacting with the
Permit API.

package com.boostmytool.store.service;

import com.boostmytool.store.exception.ForbiddenAccessException;
import com.boostmytool.store.exception.UnauthorizedException;
import io.permit.sdk.Permit;
import io.permit.sdk.api.PermitApiError;
import io.permit.sdk.api.PermitContextError;
import io.permit.sdk.enforcement.Resource;
import io.permit.sdk.enforcement.User;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service // Marks this class as a Spring service, making it a candidate for


component scanning

public class UserService { private final Permit permit;


// Constructor injection for the Permit SDK

public UserService(Permit permit) {

this. permit = permit;


}

/**
* Simulates user login by creating and returning a Permit User object.
*
* @param key User's unique key
* @return User object
*/

public Object login(String key) {


return new User.Builder(key).build();
}

/**
* Handles user signup by creating and syncing a new Permit User.
*
* @param key User's unique key
* @return Created and synced User object
*/

public User signup(String key) {

var user = new User.Builder( key).build();


try {

permit.api.users.sync(user); // Syncs the new


user with the Permit service
} catch (PermitContextError | PermitApiError | IOException e)
{

throw new RuntimeException("Failed to create user", e);


// Handles exceptions during user creation
}

return user;
}

/**
* Assigns a role to the user within the "default" environment.
*
* @param user User object to assign the role to
* @param role Role to be assigned
*/

public void assignRole(User user, String role) {


try {

permit.api.users.assignRole(user.getKey(),
role, "default"); // Assigns role in the "default" environment

} catch (PermitApiError | PermitContextError | IOException e)


{
throw new RuntimeException("Failed to assign role to user",

e); // Handles exceptions during role assignment


}
}

/**
* Checks if the user is authorized to perform a specific action on a
resource.
*
* @param user User object requesting authorization
* @param action Action to be authorized
* @param resource Resource on which the action will be performed
* @throws UnauthorizedException if user is not logged in
* @throws ForbiddenAccessException if user is denied access
*/

public void authorize(User user, String action, Resource

resource) {

if ( user == null) {
throw new UnauthorizedException("Not logged in"); //
Throws exception if user is not logged in
}
try {

permitted = permit.check(user,
var

action, resource); // Performs authorization check


if (!permitted) {
throw new ForbiddenAccessException("Access denied");
// Throws exception if access is denied
}

} catch (PermitApiError | IOException e) {


throw new RuntimeException("Failed to authorize user",

e); // Handles exceptions during authorization


}
}
}

Conclusion
This industrial training seminar has equipped me with not just
technical skills, but a profound understanding of the entire
Spring boot ecosystem. It bridges the gap between the client-
facing interface and the server-side logic, empowering me as a
Java Dev. Beyond the technical aspects, this training has
emphasized the significance of collaboration, version control,
and adhering to best practices—a combination that is
indispensable when working within a development team.
In conclusion, this Industrial Training Seminar serves as a solid
foundation for continued growth and exploration in the domain
of web development. It is not merely about mastering
technologies; it is about harnessing them to create innovative
and impactful web applications. The knowledge gained here is a
springboard into the ever-evolving field of web development,
where creativity, problem-solving, and the pursuit of excellence
are the driving forces. The integration of design, deployment,
and security measures has equipped us to build web applications
that not only meet the demands of today's digital landscape but
also thrive in it. Whether it is designing beautiful user interfaces,
building powerful backends, or securing web applications, we
now possess the tools and understanding to excel.

You might also like