You are on page 1of 175

Mbuya

§ The following are the organizations that are using Java and they need good Java
Programmers:
§ EGA
§ TRA

§ TAMISEMI
§ LATRA
§ ATCL

§ TRC
§ Ministry of Finance and Planning
§ Object Oriented − In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.
§ Platform Independent − Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
§ Simple − Java is designed to be easy to learn. If you understand the
basic concept of OOP Java, it would be easy to master.
§ Secure − With Java's secure feature it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
§ Architecture-neutral − Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
§ Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in
ANSI C with a clean portability boundary, which is a POSIX subset.
§ Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
§ Multithreaded − With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
§ Interpreted − Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.
§ High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
§ Distributed − Java is designed for the distributed environment of the internet.
§ Dynamic − Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
§ Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.
§ Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
§ Methods − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.
§ Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
§ Polymorphism
§ Inheritance
§ Encapsulation
§ Abstraction
§ Classes
§ Objects
§ Instance
§ Method
§ Message Passing
§ Local variables − Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
§ Instance variables − Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.
§ Class variables − Class variables are variables declared within a class, outside
any method, with the static keyword
§ A constructor is a function that creates and initializes an object
§ It has the same name as its class and is syntactically similar to a method.
However, constructors have no explicit return type.
§ Typically, you will use a constructor to give initial values to the instance
variables defined by the class, or to perform any other start-up procedures
required to create a fully formed object.
§ All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member
variables to zero. However, once you define your own constructor, the default
constructor is no longer used.
class ClassName {
ClassName() {
}
}
1. No argument Constructors
2. Parameterized Constructors
§ As the name specifies the no argument constructors of Java does not
accept any parameters instead, using these constructors the instance
variables of a method will be initialized with fixed values for all objects.
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}
§ Most often, you will need a constructor that accepts one or more parameters.
§ Parameters are added to a constructor in the same way that they are added to
a method, just declare them inside the parentheses after the constructor's
name.
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}

}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
§ An object is created from a class.
§ In Java, the new keyword is used to create new objects.
§ There are three steps when creating an object from a class −
§ Declaration − A variable declaration with a variable name with an object type.
§ Instantiation − The 'new' keyword is used to create the object.
§ Initialization − The 'new' keyword is followed by a call to a constructor.
§ This call initializes the new object.
§ Instance variables and methods are accessed via created objects.
§ To access an instance variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName; /*

Now you can call a class method as follows */


