0% found this document useful (0 votes)
9 views39 pages

EDu Induction

The document provides an overview of Java programming, covering its different types, software vendors, and key concepts such as Java Editions (JSE, JEE, JME), data types, and object-oriented programming principles. It discusses the Java environment, including JRE, JVM, and JDK, as well as packaging formats like JAR, WAR, and EAR. Additionally, it outlines coding practices, conditional statements, loops, and the importance of abstraction, inheritance, and interfaces in Java development.

Uploaded by

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

EDu Induction

The document provides an overview of Java programming, covering its different types, software vendors, and key concepts such as Java Editions (JSE, JEE, JME), data types, and object-oriented programming principles. It discusses the Java environment, including JRE, JVM, and JDK, as well as packaging formats like JAR, WAR, and EAR. Additionally, it outlines coding practices, conditional statements, loops, and the importance of abstraction, inheritance, and interfaces in Java development.

Uploaded by

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

2-Feb-2024--Day1

====================
java comes from diffrent vendors with different folder structure.
below are the types of java softwares.
1)Open JDK---this is from redhat company
2)Oracle JDK---this is from Oracle
3)JRocket kit----This is from Oracle weblogic

>>In java we are having 3 flavours


1)JSE/J2SE(java standard edition)---is used for designing desktop apps.
2)JEE/J2EE(java Enterprise Edition)---is used for designing web and enterprise
apps.
3)JME/J2ME(java Mobile/Micro edition)---is used for designing mobile or embeded
apps.
There is no corre java and advanced java seperatly.
>>>>Desktop app: ANy s/w which can be installed is called as desktop app.

Example: msoffice

Any app which we access thru browser is called as web app.

s/w--- system s/w and app softwares


System s/w:these s/w are essential to make your PC work. Ex: O/s
App S/w:s/w that are used for personal purpose is called as App s/w.
Example: MS office,paint,photoshop

>>>>>>>>>>>>>>>>>>>>>>>>>>
Java
------
>>java supports big data/AI.
>>if i had a new PC with O/s,will i have java in that machine?
ans) JRE

All browsers will by default powered with JRE.


JRE---java runtime Environment
JVM--Java virtual machine
JIT Compiler---Just intime compiler
JDK--java devlopment Kit

JDK provides necessary tools to write/compile code.

jdk is not JVM.

javac Hellow.java
java Hellow

javac is a tool to compile java code.


javac/java is part of bin folder.

Open notepad
write the codesave the file with "classname.java"
save it

machine language means 0,1


Byte code is a combination of 1,0 and some special symbols generated by JVM.
Example:

Hellow.java------>compile----->Run the code


javac java
Running the java code will be taken care by JVM.

JVM will convert byte code to machine code.

After compiling java code,we will get class file.

>using decompiler tool,we can convert class file(byte code) to source code.
Note: decompilers are not allowed in all organizations.
Decompiler tool is not part of jdk,it is 3rd part tool.

Source code: code written by developer.


Byte code:Byte code is a combination of 1,0 and some special symbols generated by
JVM.
Machine code: 0,1

JVM is part of JRE


---------------------------------------------
Architecture neutrality:

windows--all windows o/s will work on windows architecture (win32 api calls)
Linux---all linux flavours used kernel mode and linux architecture
mac---macintosh arch
Sunsolaris....etc

Java slogan---WODA---Write once deploy anywhere

bytecode--can run on

loader is a s/w program whose job is to load ur class to memory.


Application Loader:loads the classes that are part of app.
Bootstrap Loader: loads core java classes which are predefined that are required
for JVM to function.
Extension loader: loads third party classes or extensions

In java,if any thing starts with "native" that indicates that function/class is
written in other language ie c or C++.

Garbage Collector: GC. GC job is reallocate/remove unwanted/unused objects from


heap memory.

java doent support Garbage values.Java doesnt support pointers explicitly.It uses
internally for memory allocation..
C and C++ there is Garbage value concept,because it supports pointers.
=====================================
winzip----compress files and folders.

like above

in java when we want share code we can share in below formats.


1)jar--java archive-----desktop apps and web apps
technologies: springboot,core java,Swing,AWT
2)war--web archieve----webapp
technologies:spring MVC,springboot,servlets,jsp
3)ear---enterprise archieve----enterprise apps
technologies: EJB

jar consists of class files and config files.


war consists of html,css,js,servlets/jsp and config files
ear--consists of ejb classes and necessary config files

jar/war/ear is called as packaging in java.

to create jar or war or ear,we can use jar command.

in projects,we use MAVEN to create packaging.Gradle

>maven is inbuilt in Eclipse.


=============================================
Datatypes
---------

2,3--integer
3.12---float
srinivaskolaparthi---varchar
+---operator

datatype: datatype specifies the type of that that we need to use.

any thing which you declare within a block is called AS LOCAL and it can be
accessible only within that block.
{
}---unnamed Block

add()
{
//idf we
}----named block

//global variable can be accessed from any block.

datatype variablename;

; is called as terminator in Java.

always within a block local variables will have more priority than global.

comments:

single line comments: //


Multiline Comments: /*
*/
----Always Classname first letter shld be Upper case.
In relatime,default is not allowed.We shld not create any java class in default
package.it is strictly not allowed in any organizations.
>>package means it is a folder.
by default if we define any varaible with decimal point,it will be "double".

2.345

\n---new line character


i want to store a paragraph?

------------>Rules
1)In a single java program we can have any no of classes.
2)In a single java program we can have only one public class.
3)Alwyas filename and public class name shld be same.
4)i can have class with in a class ie nested classes.
5)we cannt use static in front of a class.only public ,abstract and final are
allowed for a class.
6)A class casn be private and static only in the case of inner classes.
7)A public class shld have main method for sure
8) We shld not write the code outside the class.

i/p:Java Fullstack
expected o/p: jAVA fULLSTACK

Always we recommend you to use predefined API.because these are tested and proved.

>>In java main accepts some parameters which are of type string array
if we want to pass some input to main method ,we can do it via command line
arguments.

>>>>Static:
-Static is no way releated to Objects.
-static contents are loaded first and then non static.
-Always main method shld be static.
static contents are loaded first--VVIP
Non static are loaded when you creat Object,otherwise not--economy

Static doent know anything about non-static


Non static know static contents.
>variable,method and a class can be static.But class can be static only in the case
of inner classes.
=========================================================
Day 2
-----
conditional statements
Loops

Character:

char e = 'w';

In ATMS and kiosk machines,java Internationalization feature.

>>Java supports Internationalization -i18n


>>java achived this through unicode supports.
>>>if unicode is supported by any programming language then that language also
supports i18n.
>>UNicode---Universal Code.
by default all editors supports english--ie UTF-8/ANSI.
>>in java to display some thing on to screen,we need to use character.
1 byte is sufficient to display some thing in english.But to display other than
english language,we need have 2 bytes.
So officlially,in java character occupies 2 bytes.
https://unicode.org/charts/
=================================
>>Type Casting:converting from one datatype to another type.
char e ='2';

2 types of castings.
1)Implicit: jvm will do convertion to another type on backend.
2)Explicit: developer shld write necessary logic to do conversion.

Small talk,eiffel---pure object oriented

=======================================
>>Wrapper classes:wrapper classes provides a mechanism to convert primitive to
object and vice versa.
1.5 version