ObjectReference.MethodName();
These rules are essential when declaring classes, import statements
and package statements in a source file.
1. There can be only one public class per source file.
2. A source file can have multiple non-public classes.
3. The public class name should be the name of the source file as well
which should be appended by .java at the end. For example: the class
name is public class Employee{} then the source file should be as
Employee.java.
4. If the class is defined inside a package, then the package statement should
be the first statement in the source file.
5. If import statements are present, then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the source
file.
6. Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.
1. Primitive Data Types - ( int, char,float,double,boolean,string)
2. Reference/Object Data Types - are created using defined constructors of the classes.
§ Local variables
§ Instance variables
§ Class/Static variables
§ Local variables are declared in methods, constructors, or blocks.
§ Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor, or
block.
§ Access modifiers cannot be used for local variables.
§ Local variables are visible only within the declared method, constructor, or
block.
§ Local variables are implemented at stack level internally.
§ There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
public class Results {
public void stdGpa() {
int gpa = 0;
gpa = gpa + 3.1;
System.out.println(”Student GPA is : " + gpa);
}
public static void main(String args[]) {
Results results = new Results();
results.stdGpa();
}
}
§ Instance variables are declared in a class, but outside a method, constructor
or any block.
§ When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
§ Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
§ Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must
be present throughout the class.
§ Instance variables can be declared in class level before or after use.
§ Access modifiers can be given for instance variables.
§ The instance variables are visible for all methods, constructors and block in
the class. Normally, it is recommended to make these variables private (access
level). However, visibility for subclasses can be given for these variables with
the use of access modifiers.
§ Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned
during the declaration or within the constructor.
§ Instance variables can be accessed directly by calling the variable name inside
the class. However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified
name. ObjectReference.VariableName.
§ Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
§ There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
§ Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
§ Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
§ Static variables are created when the program starts and destroyed when the
program stops.
§ Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
§ Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally, values can be assigned in special static
initializer blocks.
§ Static variables can be accessed by calling with the class name ClassName.VariableName.

§ When declaring class variables as public static final, then variable names (constants) are all in
upper case. If the static variables are not public and final, the naming syntax is the same as
instance and local variables.
public class Employee {
// salary variable is a private
static variable private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
WARM UP
§ For our case study, we will be creating two classes. They are Students and
StudentsTest.
§ First open notepad and add the following code.
§ Remember this is the Students class and the class is a public class. Now, save
this source file with the name Students.java.
§ The Students class has four instance variables - name, age, programme and
semester.
§ The class has one explicitly defined constructor, which takes a parameter.
§ The static keyword in Java is used for memory management mainly.
§ We can apply static keyword with variables, methods, blocks and nested
classes.
§ The static keyword belongs to the class than an instance of the class.
The static can be:
i. Variable (also known as a class variable)
ii. Method (also known as a class method)
iii. Block
iv. Nested class
§ If you declare any variable as static, it is known as a static variable.
§ The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
§ The static variable gets memory only once in the class area at the time of class loading.
§ Is used to initialize the static data member.
§ It is executed before the main method at the time of classloading.

class A2{
static{System.out.println("static block ");}
public static void main(String args[]){
System.out.println("Hello main");
}
§
§ There can be a lot of usage of Java this keyword.
§ In Java, this is a reference variable that refers to the current object.
Here is given the 6 usage of java this keyword.
i. this can be used to refer current class instance variable.
ii. this can be used to invoke current class method (implicitly)
iii. this() can be used to invoke current class constructor.
iv. this can be passed as an argument in the method call.
v. this can be passed as argument in the constructor call.
vi. this can be used to return the current class instance from the method.
Warm UP level 1
1. John has a total of 80 marbles. He wants to divide them equally among his 4 friends. Write
a Java program to calculate how many marbles each friend will get. 2.5marks
2. A car rental company charges a base rate of $30 per day plus an additional $0.15 per mile
driven. Write a Java program to calculate the total rental cost for a car if it was driven for 5
days and 400 miles. 2.5marks
3. A farmer wants to fence off a rectangular area to keep her chickens in. She has 200 feet of
fencing material available and wants to maximize the area of the enclosure. Write a Java
program to calculate the dimensions of the enclosure that will maximize its area. 2.5 marks
Warm UP level 1
1. A store is offering a 20% discount on all items. Write a program code to calculate the
discounted price of an item, given its original price. 2.5marks
2. A car is traveling at a speed of 60 km/hr. Write a program code to convert this speed to
miles per hour.. 2.5marks
3. A worker earns Tsh 15 per hour for the first 40 hours of work in a week, and $22.50 per
hour for any additional hours worked. Write a program code to calculate the worker's
weekly pay, given the number of hours worked.. 2.5 marks
4. A bank charges a penalty of Tsh20 if a customer's account balance falls below $100. Write a
program code to calculate the net balance after deducting any penalty, given the account
balance. 2.5 marks
5. A company pays its employees a bonus of Tsh500 if their sales for the month are over
Tsh10,000. Write a program code to calculate the employee's total pay, given their sales for
the month.
Warm UP level 1
1. A store sells items at a discount of 5% if the customer buys more than 10 items. Write a
program code to calculate the discounted price, given the number of items purchased and
their price.. 2.5marks
2. A person wants to invest Tsh10,000 in a savings account, which earns 2% interest per year.
Write a program code to calculate the balance after 5 years 2.5marks
Warm UP level 1
1. Bob wants to convert his temperature in Celsius to Fahrenheit. Write a Java program code
to take input from the user for temperature in Celsius and output the equivalent
temperature in Fahrenheit. 2.5marks
2. A group of friends decides to go on a road trip. They need to calculate the total cost of fuel
for the trip. Write a Java program code to take input from the user for the distance
traveled, cost of fuel per liter, and average mileage of the car, and output the total cost of
fuel for the trip. 2.5marks
3. A grocery store wants to calculate the bill for a customer. Write a Java program code to
take input from the user for the price and quantity of each item purchased, calculate the
total bill amount, and output the final bill with applicable taxes. Consider that the tax rate
is 10% of the total bill amount. 2.5 marks
§ Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
§ It is an important part of OOPs (Object Oriented programming system).
§ The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
§ Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
1. For Method Overriding (so runtime polymorphism can be achieved).
2. For Code Reusability.
Terms used in Inheritance
§ Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
§ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
§ Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
§ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
class Subclass-name extends Superclass-name
{
//methods and fields
}
§ A class which is inherited is called a parent or superclass, and the new class is called child or
subclass.
class Employee{
float salary=200000;
}
class Programmer extends Employee{
int bonus=50000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
§ On the basis of class, there can be three types of inheritance in java:
1. Single
2. Multilevel
3. Hierarchical.
§ In java programming, multiple and hybrid inheritance is supported through interface only.
§
§ When a class inherits another class, it is known as a single inheritance.
§ In the example given below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
§ When there is a chain of inheritance, it is known as multilevel inheritance.
§ As you can see in the example given below, BabyDog class inherits the Dog class which again
inherits the
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
§ Animal class, so there is a multilevel inheritance.
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
§ When two or more classes inherits a single class, it is known as hierarchical inheritance.

§ In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
§ is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to
a child class object.
§ Any Java object that can pass more than one IS-A test is considered to be
polymorphic.
§ In Java, all Java objects are polymorphic since any object will pass the IS-A test
for their own type and for the class Object.
§ It is important to know that the only possible way to access an object is
through a reference variable.
§ A reference variable can be of only one type. Once declared, the type of a
reference variable cannot be changed.
§ The reference variable can be reassigned to other objects provided that it is
not declared final. The type of the reference variable would determine the
methods that it can invoke on the object.
§ A reference variable can refer to any object of its declared type or any
subtype of its declared type.
§ A reference variable can be declared as a class or interface type.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
§ Now, the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above examples −
§ A Deer IS-A Animal
§ A Deer IS-A Vegetarian
§ A Deer IS-A Deer
§ A Deer IS-A Object
§ When we apply the reference variable facts to a Deer object reference, the
following declarations are legal −
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
§ All the reference variables d, a, v, o refer to the same Deer object in the
heap.
§ If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
§ Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
§ Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
§ No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we
will learn it later.

Why can we not override static method?


§ It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
Can we override java main method?
§
No. Method Overloading Method Overriding
1) Method overloading is used to Method overriding is used to provide
increase the readability of the the specific implementation of the
program. method that is already provided by
its super class.

2) Method overloading is Method overriding occurs in two


performed within class. classes that have IS-A (inheritance)
relationship.
Method overloading is the example Method overriding is the example
of compile time polymorphism. of run time polymorphism.

In java, method overloading can't Return type must be same or


be performed by changing return covariant in method overriding.
type of the method only. Return
type can be same or different in
method overloading. But you must
have to change the parameter.
super
§ The super keyword in Java is a reference variable which is used to
refer immediate parent class object.
§ Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super
reference variable.
Usage of Java super Keyword
§ super can be used to refer immediate parent class instance
variable.
§ super can be used to invoke immediate parent class method.
§ super() can be used to invoke immediate parent class constructor.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
final
§ The final keyword in java is used to restrict the user.
§ The java final keyword can be used in many context.
Final can be:
1. variable
2. method
3. class
final
§ The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized
final variable.
§ It can be initialized in the constructor only.
§ The blank final variable can be static also which will be initialized in
the static block only.
§ We will have detailed learning of these.
§ Let's first learn the basics of final keyword.
final
§ if you make any variable as final, you cannot change the value of
final variable(It will be constant).
§ Example of final variable
§ There is a final variable speedlimit, we are going to change the
value of this variable, but It can't be changed because final variable
once assigned a value can never be changed.
class Bike{
final int speedlimit=80;//final variable
void run(){
speedlimit=300;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}//end of class
final
§ If you make any method as final, you cannot override it.

class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
final
§ If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
final
§ A static final variable that is not initialized at the time of declaration is
known as static blank final variable.
§ It can be initialized only in static block.
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
Runtime
§ Runtime polymorphism or Dynamic Method Dispatch is a process
in which a call to an overridden method is resolved at runtime
rather than compile-time.
§ In this process, an overridden method is called through the
reference variable of a superclass. The determination of the
method to be called is based on the object being referred to by the
reference variable.
1. Upcasting
Occurs when the reference variable of Parent class refers to the object of
Child class
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
Abstraction
§ Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
§ Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you type the text and
send the message. You don't know the internal processing about the
message delivery.
§ Abstraction lets you focus on what the object does instead of how it
does it.
§ There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract
§ A class which is declared with the abstract keyword is known as an
abstract class in Java.
§ It can have abstract and non-abstract methods (method with the
body).
Abstract
§ An abstract class must be declared with an abstract keyword.
§ It can have abstract and non-abstract methods.
§ It cannot be instantiated.
§ It can have constructors and static methods also.
§ It can have final methods which will force the subclass not to
change the body of the method.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Interface
§ An interface in Java is a blueprint of a class. It has static constants
and abstract methods.
§ The interface in Java is a mechanism to achieve abstraction.
§ There can be only abstract methods in the Java interface, not
method body.
§ It is used to achieve abstraction and multiple inheritance in Java.
interface
§ It is used to achieve abstraction.
§ By interface, we can support the functionality of multiple
inheritance.
§ It can be used to achieve loose coupling.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
§ If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
inheritance
§ A class implements an interface, but one interface extends another
interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
THREAT MODELING
§ Threat modeling works to identify, communicate, and understand
threats and mitigations within the context of protecting something
of value.
§ A threat model is a structured representation of all the information
that affects the security of an application. In essence, it is a view of
the application and its environment through the lens of security.
§ Threat modeling can be applied to a wide range of things, including
software, applications, systems, networks, distributed systems,
Internet of Things (IoT) devices, and business processes.
§ Description of the subject to be modeled
§ Assumptions that can be checked or challenged in the future as
the threat landscape changes
§ Potential threats to the system
§ Actions that can be taken to mitigate each threat
§ A way of validating the model and threats, and verification of
success of actions taken
THREAT MODELING
§ Threat modeling is a process for capturing, organizing, and
analyzing all of this information.
§ Applied to software, it enables informed decision-making about
application security risks.
§ In addition to producing a model, typical threat modeling efforts
also produce a prioritized list of security improvements to the
concept, requirements, design, or implementation of an
application.
OBJECTIVES OF THREAT MODELING
§ Threat modeling is a family of activities for improving security by
identifying threats, and then defining countermeasures to prevent,
or mitigate the effects of, threats to the system.
§ A threat is a potential or actual undesirable event that may be
malicious (such as DoS attack) or incidental (failure of a Storage
Device).
§ Threat modeling is a planned activity for identifying and assessing
application threats and vulnerabilities.
§
Threat modeling across the lifecycle
§ Threat modeling is best applied continuously throughout a
software development project. The process is essentially the same
at different levels of abstraction, although the information gets
more and more granular throughout the lifecycle.
§ Ideally, a high-level threat model should be defined early on in the
concept or planning phase, and then refined throughout the
lifecycle.
§ As more details are added to the system, new attack vectors are
created and exposed.
§ The ongoing threat modeling process should examine, diagnose,
and address these threats.
§ It is a natural part of refining a system for new threats to be
exposed.
§ For example, when you select a particular technology – such as
Java for example – you take on the responsibility of identifying the
new threats that are created by that choice.
§ Even implementation choices such as using regular expressions for
validation can introduce potential new threats to deal with.
Updating threat models is advisable after events such as:
1. A new feature is released
2. Security incident occurs
3. Architectural or infrastructure changes
Threat modeling: Four question
framework
§ The following four question framework can help to organize threat
modeling:
1. What are we working on?
2. What can go wrong?
3. What are we going to do about it?
4. Did we do a good job?
Threat modeling:
§ Attempting to evaluate all the possible combinations of threat agent, attack,
vulnerability, and impact is often a waste of time and effort. It is helpful to
refine the search space in order to determine which possible threats to focus
on.
§ Assess Scope - What are we working on? This might be as small as a sprint, or
as large as a whole system.
§ Identify what can go wrong - This can be as simple as a brainstorm, or as
structured as using STRIDE, Kill Chains, or Attack Trees.
§ Identify countermeasures or manage risk - Decide what you’re going to do
about each threat. That might be to implement a mitigation, or to apply the
accept/transfer/eliminate approaches of risk management.
§ Assess your work - Did you do a good enough job for the system at hand?
Structured Threat Modeling Process
§ Threat modeling looks at a system from a potential attacker’s
perspective, as opposed to a defender’s viewpoint. Making threat
modeling a core component of your SDLC can help increase
product security.
§ The threat modeling process can be decomposed into three high
level steps.
§ Each step is documented as it is carried out. The resulting
document is the threat model for the application.
§ The first step in the threat modeling process is concerned with gaining
an understanding of the application and how it interacts with external
entities.
This involves:
1. Creating use cases to understand how the application is used.
2. Identifying entry points to see where a potential attacker could
interact with the application.
3. Identifying assets, i.e. items or areas that the attacker would be
interested in.
4. Identifying trust levels that represent the access rights that the
application will grant to external entities.
§ This information is documented in a resulting Threat Model
document.
§ It is also used to produce data flow diagrams (DFDs) for the
application.
§ The DFDs show the different paths through the system,
highlighting the privilege boundaries.
§ Critical to the identification of threats is using a threat categorization
methodology.
§ A threat categorization such as STRIDE can be used, or the Application
Security Frame (ASF) that defines threat categories such as Auditing &
Logging, Authentication, Authorization, Configuration Management,
Data Protection in Storage and Transit, Data Validation, and Exception
Management.
§ The goal of the threat categorization is to help identify threats both
from the attacker (STRIDE) and the defensive perspective (ASF).
§ DFDs produced in step 1 help to identify the potential threat targets
from the attacker’s perspective, such as data sources, processes, data
flows, and interactions with users.
§ These threats can be classified further as the roots for threat trees;
there is one tree for each threat goal.
§ From the defensive perspective, ASF categorization helps to identify the
threats as weaknesses of security controls for such threats.
§ Common threat lists with examples can help in the identification of such
threats.
§ Use and abuse cases can illustrate how existing protective measures
could be bypassed, or where a lack of such protection exists.
§ The determination of the security risk for each threat can be made using
a value-based risk model such as DREAD, or a less subjective qualitative
risk model based upon general risk factors (e.g. likelihood and impact).
§ STRIDE is a model for identifying computer security threats developed
by Microsoft.
§ It provides a mnemonic for security threats in six categories.
The threats are:
1. Spoofing
2. Tampering
3. Repudiation
4. Information disclosure (privacy breach or data leak)
5. Denial of service
6. Elevation of privilege
§ The STRIDE was initially created as part of the process of threat
modeling. STRIDE is a model of threats, used to help reason and
find threats to a system.
§ It is used in conjunction with a model of the target system that can
be constructed in parallel. This includes a full breakdown of
processes, data stores, data flows, and trust boundaries.
§ Today it is often used by security experts to help answer the
question "what can go wrong in this system we're working on?"
§ Each threat is a violation of a desirable property for a system:

Threat Desired property

Spoofing Authenticity

Tampering Integrity

Repudiation Non-repudiability

Information disclosure Confidentiality

Denial of service Availability

Elevation of privilege Authorization


Step 3: Determine Countermeasures
And Mitigation
§ A vulnerability may be mitigated with the implementation of a
countermeasure. Such countermeasures can be identified using
threat-countermeasure mapping lists. Once a risk ranking is
assigned to the threats in step 2, it is possible to sort threats from
the highest to the lowest risk and prioritize mitigation efforts.
§ The risk mitigation strategy might involve evaluating these threats
from the business impact they pose.
Step 3: Determine Countermeasures
And Mitigation
§ Once the possible impact is identified, options for addressing the
risk include:
§ Accept: decide that the business impact is acceptable
§ Eliminate: remove components that make the vulnerability
possible
§ Mitigate: add checks or controls that reduce the risk impact, or the
chances of its occurrence
§ The following sections examine these steps in depth and provide
examples of the resulting threat model in a structured format.
1.Decompose the Application
§ The goal of this step is to gain an understanding of the application
and how it interacts with external entities. This goal is achieved by
information gathering and documentation.
§ The information gathering process is carried out using a clearly
defined structure, which ensures the correct information is
collected.
2.Threat Model Information
§ Information identifying the threat model typically includes the the
following:
1. Application Name: The name of the application examined.
2. Application Version: The version of the application examined.
3. Description: A high level description of the application.
4. Document Owner: The owner of the threat modeling document.
5. Participants: The participants involved in the threat modeling process
for this application.
6. Reviewer: The reviewer(s) of the threat model.
Example:Threat Model Information
§ Threat Model Information
§ Application Version: 1.0
§ Description: The college library website is the first implementation of a website to
provide librarians and library patrons (students and college staff) with online services.
As this is the first implementation of the website, the functionality will be limited.
There will be three users of the application:
§ Students
§ Staff
§ Librarians
§ Staff and students will be able to log in and search for books, and staff members can
request books. Librarians will be able to log in, add books, add users, and search for
books.
§ Document Owner: KEVIN
§ Participants: KEVIN
§ Reviewer: KEVIN
3.External Dependencies
§ External dependencies are items external to the code of the
application that may pose a threat to the application.
§ These items are typically still within the control of the organization,
but possibly not within the control of the development team.
§ The first area to consider when investigating external
dependencies is the production environment and requirements.
§ It is useful to understand how the application is or is not intended
to be run.
External Dependencies Should Be
Documented As Follows:
§ ID: A unique ID assigned to the external dependency.
§ Description: A textual description of the external
dependency.
External Dependencies
ID Description

The college library website will run on a Linux server running Apache. This server
1 will be hardened per the college’s server hardening standard. This includes the
installation of the latest operating system and application security patches.

The database server will be MySQL and it will run on a Linux server. This server
2 will be hardened per the college’s server hardening standard. This will include
the installation of the latest operating system and application security patches.

3
The connection between the web server and the database server will be over a
private network.

4 The web server is behind a firewall and the only communication available is TLS.
Entry Points
§ Entry points define the interfaces through which potential
attackers can interact with the application or supply it with data.
§ In order for a potential attacker to attack an application, entry
points must exist. Entry points in an application can be layered.
§ For example, each web page in a web application may contain
multiple entry points.
§ Entry points show where data enters the system (i.e. input fields,
methods) and exit points are where it leaves the system (i.e.
dynamic output, methods), respectively.
§ Entry and exit points define a trust boundary
Entry Points
§ Entry points should be documented as follows:
§ ID: A unique ID assigned to the entry point. This will be used to cross-
reference the entry point with any threats or vulnerabilities that are
identified. In the case of layered entry points, a major.minor notation
should be used.
§ Name: A descriptive name identifying the entry point and its purpose.
§ Description: A textual description detailing the interaction or processing
that occurs at the entry point.
§ Trust Levels: The level of access required at the entry point. These will
be cross-referenced with the trust levels defined later in the document
ENTRY POINTS
ID Name Description Trust Levels

(1) Anonymous Web User


The college library website will be only be (2) User with Valid Login
accessible via TLS. All pages within the Credentials
1 HTTPS Port
college library website are layered on this (3) User with Invalid Login
entry point. Credentials
(4) Librarian

(1) Anonymous Web User


(2) User with Valid Login
Library Main The splash page for the college library Credentials
1.1
Page website is the entry point for all users. (3) User with Invalid Login
Credentials
(4) Librarian
(1) Anonymous
Web User
Students, faculty members and (2) User with
librarians must log in to the college Login Credentials
1.2 Login Page
library website before they can (3) User with
carry out any of the use cases. Invalid Login
Credentials
(4) Librarian

(2) User with


Valid Login
The login function accepts user Credentials
1.2. Login
supplied credentials and compares (3) User with
1 Function
them with those in the database. Invalid Login
Credentials
(4) Librarian

(2) User with


EXIT POINTS
§ Exit points might prove useful when attacking the client: for example, cross-
site-scripting vulnerabilities and information disclosure vulnerabilities both
require an exit point for the attack to complete.
§ In the case of exit points from components handling confidential data (e.g.
data access components), exit points lacking security controls to protect
confidentiality and integrity can lead to disclosure of such confidential
information to an unauthorized user.
§ In many cases threats enabled by exit points are related to the threats of the
corresponding entry point. In the login example, error messages returned to
the user via the exit point (the log in page) might allow for entry point attacks,
such as account harvesting (e.g. username not found), or SQL injection (e.g.
SQL exception errors).
Assets
§ The system must have something that the attacker is interested in;
these items or areas of interest are defined as assets.
§ Assets are essentially targets for attackers, i.e. they are the reason
threats will exist. Assets can be both physical assets and abstract
assets. For example, an asset of an application might be a list of
clients and their personal information; this is a physical asset. An
abstract asset might be the reputation of an organization.
Assets are documented in the threat model as follows:
§ ID: A unique ID is assigned to identify each asset. This will be used
to cross-reference the asset with any threats or vulnerabilities that
are identified.
§ Name: A descriptive name that clearly identifies the asset.
§ Description: A textual description of what the asset is and why it
needs to be protected.
§ Trust Levels: The level of access required to access the entry point
is documented here. These will be cross-referenced with the trust
levels defined in the next step.
ID Name Description Trust Levels

Assets relating to
Library Users and students, faculty
1
Librarian members, and
librarians.

(2) User with Valid


Login Credentials
(4) Librarian
The login credentials (5) Database Server
that a student or a Administrator
1.1 User Login Details faculty member will (7) web server User
use to log into the Process
College Library website. (8) Database Read
User
(9) Database
Read/Write User
Assets relating
2 System to the underlying
system.
The College Library
website should be
(5) Database
available 24 hours a
Server
Availability of College day and can be
2.1 Administrator
Library Website accessed by all
(6) Website
students, college
Administrator
faculty members,
and librarians.
Trust Levels
§ Trust levels represent the access rights that the application will
grant to external entities. The trust levels are cross-referenced with
the entry points and assets. This allows us to define the access
rights or privileges required at each entry point, and those
required to interact with each asset.
Trust levels are documented in the threat model as follows:
§ ID: A unique number is assigned to each trust level. This is used to
cross-reference the trust level with the entry points and assets.
§ Name: A descriptive name that allows you to identify the external
entities that have been granted this trust level.
§ Description: A textual description of the trust level detailing the
external entity who has been granted the trust level.
ID Name Description

A user who has connected to the college


1 Anonymous Web User library website but has not provided valid
credentials.

A user who has connected to the college


User with Valid Login
2 library website and has logged in using
Credentials
valid login credentials.

A user who has connected to the college


User with Invalid Login
3 library website and is attempting to log in
Credentials
using invalid login credentials.
§ All of the information collected allows us to accurately model the application
through the use of Data Flow Diagrams (DFDs). The DFDs will allow us to gain
a better understanding of the application by providing a visual representation
of how the application processes data.
§ Data flows show how data flows logically through the application, end to end.
They allow the identification of affected components through critical points
(e.g. data entering or leaving the system, storage of data) and the flow of
control through these components.
§ The focus of the DFDs is on how data moves through the application and what
happens to the data as it moves. DFDs are hierarchical in structure, so they
can be used to decompose the application into subsystems and lower-level
subsystems. The high-level DFD will allow us to clarify the scope of the
application being modeled. The lower level iterations will allow us to focus on
the specific processes involved when processing specific data.
§ The external entity shape is used to represent any entity outside
the application that interacts with the application via an entry
point.

EXTERNAL ENTITY
§ The process shape represents a task that handles data within the
application. The task may process the data or perform an action
based on the data.

Process
§ The process shape represents a task that handles data within the
application. The task may process the data or perform an action
based on the data.

Multiple
Process
§ The data store shape is used to represent locations where
data is stored. Data stores do not modify the data, they
only store data.

Data Store
§ The data flow shape represents data movement within the
application. The direction of the data movement is represented by
the arrow.
§ The privilege boundary (or trust boundary) shape is used to
represent the change of trust levels as the data flows through the
application. Boundaries show any location where the level of trust
changes.
THREAT MODELING METHODOLOGIES
STRIDE:
§ This is a threat modeling methodology developed by
Microsoft that stands for Spoofing, Tampering,
Repudiation, Information Disclosure, Denial of Service,
and Elevation of Privilege.
§ It helps organizations identify threats in each of these
categories and design countermeasures to mitigate them.
THREAT MODELING METHODOLOGIES
PASTA:
§ The Process for Attack Simulation and Threat Analysis (PASTA) is a
threat modeling methodology that follows a structured approach
to identify potential security threats and vulnerabilities in a system
using various techniques like data flow diagrams and vulnerability
assessments
THREAT MODELING METHODOLOGIES
DREAD:
§ This is another methodology developed by Microsoft that stands
for Damage potential, Reproducibility, Exploitability, Affected
users, and Discoverability.
§ It helps organizations prioritize threats based on the severity of
their impact and the likelihood of them occurring.
THREAT MODELING METHODOLOGIES
Trike:
§ This threat modeling methodology is based on the idea that a
threat is a function of the attack surface, the attacker skill, and the
attacker motivation.
§ It uses a structured approach that involves identifying assets,
attackers, attack vectors, and then assessing the risks associated
with each.
Web Application Attacks & Countermeasures To
Secure Web Applications

§ Web applications are becoming increasingly complex and are often


used to store and process sensitive data. As a result, they are a
prime target for attackers.
§ There are a number of different types of web application attacks,
and each one can have a significant impact on the application and
its users.
SQL injection: This attack involves injecting malicious SQL code into
a web application.
§ This can be done by entering specially crafted input into a form or
by exploiting a vulnerability in the application's code.
§ Once the malicious code is injected, it can be used to steal data
from the database or to take control of the application.
§ Cross-site scripting (XSS): This attack involves injecting malicious
JavaScript code into a web application.
§ This can be done by entering specially crafted input into a form or
by exploiting a vulnerability in the application's code.
§ Once the malicious code is injected, it can be used to steal cookies
or session tokens, to hijack user sessions, or to display malicious
content to the user.
§ Session hijacking: This attack involves stealing a user's session
token or cookie.
§ This can be done by exploiting a vulnerability in the application's
code or by tricking the user into entering their credentials on a
malicious website.
§ Once the attacker has the user's session token or cookie, they can
use it to impersonate the user and access the application's
resources.
§ Directory traversal: This attack involves exploiting a vulnerability in
the application's code to access files or directories that are not
intended to be publicly accessible.
§ This can be used to steal sensitive data, such as passwords or
credit card numbers, or to upload malicious code to the
application's server.
§ Denial of service (DoS): This attack involves flooding the
application with requests in an attempt to overwhelm the server
and make it unavailable to legitimate users.
§ This can be done by using a botnet or by exploiting a vulnerability
in the application's code.
§ When a user submits input to a web application, that input is often
used to construct an SQL query.
§ For example, if a user enters their username and password into a
login form, the application will use that information to construct an
SQL query that looks something like this:
§ SELECT * FROM users WHERE username = 'username' AND
password = 'password';
§ If an attacker can inject malicious SQL code into the input, they can
change the meaning of the query.
§ For example, the attacker could inject the following code:
' OR 1 = 1; --
§ This code will add an additional condition to the query, which will
always be true.
§ This means that the query will return all rows from the database,
regardless of the username and password that the user entered.
§ SQL injection can have a significant impact on a web application.
§ It can be used to steal data from the database, such as usernames,
passwords, credit card numbers, and other sensitive information.
§ It can also be used to take control of the application, which could
allow the attacker to do things like delete data, change settings, or
even deface the website.
Use prepared statements: Prepared statements are a way of
constructing SQL queries that prevents SQL injection attacks. When
a prepared statement is used, the application will first sanitize the
input and then use it to construct the query.
Validate input: All input submitted to a web application should be
validated to ensure that it is safe. This includes things like checking
for special characters, such as single quotes and backslashes.
Use a web application firewall (WAF): A WAF can help to protect
web applications from a variety of attacks, including SQL injection.
Prepared Statements
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root", "");
// Create a prepared statement.
PreparedStatement preparedStatement =
connection.prepareStatement("SELECT * FROM users WHERE
username = ? AND password = ?");
// Bind the parameters.
preparedStatement.setString(1, "username");
preparedStatement.setString(2, "password");
Prepared Statements
// Execute the query.
ResultSet resultSet = preparedStatement.executeQuery();
// Iterate over the results.
while (resultSet.next()) {
System.out.println(resultSet.getString("username"));
System.out.println(resultSet.getString("password"));
}
// Close the connection. connection.close();
String username = request.getParameter("username");
String password = request.getParameter("password");
// Sanitize the username and password.
username = sanitize(username);
password = sanitize(password);
WAF
§ A web application firewall (WAF) is a security appliance that
protects web applications from a variety of attacks, including cross-
site scripting (XSS), SQL injection, and denial-of-service (DoS)
attacks.
§ WAFs can be deployed in front of a web application, or they can be
integrated into the web application itself.
§ Protection from a variety of attacks: WAFs can protect web
applications from a wide range of attacks, including XSS, SQL
injection, and DoS attacks.
§ Improved performance: WAFs can help to improve the
performance of web applications by filtering out malicious
requests.
§ Reduced risk of data breaches: WAFs can help to reduce the risk of
data breaches by preventing unauthorized access to web
applications.
§ Cost: WAFs can be expensive to purchase and deploy.
§ Complexity: WAFs can be complex to configure and manage.
§ False positives: WAFs can sometimes block legitimate requests,
which can impact the performance of web applications.
§ The type of attacks you want to protect against: WAFs can protect
against a variety of attacks, so you need to choose one that is right
for your needs.
§ The size of your web application: WAFs are available for a variety
of sizes of web applications, so you need to choose one that is
right for your application.
§ Your budget: WAFs can range in price from a few hundred dollars
to several thousand dollars, so you need to choose one that fits
your budget.
§ Once you have chosen a WAF, you need to configure it to protect your
web application. This may involve specifying the types of attacks you
want to protect against, as well as the IP addresses or domains that you
want to allow or block.
§ How to deploy a WAF
§ Once the WAF is configured, you need to deploy it in front of your web
application. This may involve installing it on a physical or virtual server,
or using a cloud-based WAF service.
§ How to monitor a WAF
§ Once the WAF is deployed, you need to monitor it to ensure that it is
working properly. This may involve checking the WAF's logs for any
blocked requests, as well as reviewing the WAF's configuration to make
sure it is still accurate.
§ Containers are a popular way to deploy and manage software
applications.
§ They offer a number of advantages over traditional deployment
methods, such as increased portability, scalability, and efficiency.
What are Containers?
§ Containers are lightweight, standalone, executable packages of
software that include everything needed to run an application:
code, runtime, system tools, system libraries and settings.
Container images become containers at runtime and in the case of
Docker containers – images become containers when they run on
Docker Engine.
§ There are many reasons to use containers in software
development, including:
§ Portability: Containers can be run on any platform that supports
Docker Engine, which makes them ideal for deploying applications
in the cloud.
§ Scalability: Containers can be easily scaled up or down to meet
demand, which can help to save money on infrastructure costs.
§ Efficiency: Containers share the underlying operating system,
which can help to improve resource utilization and reduce costs.
§ There are a number of ways to use containers in software
development, including:
§ Docker: Docker is the most popular container platform. It provides
a number of tools and services that make it easy to build, deploy,
and manage containers.
§ Kubernetes: Kubernetes is an open-source container orchestration
platform. It can be used to automate the deployment, scaling, and
management of containerized applications.
§ Increased portability: Containers can be run on any platform that
supports Docker Engine, which makes them ideal for deploying
applications in the cloud.
§ Scalability: Containers can be easily scaled up or down to meet
demand, which can help to save money on infrastructure costs.
§ Efficiency: Containers share the underlying operating system, which can
help to improve resource utilization and reduce costs.
§ Reduced complexity: Containers can help to reduce the complexity of
software development by providing a standardized way to deploy and
manage applications.
§ Improved security: Containers can help to improve the security of
software applications by isolating them from each other and from the
underlying operating system.
§ Docker is a containerization platform that allows you to package
and run applications in isolated environments called containers.
§ Containers are lightweight and portable, making them easy to
deploy and manage.
§ Docker is a popular choice for developers and IT professionals who
want to build, deploy, and manage containerized applications.
§
§ Increased portability: Containers can be easily moved from one
environment to another, making it easy to deploy applications on
different platforms.
§ Improved performance: Containers share the host operating
system's kernel, which can improve performance over traditional
virtualization technologies that require each virtual machine to
have its own kernel.
§ Reduced resource usage: Containers use less resources than
traditional virtual machines, which can save on costs.
§
§ To use Docker, you first need to install Docker Engine on your
computer.
§ Once Docker Engine is installed, you can create a Dockerfile, which
is a text file that defines the contents of a Docker image.
§ You can then use the docker build command to build a Docker
image from the Dockerfile.
§ Once the Docker image is built,you can use the docker run command
to run the container.
§ Development: Docker can be used to develop, test, and deploy
applications.
§ Operations: Docker can be used to manage infrastructure and
applications.
§ Security: Docker can be used to isolate applications and improve
security.
§ A Dockerfile is a text file that defines the contents of a Docker
image.
§ To create a Dockerfile, open a text editor and create a new file.
WORKDIR /app
COPY . .
CMD java -jar my-app.jar
Save the file as Dockerfile.
Build The Docker Image Build The Docker Image:
docker build -t my-java-app

Run the Docker container:


docker run -it my-java-app
§ Kubernetes is an open-source system for automating deployment,
scaling, and management of containerized applications.
§ It is a container orchestration system that can be used to deploy
and manage Java web applications.
§ Scalability: Kubernetes can be used to scale Java web applications up or down
as needed. This can help to improve the performance and reliability of Java
web applications.
§ Availability: Kubernetes can be used to ensure that Java web applications are
always available. This can be done by using a technique called "rolling
updates" to deploy new versions of Java web applications without taking the
application offline.
§ Security: Kubernetes can be used to improve the security of Java web
applications. This can be done by using features such as network policies and
pod security policies.
§ Cost savings: Kubernetes can help to save money by reducing the need for
manual labor to manage Java web applications.
§ Pods: A pod is a group of one or more containers that are scheduled
together on the same host. Pods are the basic unit of deployment in
Kubernetes.
§ Replication Controllers: A replication controller ensures that a specified
number of pods are running at all times.
§ Services: A service is an abstraction that exposes pods to the network.
Services can be used to load balance traffic to pods and to provide a
single point of access for clients.
§ Deployments: A deployment is a Kubernetes object that automates the
creation, updating, and scaling of pods.
§ Jobs: A job is a Kubernetes object that automates the execution of a
task. Jobs can be used to run batch jobs or to perform tasks such as data
processing or machine learning.
§
§ Kubernetes has a decentralized architecture that does not handle
tasks sequentially.
§ It functions based on a declarative model and implements the
concept of a ‘desired state.’ These steps illustrate the basic
Kubernetes process:
§ An administrator creates and places the desired state of an
application into a manifest file.
§ The file is provided to the Kubernetes API Server using a CLI or UI.
Kubernetes’ default command-line tool is called kubectl. In case
you need a comprehensive list of kubectl commands, check out
our Kubectl Cheat Sheet.
§ Kubernetes stores the file (an application’s desired state) in a
database called the Key-Value Store (etcd).
§ Kubernetes then implements the desired state on all the relevant
applications within the cluster.
§ Kubernetes continuously monitors the elements of the cluster to
make sure the current state of the application does not vary from
the desired state.
§ The Kubernetes Master (Master Node) receives input from a CLI
(Command-Line Interface) or UI (User Interface) via an API.
§ These are the commands you provide to Kubernetes.
§ You define pods, replica sets, and services that you want
Kubernetes to maintain.
§ For example, which container image to use, which ports to expose,
and how many pod replicas to run.
§ You also provide the parameters of the desired state for the
application(s) running in that cluster.
API Server
§ The API Server is the front-end of the control plane and the only
component in the control plane that we interact with directly.
Internal system components, as well as external user components,
all communicate via the same API.
Key-Value Store (etcd)
§ The Key-Value Store, also called etcd, is a database Kubernetes
uses to back-up all cluster data. It stores the entire configuration
and state of the cluster. The Master node queries etcd to retrieve
parameters for the state of the nodes, pods, and containers.
Controller
§ The role of the Controller is to obtain the desired state from the
API Server. It checks the current state of the nodes it is tasked to
control, and determines if there are any differences, and resolves
them, if any.
Scheduler
§ A Scheduler watches for new requests coming from the API Server
and assigns them to healthy nodes. It ranks the quality of the
nodes and deploys pods to the best-suited node. If there are no
suitable nodes, the pods are put in a pending state until such a
node appears.
§ Worker nodes listen to the API Server for new work assignments;
they execute the work assignments and then report the results
back to the Kubernetes Master node.
§ Install Kubernetes on your machine. You can download
Kubernetes from the Kubernetes website.
§ Create a Java web application. You can use any Java web
application framework, such as Spring Boot or JHipster.
§ Package the Java web application as a Docker image. You can use
Docker to package the Java web application as a Docker image.
§ Deploy the Java web application to Kubernetes. You can use the
Kubernetes command-line tool to deploy the Java web application
to Kubernetes.
1. Create a Dockerfile. A Dockerfile is a text file that contains
instructions for building a Docker image.
FROM openjdk:8-jdk-alpine
COPY . /app
RUN javac -cp /app/lib/* /app/Main.java
CMD java -cp /app/lib/* Main
2.Build the Docker image. You can build the Docker image
using the following command:
docker build -t my-java-app .
3.Push the Docker image to a registry. You can push the Docker
image to a registry such as Docker Hub or Quay.io. This will make
the image available for deployment to Kubernetes.
§
§ 4.Create a Kubernetes Deployment. A Kubernetes Deployment is a
Kubernetes object that defines how to deploy a containerized
application.
§ You can create a Deployment using the kubectl create command.
kubectl create deployment my-java-app --image=my-java-app
5.Expose the Deployment. You can expose the Deployment using a
Kubernetes Service. A Kubernetes Service is a Kubernetes object
that defines how to expose a Deployment to traffic.
You can expose a Service using the kubectl expose command.
kubectl expose deployment my-java-app --type=LoadBalancer

6.Wait for the Deployment to be ready. Once the Deployment is


ready, you can access the Java web application by using the external
IP address of the Service.

You might also like