in java there is primitive data type support.


>When we say object oriented ,it shld nt support primitivrs,but java supports.Later
they realease wrapper classes.

javac -target <version no> -source <version no>

int---Primitive--- Integer--wrapper-class represtation of int.


char---Character

primitive to object conversion is called as autoboxing.this is automatic ie JVM


will lookafter.
reverse is unboxing.

>>Reason why it shld be Object?


Serialization and deserialization

Observations
=============
1)USe getNumericValue() method maily for unicode characters
2)BAsed on the given data,wisely choose which wrapper class suports us to perform
casting.

>,<,>=,<=,||,&&,%,/
Conditional Statements:
=========================
if--
if-else
Switch:
--------
>switch can have any no of cases.No limit
>recommend to add default for every switch case.
>Every case shld have break.break will instruct JVM to come out of switch statement
when it reaches end of the case..
>from java 1.8 ,we can use strings even in switch.Only int values, strings or enum
variables are permitted.
>Switch within switch is possible.

>>Strings cannt be compared using ==.In javascript for deep comparision,we are
having === operator.But in java we dont.Instead we can use equals method.

We can concatinate 2 strings using "concat" function.else we can also use "+"
symbol.
Stringbuffer stringbuilder
Every Object in java will have unique no for identification like aadhar no for us.

In java to find out that unique no /address,we need to use hashcode()


hashcode is unique across objects,but it might be same only in some cases
Note: primite datatypes dont have hashcode.
in Strings there is a concept called as String literal/Constant Pool.This Pool
concept is based on hashcode techqnics.

Loops:
======

A loop is a block of code that executes repeatedly until condition fails.


1)for
2)while
3)do-while
4)for each----Collections

Eclipse----->Git---->Github---->Security OWASP Scanner-->Sonarqube(code quality


testing tool)--->Jenkins--->test server---->Docker hub--->Tomcat

Sonarqube will scan your project for duplicate code,security voilations,coding


vioalations,bugs..etc.if voilation is more than the allowed percentage,simply it
will not qllow us to move to next layer.

if any duplicate code is a found by sonarqube,it will not allow your code move to
next phase,then ultimetly code will fail.
>>>
break: it will break exceution of the loop ie it will come out of the loop.
continue:it will not come out of the loop,but it will skip the exceution of the
block for given condition.

>Nested Loop:
loop with in loop is called as Nested Loops.

Return
=======
>return is used for returning some values to called environment.
>return also will return control back to called environment.
>if we add retrun in main,u are passing controll to JVM.

final is used for declaring constants.


Rules to follow while writing class:
---------------------------------------
>always make sure variables in a class are private.
>methods shld be public.
>Classname first letter shld be upper case.
>always a functionsubstring shld start with upper case
>Always constants shld be in Upper case.A singletter canot be a constant.
>>>Always constants shld be initialized.

Java Beans(POJO)
================
>>pojos are mainly used in Spring ,Springboot and JPA frameworks.
>pojo stands for plain old java object.
>Pojo means a class with below rules and regulation.
-------
1)Pojo classses will not have main method.
2)Property shld be private and methods shld be public.
3)pojo classes shld have setters and getters for each property.
4)Pojo classes shld not implement interfaces.
5)We shld not write business or db logic in pojo.
6)Pojo classes will not have any abstract method.
7)It shld have no argument constructor.
8)static is not allowed in pojo.
9)Always pojo classes shld be in a sperate package.never keep pojo in default.

setter for pushing


getter---for pulling
=========================
Day 3
------
>>OOPS Concepts including exception handling
OOPS-Object oriented Programming Synopsis/system
>Java supports OOPS.
OOPS Concpts:
1)Inheritance
2)Polymorphism
3)Encapsulation
4)Abstraction
5)Class
6)Object
7)Message Passing

In oops,
.-entire concept is based on Object.
Class:
======
>A class is a combination of State and behaviour.
state---properties that we define in a class
behaviour--means functionality
>Electrical switch---Object
>If we are having Object ,then as per OOPS,class shld also exist.
CAR(class)----->Sports Car ---->Normal Car(Breeza,Zen,...etc)
Normal car belongs to CAR.
>ON/OFF---Properties
if ON--then switch shld work
if OFF--Power supply shld stop
>>Class comes to existence /life if we create Object in OOPS.

If object exits,then class shld also exist.


If class exist,there is no rule that Object shld exsist.But there is no use of
class with out Object.

>IN OOPS,memory for class will be allocated only if we create Object.Otherwise


there is no use of class.
>>Memory for a class will be allocated when we create Object.

Syntax for Object:

classname <referencename> = new classname();


referencename can be given any name.

>>Security:
3 types of securitie levels.
1)Code level security-----private public protected.---developer
2)App level security-------DEVOPS/IT team with developers
3)Server level Security----------DEVOPS/IT team/Hosting team

>>>When ever JVM encounters "new" in the code,that indicates it shld allocate
memory for the object.

When we create an Object,below tasks will be done by JVM.


1)Memory allocation.
2)reeference creation
3)Can call constructor
4)Can call unnamed blocks ie.. when we create an object then unnamed blocks will be
called automatically.

Note: Static blocks will be called automatically.Static is no way realated to


Object.

>>static blocks are used mainly for early loading.


we mainly use this for intilializing DB/N/w drivers in jdbc and JPA.
>>>Always non-static contents shld not be called from static directly.

Every Object in OOPS,will have "SBI".


S----state-----property that we define in a class.
B---behaviour-----functionality
I----Identity----name of the Object

Abstraction:
=============
>>Abstraction is a process of hiding the implementation details and showing only
functionalty to the end user.
To achieve abstraction in java
1)Interfaces
2)Abstract classes

Abstract method:
=================
Method without body/logic is called as abstract method.

Concrete Method: Method with body is called as Concrete Method.

Concrete Class: class with only concrete methods is called as Concret Class.

Abstract Class:
=================
>>class with only abstract methods is called as pure Abstract Class.
>>>>class with only abstract method and concrete methods is called as partial
Abstract Class.
>>we are use the keyword "abstract".
>>As there is no body for abstract methods,we cannot create Object.
>>In reality,always abstract classes shld be in a seprate package.

Interfaces shld be in separate package.


abstract classes shld be in separate package.
POJO shld be in separate package.
main class shld be in separate package.

>IF we want to implement logic for abstract methods then we need to extend that
abstract class.
>>In pure abstract classes,dont add any constructor.

>>Constructor:
==============
>A constrcutor is a member function whose name is same as Class name but without
return type.
>constrcutor wont return anything.
>constrcutor are mainly used for intilializing class level variables.
>Even void is not alloweed for Constructor.
>if we are not adding any constructor,then JVM will add default constructor at
runtime.

Overloading: Overloading means using same name multiple times but with difrrent
parameters.
>Overloading occurs within a class,not outside the class.
Rule:
While overloading makesure no 2 functions/constructor has same method signature.

Overiding: If subclass has same method as declared in Parent class ,it is called as
Overiding.

Rules for Overiding:


1)final methods cannt be overriden.
2)static methods cannt be overriden.
3)Private methods cant be overriden.
4)overriden method shld return same datatype or subtype.
5)Use access spicifier properly.
private methods will not participate in inheritance.

Cannot reduce the visibility of the inherited method from Bank.


>>>a Constructor can be public/private and even protected,but with some rules.
1)if a constrcutor is private make sure you are not using inheritance.

Interfaces:
========
An interface is similar like a class but with only abstract methods.
Rules:
>Any method that we declare in a class is by default abstract.
>Any variable that we declare in interface is by default public static final.

>>Interfaces shld be in separate package


While naming interfaces frollow below rule.
i<interfacename>

for impl,
<interfacename>Impl

Inheritance:
============
>proces of inheriting properties and behaviour from base class to child class is
called as Inheitance.
>Advantage is Code resuability.
>>IN multiple inheritance,We will come across "Diamond Problem".TO overcome that we
need to use "interfaces" in java.
OOPS inheritance is called as IS-A relationship.
rules:
1)Constructors are not inherited.
2)We cannt inherit private members.
3)Java doent support Multiple inheritance directly.
4)Static variable are not inherited.

Note: In java for evry class there is a base class called as


Object.
https://www.oodesign.com/
When we want to call base class method from child class ,we can use
SUPER keyword.
>super can be used to call super class constructor.
>always super shld be in firstlline of the block.
-------------------------------------------------------
Exception:
=============
Whenever exception arises,nornal flow of execution stops.To handle such
suitations,we need to use Exception handling.
>>Throwable>Object
>Wen u move to project,95% of the time you will deal with USER defined exceptions.
Zeta
>NullpointerException ZetaNullpointerException

>try
{
}
catch()
{
}
finally
{
}

Exceptiond are not used to stop errors.

try--catch--finally
try--finally
try---catch

throw and throws


User defined exceptions
try with try
try can be with in catch
try with in finally block
>>Rules to follow while writing exceptions.
====================================================
Day 4
------
>Checked Exception--compile time
>UnChecked Exception---runtime

>Always while displaying exceptions follow below rules.


1)display at which line exception occured.
2)package and classname of the exception.
3)User Friendly Messages.

Note: In reality,we shld avoid using System.out.println.


Instead use Log4j or sl4j tools.
>if we write 50 time System.out.print.

>If we know that code might throw the exact exception,ten never use Excception
object in catch block.

int a = 34/0;----->Arithmetic exception

String a = "Srini";
Integer.parseInt(a);-----NumberFormatException

int e[]= new int[5];


e[45]=56;//ArrayIndexOutOfBoundsException

throw---if developer want to throw an exception manually.


Rules for User defined Exceptions:
===================================
1)Always custom exceptions shld be ina separate package.
2)we need to call super class constructor in custom exception class.
3)We shld add only user friendly messages ,while displaying.
ALwya we need to extend Exception class.

how do JVM recognize which exception was throwed from which class,method,lineno?

printStackTrace has inbult mechanism to display values on to screen.

Use throws if you dont want to handle exception manually thru try and catch.

finally block---irrespective of the condition,any thing that we declare in finally


block will be executed.

Example": Db connection,N/w connection objects closing shld be done in finnally


block.

finally
{
}

Static Imports: 1.5 version

drawback: no readability,leads to more confusion

>>If a variable can hold only single value ,then it is called as Scalar type.

Array is a reference datatype.


int,float,double primitive datatpes
>>In Array we can store similar values.
>Java provides us one predefined class callled as Arrays.
array a ,b

i want to copy data from a to b?

Arrays.copy

Arrays cannot grow., because if size is fixed.We cannt add diffrent trypes of
value.

To overcome arrays challenges,we got collections into the market.


>in java collections are part of util package.

Advanatges
--------------
>collectionsara similar like array but it can grow and shrink.
>In collections we can store diffrent types of values.
>java provides diffrent collection interfaces.
List--ArrayList and Vector
Map
Set

>When we want to use a particular collection for a project,we need to identify


right collection based on below parameters.
1)Ordering
2)Allows Null values
3)Allow duplicates
4)is it Thread Safe

Req:

I want to store multiple values with no limit.while inserting it shld allows even
duplicates.

Note: Always use Objects in collections.ie insert only Objects.Because collections


were designed for Objects not for primitive datatypes.

>>toArray--is used to convert vector to array.


addALL----

using add method,we can insert only 1 element.


using addALL method,we can insert collection at a time.
>>Collections shuffle,rotate..methods will work only for List and its
implementation classes.
>>Collection will be resized automatically,if it exceeds the limit.ie it can grow.
>Vector obj1 = new Vector();

suppose we want to restrict vector to accept on ly specific datatype.Then we need


to use Generics/templates.

Generaics will make your collection type-safe.


<>
>>ArrayList:
==============
>order is maintained.
>From collection to display data,java had given different ways.
1)Loops
2)Iterator
3)Enumerator
4)for each
>Arraylist maintains insertion order.
====================================================================Set Interface:
================
>>By default all collections in java implements serializable and Cloneable.
>>HashSet:
>default capacity: 16
>default load factor is 0.75 ie 75%
>set doent allow duplicates.lf we try to insert duplicates,simply it discards
duplicate value.It will nevr throw error messages.
>Insertion order is not maintained.
Null is allowed.
>>Is not thread safe.
>Stream was introduced from Java 8
>We canview rStream API methods even from ns like filter,predicate...etc,

When hashset will be resized?


sol)capacity as 16 and load factor as 0.75 ie 75% of capacity
which means whenevr a new value is added to hashset,its size is checked against
loadfactor and if size exceeds load factor then only it will go for resizing.
s
capacity=10
load fator =75%--best metric

what is 75% in 10.currently ur hashset size is 4 elemnts,5th ,6th 7th?


Note: resizing is tedious job for JVM ie heavy weight operation.
>In projects,either architects or customer will decide the load fator and capacity.
TreeSet:
==========>
>Treeset is not syncronized.
>will not allow null element.
>maintains ascending order.

wherever u see any colletion with tree,that indicates will display elements in
ascending order and null is not allowed.

>>>Clone might throw and exception.So,based the logic which we are writing,some
time we need to surrender the code with try-catch.

Hashtable:
===========
>doesnt allow null key or value.
>default initial capacity (11) and load factor (0.75).
>It is thread safe.

HashMap:
=========
>>>default initial capacity (11) and load factor (0.75).
>It is not thread safe.
>allows null values.
>>can have only 1 null key and 1 null value.
ComputeIFpresent/absent-----Java8 lambda ,Functional interfaces and Stream API

TreeMap:
=========
>>maintains ascending order.
>It is not thread safe.
>no null keys and values.If inserted it will throw NULLPOINTER Exception.
>>Treemap uses Navigablemap for sorting the elements in collections.So try to avoid
null in collections.
>In treemap,always makesure all keys are of similar types.Otherwise
it will lead to ClassCastException.

Note: As null leads to more issues in projects,it may lead to app crash also.To get
ride of these problems,Oracle had released "Optional" feature in java8.
Optional class will check whether object is empty or not.

2)Nullpointer exceptions if not handled carefully in servers,it might lead to


server crash.

We can pass collection as a value.


==========>
assume there is an array with 6 elements ie {bat,rat,cat,mat,TV,Laptop}.
Deisgn a hashmap whose values are same as array element value and whose keys are
index no in hashmap.

2)Assume there is a hashtable with below values.


Srinivas,srinivas,laptop,Laptop,Edu,Tech.Design code which shld display index of
duplicate values(pls ignore case).

3)create an program,which will display


latitude and longitude based on cityname.
Use Map .
---------------------------------------------------
Hyderabad,Mumbai,Chennai,Calcutta,Bihar
i/p:Hyderabad
o/p: lat:25.096073 & long: 19
------------------------------------------------------
JDBC:
=====
flat file--->Excel--->Dbase2---->Dbase3---->Access---->Oracle--->mysql........etc

Indian Army---->Dbase2---->Dbase3---->Access

Driver: Driver is a S/w Program.

Java Program------------------------------->Database

directly?No

we need a translator ie driver.


for interacting with bckend,oracle had released JDBC into the market.

ODBC---open db connectivity---odbc was designed in C/C++.So platform


dependent.These drivers can be used only fro windows.
specially designed for microsoft products only.

if u want java app to connect to Excel,MS Access db,notepad.

JDBC---Java db connectivity---Java----Independent--jdbc will work on any o/s.

java program---------->insert data to db----->Mysql

via JDBC Drivers

jdbc drivers are of 4 types.


1)JDBC-ODBC Bridge Driver---removed from java8
2)Native API driver(partially java driver)

disadvantage:
We need to install native driver in each machine.

3)Network Protocol driver(full java driver)


drawback:maintainance cost is very high.
developer sld write more code.
Performance wise it is slow

4)Thin driver(full java driver)---this is used in Development


o>performamce is v good.
>No need to install any software on machines.
disadvanatge:
we need configure db specific driver either in maven or build path.

>There is no universal drivers for JDBC ie for databases.


====================
java --Oracle comp
Database---Oracle,Mysql,tDb2,Sybase......etc

Differnt dataabses,different approaches.

>>From java8,jdbc-odbc driver support was totally removed.


To deisgn a JDBC program,we need to know JDBC API.
-----------------------------------------------------
Steps to Connect to Database from Java App:
========================================

Whene we want to establish connection to db using driver,then we need to provide


dbname,db portno,db username,db password.

>after authentication,a db session will be established between app and db.


>If session is not established transactions or operations cannt be performed
between app and db.
> signout means invalidating sessi on with server.same operation we need to
perform while doing JDBC operations.

--->
Large Object datatypes:

large object size will vary from db to db.

1)Blob:binary large object----images,audio,video-- 4gb


2)Clob: character large object---pdf,document---2 gb
3)NClob: n no of clob object

create table linkedin(username char(100),password char(100),resume clob);

>>JDBC supports large objects.


example:one jdbc program to store an image and retrive an image.
==========================================================
ResultSet object/collection which can hold ur data temporarily.
Always connection closing shld be done in finally block.
CRUD
C-create
R--select
U-Update
D-delete
Code for driver is available under connector.
Class.forName--will load ur driver class object into memory.
DriverManager Class will establish connection with db based on meta data that we
provide.
executeQuery---when we want to retrive data from db.ie select
executeUpdate---when we want to perform insert,update and delete.
above methods are part of Statement interface.

com.mysql.jdbc.Driver--- for mysql version 5.x and 6.x


com.mysql.cj.jdbc.Driver--- for mysql version 8.x
>Never display passwords in plaintext.if we provide in plain text,it is a security
breach.

It leads to code injection.We need to add passwords in encrypted format.


>>for this we can use the tool "VAULT".
https://developer.hashicorp.com/vault
>>Till now,we had executed create,update operations on static data.But what if i
want to give the data as a input?

In jdbc,Statement,PreparedStatement and CallableStatement.


PreparedStatement:
======================
>can be used for giving input at runtime.
>Preparedstatement can be used to avoid SQL injections.
>it helps to avoid app crashes because of improper usage of escape characters.
>In terms of performance of executing the query,these are faster.
wherever we want to insert data at runtime there use the Symbol ?.

In java there date package.


=====================
App Name: Abcd Bank

if a person wants to open a new bank account,


he need to provide some details.Assume all details are there.

Design a program like menu app,


which shld allow to
1)open new account
2)Modify the Personal details.
3)if balance <100,it shld throw "Less balance Message"
4)if he tries to close the account within 60 days of opening the acoount,it shld
throw a exeception msg "You are not allowed to close account ".
5)display acount info,based on accountno.
jan30 2024

current date--- 27-Feb-2024


--------------------------------------------------
Java,java.util.Date and java.sql.Date
jdbc:mysql

jdbc is called as main protocol


mysql is called as sub protocol.

sub protocol will change based on database.

>create table profile(name char(200),photopic blob);

>To call PLSQL components from JDBC,we need to Use CallableStatements.

DELIMITER &&
>>CREATE or replace PROCEDURE myprocedure()
BEGIN
SELECT * FROM employee WHERE empid=101;

END &&

>>Procedure wont return any thing.Only functions will return values.

Note: CallableStatement.execute() will return true,if it returns Resultset


object,otherwise false.

>>In the above example procedure is just returning single string not a resultset,so
it is execute method returns false.
======================================
MultiThreading
---------------
>>Multithreading means ability to perform multiple jobs/tasks at a time
simultaneously.
>Job means a task that we need to complete.
>Parents they perfom multitasking.

To work on multithreading,we need below:


1)We need a Process
2)enough Memory
3)Processor (high end processsor)
if processor is of low end or old one then it might not support multithreading.

O/s----Parent Process
JVM---Child Process
Programs that we are run are ---Threads
>>To create a Thread ,first we need to have process.
Without process,we cannt create Thread.
>Threads uses the memory of Process.

Parent---->Process
Child------>Thread
>Java supports only multithreading but not multiprocessing.
>If you want to work on multiprocessing,we can go with Python.

>Every java Program is a Thread to JVM.


>>To work on Multithreading in java First we need to know Thread Lifecycle.
>thread is independent.ie threads can work independently without depending on other
threads.
?>IN java,to create a Thread,we are having 2 ways.

1)extending Thread class


2)implementing Runnable interface

>Any thread that we create will have a name and id.


>Who will give that name and id?
ans)JVM

Every process will have PID--process id


Threadid
>No process-ids can be same.
>We can also priorities for Threads to run.
>Even though if 2 thread are having same,it cannt have same id.
>We cannt set threadid manually.Only JVM will do that.
>We can also set priority for threads as well.
1--MIN Priority
5--Normal priority
10--MAX Priority

Based on priority threads will run.


>>It is changing based on available memory and CPU.
Whoc takes the responsibilit of running the thread lifcecycle in JVM?
ans)In JVM there is a component called as Thread

Thread.sleep:
===============
>>if we want to hault the threadfor some given time then sleep is used.
>if the time is completed then it will continue from where it left.
Thread.sleep(long mls)

>if one thread completes then only another thread shld start?
ans) LOcking mechanism
mutex
semaphores

>>sleep will not perform locking mechanism at all.


Locking mechanisms are applicable only for OBject.
>If we want to perform Locking on thread,then we need tto use OBject class thread
methods like notify,notify all,wait and Synchronize blocks.
>join:
When a join is invoked,the current thread stops its execution and thread goes to
wait state.

>A dead thread cannot be restarted.


>A thread which is temporarily stoped can be restarted use start() method.

Note: try to avoid using stop() method.It leads to memory/CPU issues.

>Threads will be killed automatically,once program execution is completed.


>start/run/join/sleep/stop
>>Join it is not using any locking.it is using lifecycle.

To use notify and wait,we need to use syncronized blocks.


>Thru wait and notify we can achive locking.
>>wait(): The wait() method is used to make a thread voluntarily give up its lock
on an object, allowing another thread to execute code within a synchronized block.
The thread that calls wait() will enter a waiting state until another thread calls
notify() or notifyAll() on the same object, allowing it to resume execution.

notify(): The notify() method wakes up one of the waiting threads on the same
object. If multiple threads are waiting, it is not specified which one will be
awakened. The awakened thread will then compete for the lock on the object.
---------------
The general syntax of using the wait() method for synchronization is shown below.
synchronized(object)
{
while(condition is false)
{
object.wait();

//do the task


}
>>
=======================================================
Vault will do encryption of any text ie sensitive data.
>Vault is part of security tools in Devops.
DAEMON Thread in java?
ans) DAEMON threads are the threads which run on background.
DAEMON thread----disk and execution monitor thread
>we can also make a thread as daemon thread.
i want to perform processing tasking,then do i need to go with foreground or
background?
ans)background

when we deal with os threds and server threads we will use daemon threads.

Transaction?

int a= 1;

a++;

if thread1 thread2 thread3 tries to modify a?


then will happend? it leads to inconsitencies ie Dirty read occur.

Here a is called as Shared Variable.

Shared variable/resource:if multiple threads are trying to access same variable and
trying to perform some operations,then that resource is called shared resource.

Example: Printer in a ORganization

Synchronized blocks.
====================

Syntax:
Synchronize(resourcename){
}

The above issues that we stated above can be handled via ld Synchronize block.
>Synchronize shld be used as combination with wait and notify.
>Synchronize block make sure only one thread is accessing the resoiurce at same
time.If another thread tries to modify then it will not allow because Synchronize
block will have a lock mechanism.

notify and wait

ATM
5 Threads---tx
t1 t2 t3 t4 t5
t1 after the operation he will notify t2.
t2 after the tx ,he will notify t3.
if t1 is doing tx,then t2t3t4t5 shld be in waitiing state.

notify is used to notify single thread.


notifyAll is used to notify all threads that are in waiting condition.
Threads that ar waiting will be in Thread Queue.

Which methods in Thread will have locks?


notify,wait or notifyAll
true---resource is in use
false---resource is free.
---------------------------------------
Serialization and Deserialization
==================================
Serialization : process of saving state,behaviour and identity of an object into a
file or db is called as serialization.

Deserialization: process of restoring the object to previous state is called as


deserialization.

Rules:

1)Only non static data memebrs are saved thru serialization.


2)static contents cannt be serialized.
3)transcient variables cannt be serialized.
4)Constructor of an object is never called when an object is deserialized.

>In java We need to use Fileoutputstream and ObjectOutputstream.

Use case: mainly in networking and Gaming apps.


===========================
java8
-------------
new features
1)Lambda expressions
2)Stream API for Big data
3)Method reference---::shld be used with lambda expression
4)Functional interfaces(SAM single abstract method): an interface with only one
abstract method is called as functional interface.
We can have static and default methods as well.

To declare functional interface we need to use @FunctionalInterface annotation.

@FunctionalInterface //annotation
interface SamExample1 {
void display();
}

interface SamExample4 {//this not SAM


void display();
void display1();
}
5)enhancements in JDBC
6)static methodsin interfaces: till jdk1.7 we cant have static methods in java.But
from jdk1.8 we can also write static methods.
7)default method in functional interfaces
8)Optional

lambda+static method+functional interfaces

When we work on Big data,we need to work on structured and unstructured data.Some
time we need to perform some computations.

To perform these computations,java8 came up with lambda functions.

lambda shld be used as a combination with functional interfaces or Stream API.

Java8,they released enhanced Loop called as ForEach.


Lambda Expression:
()->

drawback: No readability
For small operations dont use lambda.
56 new features
Advanced java or Microservices
==================================================================
Spring
========
prereq:
===========
Java: jdk1.8
Eclipse for Spring
Springboot: Jdk1.8,Eclipse/Spring STS
Apache Maven/Gradle is mandetory
>mainly developer shld know what is configuration files?

Maven:
=======
Before Maven there is a tool called as "ANT"
ANT>>>>MAven>>>>>Gradle(faster)
>>Gradle is new to market.Already majority companys are using maven from last 8
years.
>>Gradle internallyy uses maven repo.
>Maven is a build tool.
>in maven dependency means a jar file.
Advantages:
1)we can build the project.
2)It can handle dependencies.
3)Handle transtive dependencies.
4)we can perform packaging of project into jar/ear/war.
5)Can install plugins that are required for Project.
......etc

Disadvantages: Performance is slow.

Maven versions comes in 2 flavours:


>>maven 1.x---outdated
>>maven 2.x
>>maven 3.x
>>Maven has its own public repo.https://mvnrepository.com/

Any 3rd party dependencies that are needed for the project can be handled by
MAVEN.Maven after reading pom.xml files,it will start downloding the dependencies
from internet.
>>Maven first checks local repository before downloading the dependency from
internet.Assume dependency is not available in local repo,then it will download
dependencies from public repo.

Local repo: repo that was created and available in our PC.
local repo name is ".m2".
Public repo: repo that is on cloud for public use.Anybody can access public repos.
Corporate repo: repo that were created for an organization for development ;for
internal use is called as Corporate repo.
>To create a corporate we need to use below tool.
Jfrog artifactory,Sonatype Nexus
>>Always corporate repo are more secure.

Public repo are not secure becase they are public.

groupid means package name


artifcatid means project name.
>Every dependency will have artifact id and groupid.
>Maven has 2 config files.
1)POM.xml
2)settings.xml

----i/p---->Maven
pom.xml
>When we run the maven project,maven wwill first read pom.xml file.
>we shld have only 1 pom.xml file per a normal project.
>Only in the case of Multi-module projects we can have multiple pom.xml
files.
>Multi-module projects are used only for Microservices Development.
>>
settings.xml file is used for entire workspace.
Pom.xml file used for Project.
worskpace--30 project----30
In setting.xml we are going to configure below
1)Local repo path
2)Proxy server details.
3)Corporate repo data.these are more secure.
4)profiling will also be handled
5)Plugin management
>Corporate repo will be created by Devops team.
>>Who will create .m2?
ans)Maven

How many local repo?


ans)1

Assume ther is no maven,then develooper shld donwload dependencies manually and he


need to add to build path.This is a tedious job.

How do u differenciate between maven and normal project?

ans)In project if we see pom.xml file then it is maven project.

Can we convert normal java project to maven project?


ans) Yes

Can we disable maven in maven project?


ans) Yes

Transitive dependencies:
======================== means whenever parent dependencies are loaded then child
dependencies shld be loaded,if not loaded project build will fail.
>MAven will take necessary care to get of child dependency issues in maven.
>Maven can also create a project from scracth.this feature is called as
SCAFFOLDING.

>Some time maven settings are good,and pom.xml is free from errors.
But still i am getting errors?
sol)do force update
===============================================
Spring:
https://spring.io/
>>Spring is an application framework and IOC container for Java.
>Spring is a group of projects or modules.
>Out of these modules to design any app using Spring,we shld be clear in
fundamentals of "Dependency injection" basics.

>>Where we will use Spring?


ans)Using Spring we can design below types of apps.
1)Cloud
2)Microservices
3)Servelerless
4)Reactive
5)Eventdriven
6)Webapp
7)Batch

<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

TO design any Spring Core App,we need to have below files.


1)POJO class/Java Bean(minimum 1 or max any no)
2)Testclass
3)applicationcontext.xml(1 or some times based on requiremnt we can create any no)
4)pom.xml(only 1)---for dependencies

Like core java, in spring we are having Spring Core.


>Spring core concepts are basic concepts to design Springboot and Spring MVC apps.

Spring works on the principle of Dependency Injection.

>>Injecting something to a boy.

Who is injecting? doctor----injecting is done by developer via


applicationxontext.xml file
To whom theya re injecting?boy---Constructor injection
Purpose? to get ride of infections----loose coupling
source/device?sireen---------Spring IOC Container

in spring,how do we know whther app is working as per expectation?Using Testclass

Spring is mainy used to reduce tight coupling between the classes or code.

tight coupling---more dependency


loose coupling---less/no dependency

Assssume there is a class A and B.

A cannt exist without B,then A is tightly coupled with B.

If tightly coupled,below are the problems


1)infuture if we change code in B,then it will effect A class.

Assssume there is a class A ,C, B.

C class can execute evenwihtout A,B---loose coupled

drawback with Tightcoupling:


1)Unnecessarily we need to disturb code.
2)More Tests shld be conducted whether code is working as per expectation.
3)We cant add new features to existing code easily.
4)There might be integrity issues in future.

>>To achive same,we need to use Dependency Injection stratagies.


>To implement or run Dependency Injection,we need IOC(inversion of control)
container.

Example for Tight Coupling?


Types of Dependency Injection stratagies?
Ways to write configurations in Spring?

Spring Core: 6.1.4--not stable

Spring 3.x,5.x,6.x

>Spring is full of configurations.

In S/w to write configurations,we need to below styles.


1)Xml---slow in terms of performance.beacuse parsing will take more time.xml wont
support collections.
2)JSON--faster that XML
3)Bson---More faster than Bson
4)YAML or YML---Universal acceptor.supports collections

In Spring to write config,we can use any of below:


xml
yaml
Annotations: Annotations are part of java.
>Always xml files shld be in src/main/resources.

Tight coupling Example:


======================
To perform dependency injection we can do it using Constructors or methods.

>I can initiialize class level variables thru constructors.

id in bean tag is used to diffrenciate between bean tags.

>>We are initlializing class variables thru constructor injection via


application.xml.

>>For Spring core app,execution starts from main method.


>>spring core is like nuts and bolts to deisgn an app.
>>Configuration file name can be any valid name.Better to use the below name:
applicationContext.xml
ClassPathResource will load ur xml file into memory for execution.
>>XmlBeanFactory class will create Objects and it will intilialize objects for pojo
classes based on the xml file.

Spring Bean Lifecycle:

ioc Container starts-->BEAN INITIALIZED--->dEPENDENCIES WILL BE INJECTED----->INIT


METHOD WILL BE CALLED BY CONTAINER---->UTILTITY METHODS WILL BE CALLED---->DESTROY
METHOD WILL BE CALLED at the end automatically by IOC conatiner.
Annotations--- no need to use any XML files.

To run the Spring app,spring provides ur 2 types of containers.


1)Application context
2)Beanfactory

>to run java app----JVM


>to run Spring app---JVM+IOC container
>Spring Web app-------JVM+IOC+Web server
-------------------------------------------
Setter Injection:
======================
>Spring supports following collections.
1)List
2)set
3)map

Rules to follow while writing Setter and Constructor Injections:


========================
1)POJO classes shld be in seprate class and testclass shld be in separate package.
2)If we use both constructor and setter injection at a time in java code,IOC
container will use only setter injection.

In short,setter injection overrides Constructor injection.


3)Partial injection of the properties can be done through setter injection,but the
same is not possible thru Constructor injection.
AutoWiring:
============
>This is important feature when we want to implement layered architecture in Spring
/Springboot App.
>in projects we will design code using Layered architecture.
Writing huge xml file is tedious job.
>at 11am feb 29th, class B----a,b,c,d,e,f
on March 9th,b propertie

>what if spring performs these above mappings automatically?


As spring is handling these mappings,developer can reduce the xml instructions in
xml file.but remeber xml file is mandetory.
===================================================================
>>Auto works for objects and class.
Disadvantage: Developer will not have any control on code.ie a new person into the
team he cant understand code.
Autowiring can be used or not applicable for primitive datatypes and string value.

>>By default autowiring internally uses setter injection.


Modes is autowiring:
====================
1)no--default
2)byName
3)byType
4)constructor
5)Autodetect
>>><dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
==============>
mojo error--->Maven issue---we need to add maven plugin in pom.xml
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
</plugins>

>>Spring MVC
-------------
>>MVC--model view controller
>>Spring mVC is used for designing web apps.
>>JSP andn servlets are server side technologies to design webapps.
In MVC we are having 2 types of architectures.
MVC1---JSP acts as controller
MVC2---Servlet will acta as controller

>Spring MVC follows MVC2 architecture.


https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/
html/mvc.html

M---model contains data of the appliction.


Controllers job is to control the flow of traffic.
>>In spring MVC, controller is also called as "Dispatcher serverlet" or "front
controller".

Moving from one menu/page to another menu/page is called as Routing.


>>view--JSp/html page
viewresolver is predefined.

prefix means folder path of jsp


suffix means its extension.

>As soon as we run any spring MVC app,it will automatically load/run startup file
which is index.jsp.

Web.xml------Dispatcher servlet---Per project only 1


index.jsp----html code
src/main/java---controller code
pom.xml---dependencs needed
spring-servlet.xml----viewresolver code

Dispatcher servlet is main controller.it shld be only 1.dispatcheer servlet is


configured in web.xml file.

We can have as many child controllers.


>The DispatcherServlet handles all the HTTP requests and responses.

After receiving an HTTP request, the DispatcherServlet consults the HandlerMapping


to call the appropriate Controller.

The Controller takes the request, calls the appropriate method, and builds the
model and returns the view page name to the DispatcherServlet.

The DispatcherServlet will then take help from the ViewResolver to pick up the
defined view page for the request.

Once the view is finalized, the DispatcherServlet passes the model data to the
view, which is finally rendered on the browser.

@Controller---This is an indication to IOC container the current class is


controller.
@Controller shld be used before class not before method.
==================>
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
>>How do IOC container recognize controller?
ans)@Controller

Hpw do IOC knows the location of contrroller ie which package and its address?
sol) thru component-scanning

Component-scanning will scann the entire code and will identify controllers.
>>
Component Scanning
Annotation
5 to6 years back ago,we need to write huge xml files for sharing meta data with
server or JVM.
To overcome these problems,Oracle had released Annotations into the market.

Annotation are alternative to XML.


Annotations starts with '@'.Annotations provides necesaary metadata to JVM.

Annotations are of 2 types.


1)predefined
2)Userdefined
>In MVC we are going to use web MVC annotations.

@Controller----IOC can understand that the current class is a controller.


>><mvc:annotation-driven/>---provides metadata to JVM
Mote: Never test any web app in Eclipse browser.

SpringMVC
==========================
Spring AOP and validations
------>
Springboot
==========
>>IDE: Spring STS---heavy weight than eclipse
Eclipse--lightweight when we compare with STS
>>Spring STS--4.x--3.x---wont support 8.x version.
Theia IDE
>>>https://spring.io/quickstart
Drawbacks of Spring:
==================
1)One of the Common Maven problem is Dispatcher servlet not found issue.--can be
overcomed using Autoconfig feature in springboot
2)Writing more config files.---very less config files
3)we need to configure server ie tomcat.---Embedded/inbuilt server
4)If we use spring for deisgning Cloud and Microservices app,code size will
drastically increase.---less no of lines of code
5)writing huge xml files.---no xml file except pom.xml
6)Profling is a manually approach.---using @Profile we can complete
7)Learning curve is very high.----less learning
8)No developer tools like autorestart/reload----Springboot has inbuilt tools
----------
Springboot 3.x version
>>TO design springboot app,we can go with the below ways.
1)Springboot CLI
2)Spring STS/Eclipse
3)MAven/Gradle
4)Using Spring initializer.https://start.spring.io/

Note: All above 3 approaches uses 4 approach internally.

Always try to avoid SNAPSHOT versions in development.

spring init --dependencies=web,data-jpa my-project


spring init --build=maven --java-version=17 --dependencies=websocket --
packaging=war sample-app.zip
=======================
>>Springboot has only 1 configuration file through wwe can control or add features
to the app.

application.properties or application.yaml

propereties file will be in src/main/resources.


>Properties is a collection were data will be in key and value format.
>in application.properties,keys are predefined and values are user defined.
>
In spring/Springboot,while creating packages we need to follow below rule.If
violated controlled cannt be identified by Dispatcher sevlet.

com.hughes
.hughes.controller

Port rule:

port no cannt start with 0.


Because of security concerns,some orgs wont allow you to use
ports which starts with 1,2,3,4,5.
1,2,3,4,5,6

Suggested is 8

>>Going forward dont use localhost.use ur ipaddress

"not secure"---that means no ssl certificate.


---->
In Spring/Springboot,to perform webpage validations we can use the below.
1)Hibernate validator
2)JSR(java specification requirement) Validator

Get----@GetMApping
put----@PutMApping
Post---@PostMapping
delete---@DeleteMapping
or
@RequestMapping
@Controller
@SpringBootApplication
>>>>>
Observations:
web.xml is not created
spring-servlet.xml--not created
we just added springstarter web dependency.
We didnt added spring core and spring web separetly.
>>Why wee added jasper separetly in pom.xml?
to run servlet we need Catalina jar
to run jsp programs we need Jasper jar.
>>Here tomcat is inbuilt.We dint configured anything for tomcat.

Note:tomcat is embedded.
what if i want weblogic server in my springboot?Is it inbuilt?
ans)No.weblogic not inbuilt.
Only tomcat,jetty,netty,undertow
Also commercial servers are not inbuilt in springboot.
...Example: Pramathi server...
=====================================================
@SpringBootApplication:
-----------------------
How do springboot recognize your controller/Service/Repository? it will scan the
entire project,component:scan
How spring spring is config dispatcher servlet?
who loaded beans into IOC container?
In Spring,@Controller,@Service,@Repository,@Component are called as Stereotype
annotations/types.

for all the above questions?


@SpringBootApplication=@Configuration+@ComponentScan+@EnableAutoConfiguration
@ComponentScan==it will scan ur packages and subpackages and registers the bean
with IOC container.

>>We didnt configured dispatcher servlet in any file in springboot.In the case of
springboot beacuse of "AutoConfiguration" feature,based on the starter it will
recognize the type of dependency and will perfrom necssary actions with developer
involvement.

Autoconfig will work based on the starter that we give in pom.xml.

@Configuration:In spring we can write configurations in the form of class.Whatever


we wrote in spring-servlet.xml,the same can be written in classes and Object way.

@Service---in this layer we are going to write Business logic.


@Controller----Controller logic and view related
@Repository----DAO classes that interact with database

DAO: DAO stands for data access Object.A DAO class is a class with only CRUD
operations.
>DAO is also a design pattern.

In spring ,we are calling asd Dependency


In springboot,we call dependency as "STARTER".

redis server---->Spring-boot-starter-redis
mongo----Spring-boot-starter-mongo`

>>Commandline runner:
=======================
SpringApplication.run===command line runner.
The main use of the above command is
1)it will start the Application
2)Initializes and configures beans,properties and app context.
3)Commandline runner methods will be executed.
4)After 1,2,3 steps the app will start working.
---------------------------------------------------------
6-MArch-2024
SpringBoot AOP
Spring Security
Unit testing in Spring
mappings in springboot
=========================
SpringBoot JDBC
WebServices Introduction
Springboot Restfull services
Connection Pooling and Datasources
JPA Introduction and Sample App
------------------------>>>
Springboot Layered Architecture+JDBC(connection pooling)
Spring JDBC vs SpringBoot JDBC:
1)In spring JDbc we need to write more xml files and config files,but in springboot
jdbc no xml files.
2)in spring jdbc we need to add multiple dependencies,but in springbootjdbc,we need
to add only one starter Spring-boot-starter-jdbc.
We are opening the connection and we are closing connection in jdbc.but if we go
with Spring boot/spring jdbc,no need to close connection manually.There is
autoclosing feature.
>>It can exceptions automatically.
>>Springboot JDBC uses "Connection pooling mechanism",but normal jdbc wont use the
same.
>>springboot jdbc is built on JDBC.

If we want to perform CRUD operations on Db using Spring boot,below are the ways.
1)Springboot JDbc
2)Springboot + ORM
3)Springboot + Hibernate
4)AOP

Connection pooling mechanism:


=============================
DataSource: datasource means any thing that emits data/origin point for data.

Connection pooling: pooling means group of connection objects.

Assume if somebody is giving that object and we are reusing it?

Shubham: Bhuvaneswar----Vizg

Thru car?

is there any rule that shubham shld purchasee new car to go to vizag
or will he hire a car
rent:u will get a car on hourly basic---rent

MAruthi cars--swift---9am 1pm----9pm to 1am--9am

car---db object
car garrage/car agency------database
After his travel he will handover car to that car agency--amount

Connection pooling is a pool of readymade db connection objects which are


maintained by Connection pooling providers and db vendors.On request one db
connection object will given to us and after the usage we will handover that object
back to Provider.

Note:Connection pooling feature will be dependent on the type of database that you
were using.

requester------request db obejct----------------->Databse+connection pool provider


-------------will grant db connection
requester will use that object
After usage he will handover that object back to db connection pool provider

Case 2: if requester is not using the db object for some time,that db object will
be automatically handed back to db.

srinivas had 2 cars--car1 car2 he uses car1 most frequently


Car2 for evry 3 months.

srinivas is loosing.srinivas got suggestion from Rahul.y dont u give to ola or uber
for rent.so that u can generate money.
In connection Pool ,we are going to have pool of readymade db objects.
how many db objects?
ans)it depends on available memory on server,Database and Processor

Connection pool mechanism can be achieved using below 3rd party library.
1)DBCP
2)C3PO
3)Hikari connection Pooling---market
leader(https://github.com/brettwooldridge/HikariCP)
4)Server side connection pooling---Webserver/App server

CommandlineRunner :
======================
>Commandlinerunner is an interface in spring boot.
>It has only one abstract method "run".
>When a class implements this interface,springboot will automatically call run
method.
>>This interface is used for db initlialization at starting of the app,or if u want
to perform startup activities then we are going to use this.
>>This commandline runner will run ur code after springbootbeans intilializing and
loading is completed.

SpringBoot Restfull Services


=============================
>Java is not language independent,it is platform independent.
>To achieve language independency in java,w3c along with Sun microsystems had come
up with solution called as "WEBSERVICES".
>>Webservices client-server architecture.
>to make communication between 2 diffrent apps which were designed using differnt
programming languages,we use webservices.
>>webservices will transfer the data between 2 machines using XML.
>As xml is heavy weight ,now evrybody is using JSON.
>>Webservices are of 2 types.
1)SOAP---xml--heavy weight---more secure(all legacy services are in soap)
2)REST---xml/json---light weight----less secure
>>rest worrks on http/https protocl.
>We can use SOAP for mobile apps.All mobile apps uses RESt services only as it is
light weight and it uses JSON.
>>Restfull services can be created using any:
1)Groovy
2)Scala
3)Spring Restfull
4)SpringBoot rest
5)Jersy
6)RestEasy fw 7)Python django rest....etc

web services we will have 2 actors


1)Publishers/producer
2)consumers

SpringBoot rest+Reactjs
reactjs/Angular---consumer
Producer----Springboot rest
SOAP---SOapUI tool for consuming
>>A consumer can be an app,webservice,browser.
3rd party agents: postman/rest IDE

@Controller-----MVC
Springboot rest----
@RestController-----Restfull services
@RequestMapping
@Post---@PostMapping
@Get----@GetMApping
@delete---@DeleteMapping
>>Springboot gives one inbuilt database called as h2.
h2 shld be used for training and POC purpose.Dont use this production
environements.
mem--datasource name/inmemory

jdbc:h2:mem:training
>>>>>>>>>>>JPA----Java Persistance API
Springboot+JDBC
Springboot+ JPA
@RequestBody
@ResponseBody
anything that we get from server is called as response.

Post----->we are pushing data to database thru body.


>>JPA removes unnecessary writing of code.

JPA repository
>>JPA advantages
Vendors---Hibernate is implementor of JPA
ORM---object relation Mapping

>>>Springboot JDBC

write springboot jdbc code for below operations

aadhar no
citizen name
citizen mobileno
Addresss
Income
State

CRUD Operations
==========================================================
try {
connection = DriverManager.getConnection(jdbcURL, username, password);

Statement statement = connection.createStatement();

statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email1',


'pass1', 'Name 1')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email2',
'pass2', 'Name 2')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email3',
'pass3', 'Name 3')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email4',
'pass4', 'Name 4')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email5',
'pass5', 'Name 5')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email6',
'pass6', 'Name 6')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email7',
'pass7', 'Name 7')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email8',
'pass8', 'Name 8')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email9',
'pass9', 'Name 9')");
statement.addBatch("INSERT INTO users (email, pass, name) VALUES ('email0',
'pass0', 'Name10')");

int[] updateCounts = statement.executeBatch();

for (int count : updateCounts) {


System.out.println(count);
}

connection.close();

} catch (SQLException ex) {


ex.printStackTrace();
}
=============
Login Screen---Html,bootstrapjs,css,javascript

Spring provides us form validations feature.

Validations are of 2 types


1)client side/browser side validation
2)Server side validations

Spring provides below to perform client side validations.


1)Spring validations
2)JSR validations--javax.validation---https://beanvalidation.org/
3)Hibernate validation--org.hibernate

====================
Springboot development tools:
=============================
n>LiveReload-- to use live reload on browser we need to install live relaod plugin
on browser.
Drawback with live reload: Browser wil crash most frequently.
https://chromewebstore.google.com/detail/livereload/
jnihajbhpnppcggbcgedagnkighmdlei?pli=1
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
to springboot Projects pom.xml file.
>>Remote debugging
>Remote Update or restart
===========================================
Testing:
-----------------

Testing can be performed in 2 ways.


1)Manual testing
2)Automation testing(example: selenium)
>>To check for vulnarabilities
>>To check defects.
>to check whther we had got expected output
>To design quality product we need to do testing.
In java,to perform testing we can below frameworks/tools.
1)Junit(java unit testing framework)
2)Mockito
3)Power mock
>>JUnit basics

Junit+Mockito
Versions: Junit4 and Junit5

>>In testing,we will 2 parameters.

expected output actual output


Always expected and actual shld be same
>>To perform above we need to use Assertions in junit.
>>Testcasess will have 2 states
1)Green-----Success
2)RED----failure

in project do we need to use 100% succes intesting?


ans)min 85%

>>>I want to test a functionality whether the function is executing with in 1000ms.
>>how do test whether dbconnection is established with in lesstime in jdbc?

>>If we want to make junti to ignore a particular test case from running,simply use
@Ignore.

>>To perform unittesting of controller,service and repository we can use


springboot-starter-test.
>springboot-starter-test internally uses Junit to perform unit testing.
-------------------------------------
JPA
====
>>JPA is a specification.
Tools like Hibernate,Toplink uses JPA specifications.
>>Using JPA we can reduce no of lines of code fr CRUD operations.
>>is SQL independent or dependent?
ans) SQL is db dependent.
>SQl queries will vary from db to db.Then it will be difficult for a devloper to
write code for different databses.---JPA had come up with one solution JQL/JPQL--
java persistance Query language
>>JQL queries are independent.JQL queries looks like SQl,but it will run on any db.
>>IN Jpa no need to close any DB connections manually.
>>JPA Provides ORM feature.
>>JPA provides mappings between tables
>JPA provides algorithms for primary key genrations.

ORM:Object relation mapping

JPA----auto dll feature

it will convert POjo class to table and table to POjo class.


@Entity
@Table
class Empployee
{
private int no;
private String name;
} ------------------converted to table Employee---no name

Reverse engineering---table to class conversion--? yes

ORM Relationships----one to one


One to many
many to one

SpringBoot Security:
==============================
Springboot starter security---add in pom.xml.
>security features in Spring boot will be enabled for ur app.
Springboot gives so many features for security using less no of lines of code.
1)As soon as we add security dependecny springboot will perform autoconfiguration
and will enable security.
2)
features:1)filters---Antisamy filters,OWASP filters
2)Oauth1.0
3)Oauth2.0-mostly used
4)LDAP
5)SAML
6)JSON token---mostly used
7)Kerberos
8)in-memory login credentials

1,2,3,4,5,6,7,8++++are used for Autherntication and authrorization in Springboot


9)Http based authentication---basic for testing and training
10)Easy integrate Springboot with 3rd party security tools.

Spring AOP introduction:


========================
>>AOP stands for Aspect orient programming.
>AOP for modularity and middleware services.
Middleware services/cross cutting concerns.:
========================================
tx management
Connection pool
Logging
Security.....etc
---------------
Aspect:this is class where we are going to write cross cutting concerns.
Advice:What action shld be taken.
joinpoint:When to apply concerns in the program
pointcut:Expression for Advice ie where to apply advice

Example:
mod1
mod2
mod3
mod4
mod5
Customter asked u to insert logging at mod3.

You might also like