0% found this document useful (0 votes)
2 views260 pages

Fsd Full Notes

The document outlines the fundamentals of enterprise organization and business processes, detailing steps such as determining activities, grouping them, assigning duties, delegating authority, and coordinating efforts. It also discusses the importance of business process automation and digital transformation, highlighting the convergence of IT and OT to enhance operational efficiency. Additionally, it covers full-stack development, design thinking, and project planning, emphasizing the roles of various departments within a software company.

Uploaded by

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

Fsd Full Notes

The document outlines the fundamentals of enterprise organization and business processes, detailing steps such as determining activities, grouping them, assigning duties, delegating authority, and coordinating efforts. It also discusses the importance of business process automation and digital transformation, highlighting the convergence of IT and OT to enhance operational efficiency. Additionally, it covers full-stack development, design thinking, and project planning, emphasizing the roles of various departments within a software company.

Uploaded by

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

DEPARTMENT OF TECHNIAL EDUCATION

HMS POLYTECHNIC (GOVT-AIDED), TUMKUR

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

FULLSTACK DEVELOPMENT
(20CS52I)

Student Name:…………………………………….…………….

Prepared by:

Siddaramaiah S R, SGL/CS

Noor Aisha, SGL/CS


FULLSTACK DEVELOPMENT
WEEK-01
What is enterprise and examples?
The definition of an enterprise is a project, a willingness to take on a new project, an
undertaking or business venture. An example of an enterprise is a new start-up business. An
example of enterprise is someone taking initiative to start a business

Organizing the Enterprise - process


Five main steps involved in the process of organizing an enterprise.
1. Determining Activities
2. Grouping of Activities
3. Assigning Duties
4. Delegating Authority
5. Coordinating Activities.

1. Determining Activities
• The first step in organizing is to identify and enumerate (to specify one after another)
the activities required to achieve the objectives of the enterprise.
• The activities will depend upon the nature and size of the enterprise.
• For instance, a manufacturing concern will have production, marketing and other.
2. Grouping of Activities

• The various activities are then classified into appropriate departments and divisions on
the basis of functions, products, territories, customers etc.
• Similar and related activities may be grouped together under one department or
division.
• Grouping of activities helps to secure specialization. Each department may be further
sub divided into sections and groups.

3. Assigning Duties

• The individual groups of activities are then allotted to different individuals on the basis
of their ability and aptitude.
• The responsibility of every individual should be defined clearly to avoid duplication of
work and overlapping of effort.
• Each person is given a specific job best suited to him and he is made responsible for its
execution.

4. Delegating Authority:

• Every individual is given the authority necessary to perform the assigned task
effectively.
• An individual cannot perform his job without the necessary authority or power.

5. Coordinating Activities:
• The activities and efforts of different individuals are then synchronized. Such co-
ordination is necessary to ensure effective performance of specialized functions.

Understanding Business Activities


There are three main types of business activities: operating, investing, and financing.
• Operating Activities: Operating activities refer to all those business activities that are
directly or indirectly related to the provision of goods and services. As such they have
a direct impact on cash flow, and eventually on income.
• Investing Activities: Investing activities refers to all those activities that aimed to be
capitalized for more than a year. This includes capital expenditure such as purchase of
long term assets or real estate.
• Financing Activities: Financing activities refer to all those activities that fund the
business but are not directly related to the revenues from goods and services. Common
financing activities include bonds, loans, and share issues

What is a business process?


A business process is an activity or set of activities that accomplish a specific organizational
goal. Example
• Manufacturing
• Quality Assurance
• Packaging
• Shipping
• Purchasing

What is Business Process Automation?


• Business process automation (BPA) is a subset of a business process management
(BPM).
• It is the use of computer software or hardware to replace, control or automate repetitive
business tasks.
• The main aim of automation is to reduce or eliminate processes that either don't add
value or have a high potential for human error.
• In other words, anything that can be done by a machine should be.
• This helps you run more efficiently but can also save you money and ensure that
operations are done correctly.
Why automate business processes?
• Automating business processes is good for your employees.
• It frees up their time so they can focus on higher-level tasks instead of spending most
of their day answering similar questions over and over. Plus, it offers a lot more
efficiency in the long run.
• Automation helps you get your work done faster and more efficiently, thereby saving
money and time, which you can then invest in other things.
Digital transformation through Convergence of IT & OT

Information Technology and Operational Technology are brought together (Integrated) to help
digital transformation.

What is digital transformation?

Digital transformation is the integration of digital technology into all areas of a business,
fundamentally changing how you operate and deliver value to customers.

Digital technology: Digital technologies are electronic tools, systems, devices and resources
that generate, store or process data. Well known examples include social media, online games,
multimedia and mobile phones.

IT/OT convergence: IT/OT convergence is the integration of information technology (IT)


systems with operational technology (OT) systems. IT systems are used for data-centric
computing; OT systems monitor events, processes and devices, and make adjustments in
enterprise and industrial operations.

Information Technology: Information Technology means the use of hardware, software,


services, and supporting infrastructure to manage and deliver information using voice, data,
and video.

Operational Technology : Hardware and software that detects or causes a change through the
direct monitoring and/or control of physical devices, processes and events in the enterprise.

Digital Transformation Success Stories

1. IKEA

First, IKEA purchased the online service TaskRabbit to help customers who don’t like
assembling their own furniture — a foray into software.

Next, they dipped into the smart home sector by developing its own products, and changing
their payment processing.

By June 2021, it was reported that they had seen a 300% increase in ecommerce sales as a
direct result of their transformation efforts.
2. Budweiser

The King of Beers became the Kings of Digital Transformation when they decided to
implement AI to revolutionise their processes.

ABinBev, the owner of Budweiser, Stella Artois, and Corona, established the ‘Beer Garage’
— a Silicon Valley-based innovation centre, where it researches, develops, and tests
technology-driven solutions.

They use it to dive deep into the brewing process to predict end-product outcomes.

3. Coca-Cola

Implemented a transformation strategy that aimed to address the numerous changes in shopper
behavior as the world has gone digital.

Their goal was to update the Coke brand “for a generation that doesn’t see a line between the
online world and the offline, reality and augmented reality.”

Their roadmap covered experiential, operational, cultural, and business. As a result they have
been able to speed time to market for new products from three months to two or less. This
results in an improved customer experience and increased sales.

How technology has impacted digital transformation


Digital technologies allow organizations to easily adapt business processes and drive higher levels
of innovation.

Case study: Digital transformation through IT/OT convergence


A copper mining company brought information and operational technology under a single
governance and operating model to aid digital transformation.
Challenge
With the goal of becoming a leader in the use of automation in its operations, a large copper
mining company wanted to take advantage of an information technology (IT) and operational
technology (OT) convergence movement sweeping across industries.
In a highly competitive and rapidly changing technology landscape, the company knew that a
digital transformation, aimed at bringing IT and OT together under a common governance
structure, could be the difference between surviving and thriving.
With Accenture’s help, the company would launch a program to make better use of its
technology and data, change the way it worked and ultimately, build a foundation to support
its overall vision for digital transformation.
What Accenture did
The company and Accenture team designed and implemented unified technology governance
and a common technology operating model across various sites and brought the management
of IT and OT together under one new centralized technology organization.
Because of the complexity involved and because processes and technologies varied widely at
different sites, the effort was divided into three phases:
Assessment:
The team used a Kanban board (a key tool to depict workflow visualization), created sticky
notes to record ideas and gave presentations.
Design:
The team designed a global IT/OT convergence strategy, along with transition plans for each
asset that would vary depending on the complexity.
Execution:
The team launched strategy and transition plans as the company moved to a new
technology organization that encompassed both IT and OT.

People and culture


Because the effort involved a significant change in culture, stakeholders were consulted
throughout the project, helping people understand what was happening and building buy-in for
the new approach.
The company and Accenture also highlighted the fact that the convergence of IT and OT would
benefit the workforce by creating a wider variety of technical career paths, opportunities to
learn and develop skills, and the potential for employees to apply their skills to a broader range
of roles across the company’s operations and sites. Furthermore, they showed how the breaking
down of silos and the integration of IT and OT teams will bring a more coordinated response
to business requirements, the ability to share resources and exploit the same contracts, and
significant cost reductions

Value delivered
This initiative has provided greater visibility across the company’s technology
landscape and enabled IT and OT to operate under a single model, using higher-quality
operational data.
The new approach allows management to optimize operations from a holistic perspective and
use technology more efficiently and effectively. It has also allowed the company to enhance its
focus on safety, production volume and operational costs. And it has enabled leading practices
such as predictive asset management and integrated planning and scheduling.
Finally, the unified approach to IT and OT has positioned the company to continue to
better take advantage of digital technologies. Technology professionals can work as an
integrated team to identify and address IT/OT-related problems and move quickly to replicate
improvements and innovations across the company—which will be key to realizing the
company’s transformation vision in the coming years.

Business division and their activities in a software company


According to their duties, people create their individual departments in a company such as

1. IT Department
• IT Department is a core of every software company.
• It has created by the group of software professionals who are technical part of the
project.
• Duties within this department are divided among Developers, Project Managers and
QA specialists.

2. UX/UI Department
• Here the graphic part of the project is created.
• UX design stands for user experience design, while UI design stands for user interface
design.
• Create interfaces that are both effective and easy to use.
• As a result they design the whole application and its individual components.
• While creating the product, they work closely with the IT Department.

3. Business Development Department


• Business Manager who is the first to have contact with the potential customer.
• Exhaustive meetings with all team members and regular updates to client will follow
and once all features are defined the development team will begin building the product.
Collaboration and communication between all teams.

4. Marketing Department
• Responsible for creating the company's image on the market.
• Starting from the design of the website, through advertising, presence on industry
portals and press releases

5. HR Department
• Their main objective is to create the best possible team of dedicated and reliable
employees
• They are also aimed at staff development programs, improvement of staff efficiency
and career pathing.
• They play an important role in creating and implementing health and safety
regulations within the company.
6. Accounting and finances Department
• This department takes care of every financial aspect among the company.
• Also their aim is to control document flow and all settlements with partners.

7. Board of Directors
• They are responsible for coordinating the design, development, and implementation
of an organization's applications.
• Director of software development, your responsibilities are to oversee the
organization and daily operations of a software development.

Workflow
• A Workflow is defined as a sequence of tasks that processes data through a specific path
from initiation to completion. They can be used to structure any kind of business function
regardless of industry. Essentially, anytime data is passed between humans and/or
systems, a workflow is created.

Full-Stack Development
• Full-stack development refers to building end-to-end software solutions including
front-end and back-end development.
• Front-end refers to the front part of the application or UI which is seen by the end-user
and used for end-user interaction.
• The back-end part is related to server-side development, database, and API
development.
What is a full-stack web developer?
• Full stack web developers have the ability to design complete web applications and
websites. They work on the frontend, backend, database and debugging of web
applications or websites.
• They are proficient (Skilled or expert) in both frontend and backend languages and
frameworks, as well as in server, network and hosting environments.

Components of Full stack development


• Front End
• BackEnd

Front end: It is the visible part of website or web application which is responsible for user
experience. The user directly interacts with the front end portion of the web application or
website.

Front end Languages:


• HTML
• CSS
• JavaSccript
• Libraries
• CSS Processors
• Build Tools
• Frameworks

Front End Frameworks and Libraries:


• AngularJS
• [Link]
• Bootstrap
• jQuery
Back end: It refers to the server-side development of web application or website with a primary
focus on how the website works. It is responsible for managing the database through queries
and APIs by client-side commands.

• PHP:
• C++
• Java:
• Python:
• JavaScript
• [Link]

Database
• Oracle: Oracle database is the collection of data which is treated as a unit. The purpose of
this database is to store and retrieve information related to the query. It is a database server
and used to manage information.
• MongoDB: MongoDB, the most popular NoSQL database, is an open source document-
oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t
based on the table-like relational database structure but provides an altogether different
mechanism for storage and retrieval of data.
• Sql: Structured Query Language is a standard Database language which is used to create,
maintain and retrieve the relational database.

Full stack development Tools


• Backbone
• Code pen
• Visual Studio Code
• Type Script
• Web Strom
• GitHub
• Electron

Top 10 Front-End and Back-end Frameworks for Full-Stack Developers


1. React JS [Best JavaScript GUI library]
2. Spring Boot [Best Java Backend Framework]
3. Angular [Best JavaScript GUI Framework]
4. Node JS + [Link] [Best JavaScript Backend Framework]
5. Django [Best Python Full Stack Framework]
6. Flask [Best Python Backend Framework]
7. Bootstrap [Best CSS Framework for Web Development]
8. jQuery [Best JavaScirpt library]
9. Ruby on Rails [Best Ruby Framework for Web development]
10. GraphQL [Best JavaScript library for APIs]
Design Thinking
Design thinking enables software development companies to test the feasibility of the future
product and its functionality at the initial stage. It allows them to keep end user needs in mind,
clearly specify all requirements and translate all this into product features

Design thinking for software development


Design Thinking is a 5-step process to come up with meaningful ideas that solve real problems
for a particular group of people.

The five steps in design thinking are:


• Empathize: Understand the user’s needs and perspective
• Define: Define the problem that needs to be solved
• Ideate: Generate new and innovative ideas.
• Prototype: Create a prototype of the product.
• Test: Test the product with actual users to get feedback

What is project planning?


Project planning is a discipline addressing how to complete a project in a certain timeframe,
usually with defined stages and designated resources. One view of project planning divides the
activity into these steps:
• setting measurable objectives
• identifying deliverables
• scheduling
• planning tasks

How to create project plan


The software plan prevents hurdles that tend to crop up during the project’s
execution. It also ensures optimal utilization of every allotted resource and time.
1. Define your scope:
• A project's scope describes the goals needed to complete the project successfully.
• Defining your scope, consider project aspects like outcomes, tasks, budget, time
frame and deliverables.
• You can define these by writing them in sentences or creating a bulleted list within
your software project plan document.
2. Define and coordinate your requirements:
• Identify appropriate resources that will help you to meet the objectives.
• Define the other aspects of the project such as equipment, budget for software
development, team, skills, and timeline.
3. Understand your constraints:
• Project may encounter unexpected events that may adversely affect it. Such as
increase in costs, delayed results, technical and business etc.
• Such hurdles include support from the management, appropriate schedule,
appropriate budget, and skilled software developers.
4. Map your business processes:
• Business process mapping is a powerful technique to visually depict process steps
and show how a process should function from start to finish.
5. Estimate your budget:
• The estimates will help you get an idea of the money and time you need.
6. Draw up your staged deliverables:
• Next task is to draw software development milestones to give room for testing and
feedbacks at each phase.
• Milestones ensure the software development team focuses on specific
functionality aspects.
• When planning tasks and features to be done at the various phases, concentrate
more on achieving original targets.
7. Create a team:
• Project management requires one or several teams of professionals with the right
experience and skills.
• If your company lacks these individuals, you may hire from outside or outsource
the recruitment process to a company that will put together the teams for you.
8. Discuss quality and progress:
• Your planning is not yet over until you include the progress checks and quality
testing.
• Testing your stages ensures you’re meeting your milestone goals.

What is a product backlog?


A product backlog is a prioritized list of work for the development team that is derived from
the roadmap and its requirements. The most important items are shown at the top of the product
backlog so the team knows what to deliver first.

Steps to create a product backlog


A product backlog is more than a simple to-do list—it’s where you break down complex tasks
into a series of steps and delegate them to team members.
1. Build a product roadmap
The product roadmap is the foundation for the product backlog. Your team should create a
roadmap first, which will then serve as the action plan for how your product will change as it
develops. The roadmap is the vision for long-term product development, but it can also evolve.

2. List product backlog items


These items should include both high-priority items and more abstract ideas. During this phase
of product backlog creation, you’ll also need to communicate with stakeholders and listen to
their ideas for product improvements.

3. Prioritize your backlog


After your team lists all the product backlog items, sort and prioritize your most important
tasks. You can identify top-priority items by putting the customer front of mind and considering
what items provide the most value to them.

4. Update regularly
As your team works through the product backlog, remember that it’s a living document. You
can continuously add items to the backlog and prioritize or refine them as you work.
FULLSTACK DEVELOPMENT
WEEK-02
Software development in agile methodology
Define goal of product
Product goals help achieve the product vision and business objectives. Goals are a key piece of your
product strategy.

Define Epic
Agile epics are large pieces of work that can be broken down into smaller and more manageable work
items, tasks, or user stories. These series of work items share the same goal described by the epic.

Road Map
Roadmaps in Jira Software are team-level roadmaps useful for planning large pieces of work several
months in advance at the Epic level within a single project

Cost estimation
Cost estimation in software engineering is the process of predicting the resources (money, time, and
people) necessary to finish a project within the defined scope.

Risk Management
There are three main classifications of risks which can affect a software project:
1. Project risks
2. Technical risks
3. Business risks
1. Project risks: Project risks concern differ forms of budgetary, schedule, personnel, resource, and
customer-related problems.
2. Technical risks: Technical risks concern potential method, implementation, interfacing, testing, and
maintenance issue. Most technical risks appear due to the development team's insufficient knowledge
about the project.
3. Business risks: This type of risks contain risks of building an excellent product that no one need,
losing budgetary or personnel commitments, etc.

Creating user stories for the epic using Jira


Step 1: Create a new epic in Jira Software
• There are three ways to create epics in Jira Software the Roadmap, Backlog, and Global
Create issue button.
When you create an epic, you'll need to enter the following details:
• Epic name – A Label to identify for your epic.
• Epic summary - You'll see this whenever Jira displays the epic.

Create an epic on the Roadmap


• The roadmap is useful for visualizing and planning large pieces of work that may be in
progress right now or you may prioritize in the future.
First, enable the roadmap.
1. From your board select More (•••) in the top right corner > Board settings
2. In the Roadmap tab, enable the feature for your project.
3. Then, select Roadmap from the menu on the far left.
4. Hit + Create epic on the Roadmap. If your Roadmap is empty, simply start typing to create your
first epic.

Create an epic from a new issue


You can create epics and any other issue types using the global navigation menu.
1. Click the create button located in the global navigation bar at the top of the screen.
2. Select Epic for the issue type.

Create an epic from the Epic Panel in the backlog


1. Navigate to the Backlog.
2. Click on the Epics Panel.
3. Hit Create Epic.

Step 2: Add stories or child-issues


• There are two ways to add a story to an epic:

From the issue create screen


1. Click Issue in the top-left corner. Select an issue type other than epic. Find the Epic
Link field, and select your epic. Fill in any other details and click Create.

From the Epics Panel


1. Navigate to the Backlog.
2. Open the Epics Panel.
3. Hit Create issue in epic.
On the roadmap
1. Hover over an epic and click + Add a child issue.
2. Choose an issue type, then hit enter.

To remove an issue from an epic


Navigate to either Backlog or Active sprints:
• In the Backlog, drag the issue onto the Issues without epics section at the bottom of
the Epics Panel; or
• In either the Backlog or the Active sprints, click the relevant issue to display it on the right-
hand side of the screen, then click the x in the epic name (e.g. "Apples" in Screenshot 1 below).

Step 3: Viewing your epics


You can see information relating to all your epics in the Backlog.
1. Epics Panel: Go to the Backlog and open the Epics Panel to view and manage your epics.
2. List of epics: The Epics Panel displays a list of all epics in your project.
3. View issues in epic: Click an epic's name to view all the issues belonging to that epic, across
all sprints.

Step 4: Set up swimlanes for your epics on your board


• During a sprint, you might find it useful to divide your board into swimlanes for each
epic, to make the board visually clearer.

Here's how you can set this up in Jira Software:


1. Navigate to the Backlog (or active sprint).

2. Select more ( ) > Board settings.


3. Click on Swimlanes.
4. Under Base swimlanes on, select Epics.
Step 5: Monitor the progress of your epic
• It is important to keep track of all incomplete issues attached to an epic.
Step 6: Complete your epic
• To complete an epic navigate to the backlog or roadmap
Backlog
1. Navigate to the Backlog.
2. Open the Epics Panel.
3. Click the drop-down for your epic, and select Mark as Done.
Roadmap
1. Navigate to the Roadmap
2. Click on the epic
3. Click the status drop-down in the detail view and select Mark as Done.

Creating Acceptance Criteria:


1. Go to your Project and select Project Settings.
2. Select Issue Types from the left-hand menu and choose the User Story issue type.
3. Create a new "Paragraph" custom field from the right-hand "Create a Field" menu by clicking
on it.
4. Give the field a name - Acceptance Criteria.
5. Click Save Changes.
Sprint Planning:
Create a sprint
You can create a sprint for your current iteration, or multiple future sprints if you want
to plan several iterations ahead.

1. If not already there, navigate to your company-managed Jira Software project.


2. From your project’s sidebar, select your Backlog.
3. Click Create sprint at the top of the backlog section.
Once you've created a sprint, you can add issues to it.

Plan a future sprint


To plan a future sprint:
1. If not already there, navigate to your company-managed Jira Software project.
2. From your project’s sidebar, select your Backlog.
3. Click Create sprint at the top of the backlog section. The new sprint will appear below the
current sprint.
4. SelectAdd dates (located under the sprint’s header) to plan the start and end date of your future
sprint.
Backlog Refinement:
• The refinement stage. The purpose of the refinement stage is to set clear expectations
with stakeholders and other teams.
1: Backlog Is Treated Like a Wish List
2: Sprint Objectives Are Not Aligned with Business Goals
3: Backlog Grooming Is Not Regulated
4: Issues Are Not Refined with Relevant Context

Sprint Demo
It is the opportunity for the Scrum Team to showcase to Stakeholders and the Product
Owner, things that have been done in a Sprint.

Burndown chart
Burndown chart is a major parameter used in agile software development and scrum
to detect how much work remains to be completed.
Burndown Chart is a graphical representation of work done, work to be done, the time
required for pending work done.

To view the sprint burndown chart:


1. Navigate to your scrum project.
2. Select the Backlog or Active sprint.
3. Click Reports, then select Burndown Chart.

Sprint retrospective
The sprint retrospective is a recurring meeting held at the end of a sprint used to discuss
what went well during the previous sprint cycle and what can be improved for the next sprint.
During the Sprint Retrospective, the team discusses:
• What went well in the Sprint
• What could be improved
• What will we commit to improve in the next Sprint

Design Principles
1. Availability refers to the percentage of time that the infrastructure, system, or solution
remains operational under normal circumstances in order to serve its intended purpose
2. Performance is an indicator of how well a software system or component meets its
requirements for timeliness. Timeliness is measured in terms of response time or
throughput. The response time is the time required to respond to a request
3. Consistency defined as the requirement that a series of measurements of the same
project carried out by different raters using the same method should produce similar
results, is one of the most important aspects to be taken into account in the measurement
methods of the software.
4. Scalability is the measure of a system's ability to increase or decrease in performance
and cost in response to changes in application and system processing demands.
5. Manageability How efficiently and easily a software system can be monitored and
maintained to keep the system performing, secure, and running smoothly.
6. Software cost estimation is the process of predicting the effort required to develop a
software system.

Architecture Pattern:
1. Monolithic Architecture is like a big container, wherein all the software
components of an app are assembled and tightly coupled, i.e., each component fully
depends on each other.
As you can see in the example all the services provided by the application (Customer
Services, Cost Services, Product Services) are directly connected. So if we want to
change in code or something we have to change in all the services as well.
2. Layered architecture:

• A number of different layers are defined with each layer performing a well-defined
set of operations. Each layer will do some operations that becomes closer to machine
instruction set progressively.
• At the outer layer, components will receive the user interface operations and at the
inner layers, components will perform the operating system
interfacing(communication and coordination with OS)
• Intermediate layers to utility services and application software functions.

3. The Microservices pattern combines design patterns to create multiple services that
work interdependently to create a larger application. Because each application is small,
it's easier to update them when needed.

4. Service-Oriented Architecture (SOA) is a stage in the evolution of application


development and/or integration. It defines a way to make software components.
Design methods for security
1. Application security
Definition
Application security is the process of developing, adding, and testing security features within
applications to prevent security vulnerabilities against threats such as unauthorized access and
modification.
Types of application security
1. Authentication: Authentication procedures ensure that a user is who they are. This can
be accomplished by providing a user name and password when logging in to an
application.
2. Authorization: The system can validate that a user has permission to access the
application by comparing the user’s identity with a list of authorized users.
3. Encryption: Encryption is the method by which information is converted into secret
code that hides the information's true meaning.

Token Based security:


• Token-based authentication is a protocol that generates encrypted security tokens.
• It enables users to verify their identity to websites, which then generates a unique
encrypted authentication token.
• That token provides users with access to protected pages and resources for a limited
period of time without having to re-enter their username and password.
Cookie based Security:
Cookie authentication uses HTTP cookies to authenticate client requests and maintain
session information
Open ID:
OpenID allows you to use an existing account to sign in to multiple websites, without
needing to create new passwords.
Third party access:
• Third-party access refers to the process of an organization granting external vendors
and service providers secure access to corporate IT assets for maintenance,
administration and management purposes.
• virtual private network (VPN) solutions to authenticate and authorize employees
accessing corporate applications and IT services from outside the enterprise network.
SAML:
• SAML is an acronym used to describe the Security Assertion Markup Language
(SAML).
• Security Assertion Markup Language (SAML) is an open standard that allows identity
providers (IdP) to pass authorization credentials to service providers (SP).
Multi factor Authentication:
• Multi-factor Authentication (MFA) is an authentication method that requires the user
to provide two or more verification factors to gain access to a resource such as an
application, online account, or a VPN.
Data Source:
• A datastore is a repository for storing, managing and distributing data sets on an enterprise
level.
• A Data Store is a connection to a store of data, whether the data is stored in a database or
in one or more files.
Structured data:
• Data is stored in a spreadsheet
• Excel spreadsheets, Comma-separated value file (.csv) and Relational database tables.

• Data entries have the same format and a predefined length and follow the same order.

Semi Structured data:


• Data is stored in a text file.
• With some structure like headers, paragraphs, etc
• HTML files, JavaScript Object Notation (JSON) files and XML files.
• Data entries have the hierarchical format and a but the size and order of elements can
vary.
Unstructured data:
• Data has no specific format.
• Images such as .jpeg or .png files, Videos such as .mp4 or m4a files, Sound files such
as .mp3 or .wav files, Plain text files. Word files and PDF files.
• Data that can take any form and thus be stored as any kind of file

Design Principles for UI/UX:


• UX design refers to the term “user experience design”, while UI stands for “user
interface design”.

Technology for Application development


• JavaScript
• Java
• HTML
• C
• Git
• C++
• Python
• CSS
• Blockchain
• SQL

Tools and framework for Application development


• GitHub
• Atom
• IntelliJ IDEA
• Google Docs
• Bootstrap
• [Link]
• Django
• Angular JS
• React JS
• Microsoft Azure
• NetBeans
• Jenkins
What is DevOps?
DevOps is an evolving philosophy and framework that encourages faster,
better application development and faster release of new or revised software
features or products to customers.
The practice of DevOps encourages smoother, continuous communication,
collaboration, integration, visibility, and transparency between application
development teams (Dev) and their IT operations team (Ops) counterparts.

DevOps Engineering Practices


DevOps stands for development and operations. Its pratices that aims at
merging development, vality assurance and operations into a single,
continuous set of process. This methodology is a natural extention of agile and
continuous delivery approaches.

Configuration Management
Configuration management occurs when a configuration platform is used to
automate, monitor, design and manage otherwise manual configuration
processes. System-wide changes take place across servers and networks,
storage, applications, and other managed system.

An important function of configuration management is defining the state of


each system. By orchestrating these processes with a platform, organizations
can ensure consistency across integrated systems and increase efficiency. The
result is that businesses can scale more readily without hiring additional IT
management staff. Companies that otherwise wouldn’t have the resources can
grow by deploying a DevOps approach.

What is continuous integration


Continuous integration refers to the build and unit testing stage of the
software release process. Every revision that is committed triggers an
automated build and test. With continuous delivery, code changes are
automatically built, tested, and prepared for a release to production.

What is automated testing


DevOps makes testing a shared responsibility of the entire team, while test
automation enables developers to ship code changes quickly with high
confidence in quality.

Infrastructure as Code
Infrastructure as Code (IaC) is the managing and provisioning of infrastructure
through code instead of through manual processes. With IaC, configuration
files are created that contain your infrastructure specifications, which makes it
easier to edit and distribute configurations.

Continuous Delivery
Continuous delivery lets developers automate testing beyond just unit tests so
they can verify application updates across multiple dimensions before
deploying to customers. These tests may include UI testing, load testing,
integration testing, API reliability testing, etc.

DevOps practices
DevOps practices reflect the idea of continuous improvement and automation.
Many practices focus on one or more development cycle phases. These
practices include:
• Continuous development. This practice spans the planning and coding
phases of the DevOps lifecycle. Version-control mechanisms might be involved.

• Continuous testing. This practice incorporates automated,


prescheduled, continued code tests as application code is being written or
updated. Such tests can speed the delivery of code to production.

• Continuous integration (CI). This practice brings configuration


management (CM) tools together with other test and development tools to
track how much of the code being developed is ready for production. It
involves rapid feedback between testing and development to quickly identify
and resolve code issues.

• Continuous delivery. This practice automates the delivery of code


changes, after testing, to a preproduction or staging environment. An staff
member might then decide to promote such code changes into production.

• Continuous deployment (CD). Similar to continuous delivery, this


practice automates the release of new or changed code into production. A
company doing continuous deployment might release code or feature changes
several times per day. The use of container technologies, such as Docker and
Kubernetes, can enable continuous deployment by helping to maintain
consistency of the code across different deployment platforms and
environments.

• Continuous monitoring. This practice involves ongoing monitoring of


both the code in operation and the underlying infrastructure that supports it. A
feedback loop that reports on bugs or issues then makes its way back to
development.

• Infrastructure as code. This practice can be used during various


DevOps phases to automate the provisioning of infrastructure required for a
software release. Developers add infrastructure “code” from within their
existing development tools. For example, developers might create a storage
volume on demand from Docker, Kubernetes, or OpenShift. This practice also
allows operations teams to monitor environment configurations, track
changes, and simplify the rollback of configurations.

Agile planning in DevOps


• Continuous development. This practice spans the planning and
coding phases of the DevOps lifecycle. Version-control mechanisms might be
involved.

• Continuous testing. This practice incorporates automated,


prescheduled, continued code tests as application code is being written or
updated. Such tests can speed the delivery of code to production.
• Continuous integration (CI). This practice brings configuration
management (CM) tools together with other test and development tools to
track how much of the code being developed is ready for production. It
involves rapid feedback between testing and development to quickly identify
and resolve code issues.
• Continuous delivery. This practice automates the delivery of code
changes, after testing, to a preproduction or staging environment. An staff
member might then decide to promote such code changes into production.

• Continuous deployment (CD). Similar to continuous delivery, this


practice automates the release of new or changed code into production. A
company doing continuous deployment might release code or feature changes
several times per day. The use of container technologies, such as Docker and
Kubernetes, can enable continuous deployment by helping to maintain
consistency of the code across different deployment platforms and
environments.

• Continuous monitoring. This practice involves ongoing monitoring of


both the code in operation and the underlying infrastructure that supports it. A
feedback loop that reports on bugs or issues then makes its way back to
development.
• Infrastructure as code. This practice can be used during various
DevOps phases to automate the provisioning of infrastructure required for a
software release. Developers add infrastructure “code” from within their
existing development tools. For example, developers might create a storage
volume on demand from Docker, Kubernetes, or OpenShift. This practice also
allows operations teams to monitor environment configurations, track
changes, and simplify the rollback of configurations.

Benefits of DevOps
DevOps proponents describe several business and technical benefits, many of
which can result in happier customers. Some benefits of DevOps include:
• Faster, better product delivery
• Faster issue resolution and reduced complexity
• Greater scalability and availability
• More stable operating environments
• Better resource utilization
• Greater automation
• Greater visibility into system outcomes
• Greater innovation

The 7 key practices of DevOps are:

1. Configuration Management

2. Continuous Integration

3. Automated Testing

4. Infrastructure as Code

5. Continuous Delivery

6. Continuous Deployment

7. Continuous Monitoring

DevOps tools
Followers of DevOps practices often use certain DevOps-friendly tools as part
of their DevOps “toolchain.” The goal of these tools is to further streamline,
shorten, and automate the various stages of the software delivery workflow
(or “pipeline”). Many such tools also promote core DevOps tenets of
automation, collaboration, and integration between development and
operations teams. The following shows a sample of tools used at various
DevOps lifecycle stages.

• Plan. This phase helps define business value and requirements. Sample
tools include Jira or Git to help track known issues and perform project
management.

• Code. This phase involves software design and the creation of software
code. Sample tools include GitHub, GitLab, Bitbucket, or Stash.

• Build. In this phase, you manage software builds and versions, and use
automated tools to help compile and package code for future release to
production. You use source code repositories or package repositories that also
“package” infrastructure needed for product release. Sample tools include
Docker, Ansible, Puppet, Chef, Gradle, Maven, or JFrog Artifactory.

• Test. This phase involves continuous testing (manual or automated) to


ensure optimal code quality. Sample tools include JUnit, Codeception,
Selenium, Vagrant, TestNG, or BlazeMeter.

• Deploy. This phase can include tools that help manage, coordinate,
schedule, and automate product releases into production. Sample tools
include Puppet, Chef, Ansible, Jenkins, Kubernetes, OpenShift, OpenStack,
Docker, or Jira.

• Operate. This phase manages software during production. Sample


tools include Ansible, Puppet, PowerShell, Chef, Salt, or Otter.

• Monitor. This phase involves identifying and collecting information


about issues from a specific software release in production. Sample tools
include New Relic, Datadog, Grafana, Wireshark, Splunk, Nagios, or Slack.
Configuration management

Why Do We Need a Version Control System?


Version control systems allow multiple developers, designers, and team
members to work together on the same project. It helps them work smarter
and faster! A version control system is critical to ensure everyone has access to
the latest code and modifications are tracked. As development becomes
increasing complex and teams grow, there’s a bigger need to manage multiple
versions and components of entire products.

What is GitHub?
• Git is not the same as GitHub.
• GitHub makes tools that use Git.
• GitHub is the largest host of source code in the world, and has been
owned by Microsoft since 2018.
.

Git Install
You can download Git for free from the following website: [Link]
[Link]/

Fundamentals of Git
Here is a basic overview of how Git works:
1. Create a “repository” (project) with a git hosting tool (like Bitbucket)
2. Copy (or clone) the repository to your local machine
3. Add a file to your local repo and “commit” (save) the changes
4. “Push” your changes to your main branch
5. Make a change to your file with a git hosting tool and commit
6. “Pull” the changes to your local machine
7. Create a “branch” (version), make a change, commit the change
8. Open a “pull request” (propose changes to the main branch)
9. “Merge” your branch to the main branch

Git Client installation and setup


Installation of Git Client
If you are using Debian base GNU/Linux distribution, then apt-get command
Will do the needful.
[ubuntu ~]$ sudo apt-get install git-core

[sudo] password for ubuntu:

[ubuntu ~]$ git –version

Git version [Link]


And if you are using RPM based GNU/Linux distribution, then use yum
command
As given.

[CentOS ~]$

Su –

Password:

[CentOS ~]# yum -y install git-core

[CentOS ~]# git –version

Git version 1.7.1


Customize Git Environment

Git provides the git config tool, which allows you to set configuration variables.
Git stores all global configurations in .gitconfig file, which is located in your
Home directory. To set these configuration values as global, add the –
Global option, and if you omit –global option, then your configurations are
Specific for the current Git repository.
You can also set up system wide configuration. Git stores these values in
The /etc/gitconfig file, which contains the configuration for every user and
Repository on the system. To set these values, you must have the root rights
And use the –system option.
When the above code is compiled and executed, it produces the following
result:

Setting username
This information is used by Git for each commit.
[jerry@CentOS project]$ git config –global [Link] “Jerry Mouse”

Setting email id
This information is used by Git for each commit.
[jerry@CentOS project]$ git config –global [Link]

“jerry@tutorialspoint.c
Avoid merge commits for pulling
You pull the latest changes from a remote repository, and if these changes are
Divergent, then by default Git creates merge commits. We can avoid this via
Following settings.
jerry@CentOS project]$ git config –global [Link] always

Color highlighting

The following commands enable color highlighting for Git in the console.
[jerry@CentOS project]$ git config –global [Link] true

[jerry@CentOS project]$ git config –global [Link] auto

[jerry@CentOS project]$ git config –global [Link] auto

Setting default editor


By default, Git uses the system default editor, which is taken from the VISUAL
or
EDITOR environment variable. We can configure a different one by using git
Config.

Basic local Git operations


▪ creating a repository

Different ways to Create Git Repository


We can Create Git Repository using one of the three approaches enlisted below:
• Create a bare repositor
Creating a Bare Git Repository for a new project is three-step process:

1) Create a New Project/Folder


2) Browse to New Project
3) Initialize Git Repository for the Project
Reference: [Link]

• Initialize repository in an existing project directory


Create Git Repository for an Existing Project
We’d also like to track an existing project by using Git. In this case, we’ll
initialize a Git repository in an existing project directory. There is no rocket
science in creating git Repository for an existing project, it is as same as
creating a git repository for a new project with the only difference of step 1 is
not required:
I. Browse to Existing Project
II. Initialize Git Repository for the Project
Reference : [Link]

• Cloning a repository

i. On [Link], navigate to the main page of the repository.


ii. Above the list of files, click Code.
iii. Copy the URL for the repository. To clone the repository using HTTPS,
under “HTTPS”, click . …Open .
iv. Change the current working directory to the location where you want the
cloned directory
• making and recording changes
You have a bona fide Git repository and a checkout or working copy of the files
for that project. You need to make some changes and commit snapshots of those
changes into your repository each time the project reaches a state you want to
record.
Remember that each file in your working directory can be in one of two states:
tracked or untracked. Tracked files are files that were in the last snapshot; they
can be unmodified, modified, or staged. Untracked files are everything else —
any files in your working directory that were not in your last snapshot and are not
in your staging area. When you first clone a repository, all of your files will be
tracked and unmodified because you just checked them out and haven’t edited
anything.

As you edit files, Git sees them as modified, because you’ve changed them since
your last commit. You stage these modified files and then commit all your staged
changes, and the cycle repeats. This lifecycle is illustrated in Figure 2-1.

▪ staging and committing changes


Stage Files to Prepare for Commit
1. Enter one of the following commands, depending on what you want to do:
Stage all files: git add . Stage a file: git add example. Html (replace
example. …
2. Check the status again by entering the following command: git status.
3. You should see there are changes ready to be committed.

▪ Viewing the history of all the changes Undoing


changes
The git revert command is used for undoing changes to a repository’s commit
history. Other ‘undo’ commands like, git checkout and git reset , move the HEAD
and branch ref pointers to a specified commit. Git revert also takes a specified
commit, however, git revert does not move ref pointers to this commit.

▪ Git Branching and merging


Merging is Git’s way of putting a forked history back together again. The git
merge command lets you take the independent lines of development created by
git branch and integrate them into a single branch. Note that all of the commands
presented below merge into the current branch.

Basic
▪ Creating and switching to new branches
New Branches
The git branch command can be used to create a new branch. When you want to
start a new feature, you create a new branch off main using git branch new_branch
. Once created you can then use git checkout new_branch to switch to that branch.

▪ Switching between branches


You can use the git switch – command to undo any changes you make and return
to your previous branch. If you instead want to keep your changes and continue
from here, you can use git switch -c <new-branch-name> to create a new branch
from this point.

▪ Merging local branches together


To merge branches locally, use git checkout to switch to the branch you want to
merge into. This branch is typically the main branch. Next, use git merge and
specify the name of the other branch to bring into this branch. This example
merges the jeff/feature1 branch into the main branch.

GitHub
- Basics of distributed git
Git is distributed version control software. Version control is a way to save
changes over time without overwriting previous versions. Being distributed
means that every developer working with a Git repository has a copy of that entire
repository – every commit, every branch, every file.
Account creation and configuration
You typically configure your global username and email address after installing
Git.

[Link] your global username/email configuration:
[Link] the command line.
[Link] your username: git config –global [Link] “FIRST_NAME
LAST_NAME”
[Link] your email address: git config –global [Link]
“MY_NAME@[Link]”
- Create and push to repositories
➢ Create a new repository on [Link]. …
➢ Open TerminalTerminalGit Bash.
➢ Change the current working directory to your local
project.
➢ Use the init command to initialize the local directory as a
Git repository. …
➢ Add the files in your new local repository. …
➢ Commit the files that you’ve staged in your local
repository.
- Versioning
➢ Version control is a system that records changes to a file
or set of files over time so that you can recall specific
versions later. For the examples in this book, you will use
software source code as the files being version controlled,
though in reality you can do this with nearly any type of
file on a computer.
- Collaboration
➢ Collaboration is the way different people can work on the
same project together. It is like creating a group in GitHub
just like Groups in other social media. The people added
to the collaborator’s list can be able to push, merge, and
do other kinds of similar things on the project.
- Migration
➢ We’ve broken down the SVN-to-Git migration process
into 5 simple steps: Prepare your environment for the
migration. Convert the SVN repository to a local Git
repository. Synchronize the local Git repository when the
SVN repository changes. Share the Git repository with
your developers via Bitbucket.

CLOUD BASICS
Cloud infrastructure overview

Cloud computing infrastructure is the collection of hardware


and software elements needed to enable cloud computing. It includes
computing power, networking, and storage, as well as an interface for
users to access their virtualized resources. The virtual resources mirror
a physical infrastructure, with components like servers, network
switches, memory and storage clusters. ]
Cloud computing architecture and its components

Cloud computing, which is one of the demanding technology of the


current time and which is giving a new shape to every organization by
providing on demand virtualized services/resources. Starting from
small to medium and medium to large, every organization use cloud
computing services for storing information and accessing it from
anywhere and any time only with the help of internet. In this article, we
will know more about the internal architecture of cloud computing.
Transparency, scalability, security and intelligent monitoring are
some of the most important constraints which every cloud
infrastructure should experience. Current research on other important
constraints is helping cloud computing system to come up with new
features and strategies with a great capability of providing more
advanced cloud solutions.

Cloud Computing Architecture :

The cloud architecture is divided into 2 parts i.e.


1. Frontend
2. Backend
The below figure represents an internal architectural view of cloud
computing.
Front End:
The client uses the front end, which contains a client-side interface and application.
Both of these components are important to access the Cloud computing platform.
The front end includes web servers (Chrome, Firefox, Opera, etc.), clients, and
mobile devices.

Back End:
The backend part helps you manage all the resources needed to provide Cloud
computing services. This Cloud architecture part includes a security mechanism, a
large amount of data storage, servers, virtual machines, traffic control mechanisms,
etc.

What is Cloud Computing?


Cloud Computing refers to manipulating, configuring, and accessing the hardware and
software resources remotely. It offers online data storage, infrastructure, and application.
Cloud computing offers platform independency, as the software is not required to be installed
locally on the PC. Hence, the Cloud Computing is making our business
applications mobile and collaborative.

Basic Concepts
There are certain services and models working behind the scene making the cloud computing
feasible and accessible to end users. Following are the working models for cloud computing:

• Deployment Models

Service Models

Services models
The three major Cloud Computing Offerings are

• Software as a Service (SaaS)


• Platform as a Service (PaaS)
• Infrastructure as a Service (IaaS)

Different business use some or all of these components according to their


requirement.

SaaS (Software as a Service)


SaaS or software as a service is a software distribution model in which applications
are hosted by a vendor or service provider and made available to customers over a
network (internet). SaaS is becoming an increasingly prevalent delivery model as
underlying technologies that supports Service Oriented Architecture (SOA) or
Web Services. Through internet this service is available to users anywhere in the
world.
Traditionaly, software application needed to be purchased upfront &then installed
it onto your computer. SaaS users on the other hand, instead of purchasing the
software subscribes to it, usually on monthly basisvia internet.

Anyone who needs an access to a particular piece of software can be subscribe as a


user, whether it is one or two people or every thousands of employees in a
corporation. SaaS is compatible with all internet enabled devices.

Many important tasks like accounting, sales, invoicing and planning all can be
performed using SaaS.

PaaS (Platform as a Service)


Platform as a service, is referred as PaaS, it provides a platform and environment
to allow developers to build applications and services. This service is hosted in the
cloud and accessed by the users via internet.

To understand in a simple terms, let compare this with painting a picture, where
you are provided with paint colors, different paint brushes and paper by your
school teacher and you just have to draw a beautiful picture using those tools.
PaaS services are constantly updated & new features added. Software developers,
web developers and business can benefit from PaaS. It provides platform to
support application development. It includes software support and management
services, storage, networking, deploying, testing, collaborating, hosting and
maintaining applications.

IaaS (Infrastructure as a Service)


IaaS (Infrastructure As A Service) is one of the fundamental service model of
cloud computing alongside PaaS( Platform as a Service). It provides access to
computing resources in a virtualized environment “the cloud” on internet. It
provides computing infrastructure like virtual server space, network connections,
bandwidth, load balancers and IP addresses. The pool of hardware resource is
extracted from multiple servers and networks usually distributed across numerous
data centers. This provides redundancy and reliability to IaaS.

IaaS(Infrastructure as a service) is a complete package for computing. For


small scale businesses who are looking for cutting cost on IT infrastructure, IaaS is
one of the solutions. Annually a lot of money is spent in maintenance and buying
new components like hard-drives, network connections, external storage device
etc. which a business owner could have saved for other expenses by using IaaS.

Deployment Models
Deployment models define the type of access to the cloud, i.e., how the cloud is located? Cloud
can have any of the four types of access: Public, Private, Hybrid, and Community.

Public Cloud
The public cloud allows systems and services to be easily accessible to the general public.
Public cloud may be less secure because of its openness.
Private Cloud
The private cloud allows systems and services to be accessible within an organization. It is
more secured because of its private nature.
Community Cloud
The community cloud allows systems and services to be accessible by a group of
organizations.
Hybrid Cloud
The hybrid cloud is a mixture of public and private cloud, in which the critical activities are
performed using private cloud while the non-critical activities are performed using public
cloud.

Important Components of Cloud Computing


Architecture
Here are some important components of Cloud computing architecture:

1. Client Infrastructure:
Client Infrastructure is a front-end component that provides a GUI. It helps users to
interact with the Cloud.

2. Application:
The application can be any software or platform which a client wants to access.

3. Service:
The service component manages which type of service you can access according to
the client’s requirements.

Three Cloud computing services are:

• Software as a Service (SaaS)


• Platform as a Service (PaaS)
• Infrastructure as a Service (IaaS)

4. Runtime Cloud:
Runtime cloud offers the execution and runtime environment to the virtual
machines.
5. Storage:
Storage is another important Cloud computing architecture component. It provides
a large amount of storage capacity in the Cloud to store and manage data.

6. Infrastructure:
It offers services on the host level, network level, and application level. Cloud
infrastructure includes hardware and software components like servers, storage,
network devices, virtualization software, and various other storage resources that
are needed to support the cloud computing model.

7. Management:
This component manages components like application, service, runtime cloud,
storage, infrastructure, and other security matters in the backend. It also establishes
coordination between them.

8. Security:
Security in the backend refers to implementing different security mechanisms for
secure Cloud systems, resources, files, and infrastructure to the end-user.

9. Internet:
Internet connection acts as the bridge or medium between frontend and backend. It
allows you to establish the interaction and communication between the frontend
and backend.

Benefits of Cloud Computing Architecture :


• Makes overall cloud computing system simpler.
• Improves data processing requirements.
• Helps in providing high security.
• Makes it more modularized.
• Results in better disaster recovery.
• Gives good user accessibility.
• Reduces IT operating cost.
Virtualization and Cloud Computing
The main enabling technology for Cloud Computing is Virtualization.
Virtualization is the partitioning of a single physical server into multiple logical
servers. Once the physical server is divided, each logical server behaves like a
physical server and can run an operating system and applications independently.
Many popular companies like VMware and Microsoft provide virtualization
services. Instead of using your PC for storage and computation, you can use their
virtual servers. They are fast, cost-effective, and less time-consuming.

Network Virtualization: It is a method of combining the available resources in


a network by splitting up the available bandwidth into channels. Each channel is
independent of others and can be assigned to a specific server or device in real
time.

Storage Virtualization: It is the pooling of physical storage from multiple


network storage devices into what appears to be a single storage device that is
managed from a central console. Storage virtualization is commonly used in
storage area networks (SANs).

Server Virtualization: Server virtualization is the masking of server resources


like processors, RAM, operating system, etc., from server users. Server
virtualization intends to increase resource sharing and reduce the burden and
complexity of computation from users.

cloud native application deveploment

The term cloud native refers to the concept of building and running
applications to take advantage of the distributed computing offered by
the cloud delivery model. Cloud native apps are designed and built to
exploit the scale, elasticity, resiliency, and flexibility the cloud
provides.
As defined by the Cloud Native Computing Foundation (CNCF), Cloud
native technologies empower organizations to build and run scalable
applications in public, private, and hybrid clouds. Features such as
containers, service meshes, microservices, immutable infrastructure,
and declarative application programming interfaces (APIs) best
illustrate this approach.
These features enable loosely coupled systems that are resilient,
manageable, and observable. They allow engineers to make high-
impact changes frequently and with minimal effort.
Continuous integration

Continuous integration is a DevOps software development practice where


developers regularly merge their code changes into a central repository, after which
automated builds and tests are run. Continuous integration most often refers to the
build or integration stage of the software release process and entails both an
automation component (e.g. a CI or build service) and a cultural component (e.g.
learning to integrate frequently). The key goals of continuous integration are to find
and address bugs quicker, improve software quality, and reduce the time it takes to
validate and release new software updates.

CI/CD tool
CI/CD tools can help a team automate their development, deployment, and testing. Some tools
specifically handle the integration (CI) side, some manage development and deployment (CD),
while others specialize in continuous testing or related functions.

One of the best known open source tools for CI/CD is the automation server Jenkins. Jenkins
is designed to handle anything from a simple CI server to a complete CD hub.

Continuous integration refers to the build and unit testing stages of the software
release process. Every revision that is committed triggers an automated build and
test.

With continuous delivery, code changes are automatically built, tested, and prepared
for a release to production. Continuous delivery expands upon continuous
integration by deploying all code changes to a testing environment and/or a
production environment after the build stage.

[Link]

What is Jenkins?
Jenkins is an open-source Continuous Integration server written in Java for
orchestrating a chain of actions to achieve the Continuous Integration process in an
automated fashion. Jenkins supports the complete development life cycle of
software from building, testing, documenting the software, deploying, and other
stages of the software development life cycle.

How does Jenkins work?


Jenkins is a server-based application and requires a web server like Apache
Tomcat to run on various platforms like Windows, Linux, macOS, Unix, etc. To
use Jenkins, you need to create pipelines which are a series of steps that a Jenkins
server will take. Jenkins Continuous Integration Pipeline is a powerful instrument
that consists of a set of tools designed to host, monitor, compile and test code, or
code changes, like:

• Continuous Integration Server (Jenkins, Bamboo, CruiseControl, TeamCity,


and others)
• Source Control Tool (e.g., CVS, SVN, GIT, Mercurial, Perforce, ClearCase
and others)
• Build tool (Make, ANT, Maven, Ivy, Gradle, and others)
• Automation testing framework (Selenium, Appium, TestComplete, UFT,
and others)

Why use Continuous Integration with Jenkins?


Some people might think that the old-fashioned way of developing the software is
the better way. Let’s understand the advantages of CI with Jenkins with the
following example

Let us imagine, that there are around 10 developers who are working on a shared
repository. Some developer completes their task in 25 days while others take 30
days to complete.

Before Jenkins After Jenkins

The code is built and test as soon as


Developer commits code. Jenkin
Once all Developers had completed their will build and test code many times
assigned coding tasks, they used to commit their during the day
code all at same time. Later, Build is tested and If the build is successful, then
deployed. Jenkins will deploy the source into
the test server and notifies the
Code commit built, and test cycle was very
deployment team.
infrequent, and a single build was done after
many days.
If the build fails, then Jenkins will
notify the errors to the developer
team.
Since the code was built all at once, some
The code is built immediately after
developers would need to wait until other
any of the Developer commits.
developers finish coding to check their build
Since the code is built after each
It is not an easy task to isolate, detect, and fix commit of a single developer, it’s
errors for multiple commits. easy to detect whose code caused
the built to fail
Code build and test process are entirely manual, Automated build and test process
so there are a lot of chances for failure. saving timing and reducing defects.
The code is deployed once all the errors are fixed The code is deployed after every
and tested. successful build and test.
The development cycle is fast. New
Development Cycle is slow features are more readily available
to users. Increases profits.

Comparison of cloud service

Full Stack Developers and DevOps

Both are, in a sense, two sides of the same coin. It's difficult to decide which side to play on. Both are
highly able experts. So, they strive to deliver software on time and with zero errors. What separates
them from one another are the ideas and tactics them to meet their aims.

They are both giving contributors to the growing firm. So, they desire more flexibility and agility. Let's
look at the following points to better grasp the parallels between both Coders.

Before fixing which one to hire. So, it's a good idea to figure out what your firm's current needs are.
The following are the critical factors that must conclude.
FSD

Week 4

HTML
• HTML stands for Hyper Text Markup Language
• HTML is the standard markup language for Web pages
• HTML elements are the building blocks of HTML pages
• HTML elements are represented by <> tags

CSS
• CSS stands for Cascading Style Sheets
• CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
• CSS saves a lot of work. It can control the layout of multiple web pages all at once
• External style sheets are stored in CSS files

CSS Syntax
A CSS rule consists of a selector and a declaration block.

The selector points to the HTML element you want to style.


The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded
by curly braces.

Dept. CSE Page 1


FSD

<html><head>
<style>
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
</style>
</head>
<body>
<h1>My First CSS Example</h1>
<p>This is a paragraph.</p>
</body>
</html>

CSS Selectors
A CSS selector selects the HTML element(s) you want to style.
We can divide CSS selectors into five categories:
• Simple selectors (select elements based on name, id, class)
• Combinator selectors (select elements based on a specific relationship between them)
• Pseudo-class selectors (select elements based on a certain state)
• Pseudo-elements selectors (select and style a part of an element)
• Attribute selectors (select elements based on an attribute or attribute value)

Dept. CSE Page 2


FSD

The CSS element Selector


The element selector selects HTML elements based on the element name.
<html><head>
<style>
p{
text-align: center;
color: red;
}
</style></head>
<body>
<p>Every paragraph will be affected by the style.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body></html>

The CSS id Selector


The id selector uses the id attribute of an HTML element to select a specific element.
To select an element with a specific id, write a hash (#) character, followed by the id of the
element.
<html><head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>
</body></html>

Dept. CSE Page 3


FSD

The CSS class Selector


The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
<html><head><style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1 class="center">Red and center-aligned heading</h1>
<p class="center">Red and center-aligned paragraph.</p>
</body></html>

The CSS Universal Selector


The universal selector (*) selects all HTML elements on the page.
<!DOCTYPE html>
<html><head>
<style>
*{
text-align: center;
color: blue;
}
</style></head>
<body>
<h1>Hello world!</h1>
<p>Every element on the page will be affected by the style.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body></html>

Dept. CSE Page 4


FSD

The CSS Grouping Selector


The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>
</body>
</html>

Three Ways to Insert CSS


There are three ways of inserting a style sheet:
• External CSS
• Internal CSS
• Inline CSS

External CSS
With an external style sheet, you can change the look of an entire website by changing just one
file
Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.

Dept. CSE Page 5


FSD

<html>
<head>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

[Link]
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}

Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.

<html>
<head>
<style>
body {
background-color: linen;
}

Dept. CSE Page 6


FSD

h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain
any CSS property.
<html><body>
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
</body>
</html>

What is JavaScript?
• An object-oriented computer programming language commonly used to create interactive
effects within web browsers.
• JavaScript is a text-based programming language used both on the client-side and
server-side.
• Where HTML and CSS are languages that give structure and style to web pages,
JavaScript gives web pages interactive elements that engage a user
• JavaScript programs can be inserted almost anywhere into an HTML document using
the <script> tag.

Dept. CSE Page 7


FSD

<html>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>

JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().


<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='[Link]("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>

JavaScript Statements
• In a programming language, the list of programming instructions are called statements.
• A JavaScript program is a list of programming statements.
• JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and
Comments.

Comments
Single line comments start with //
Multi-line comments start with /* and end with */

Dept. CSE Page 8


FSD

Variables
Variables are containers for storing data (storing data values).
In this example, x, y, and z, are variables, declared with the var keyword:
var x = 5;
var y = 6;

Declaring a JavaScript Variable


• Using var
• Using let
• Using const

<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x=5;
var y = 6;
var z = x + y;
[Link]("demo").innerHTML ="The value of z is: " + z;
</script>
</body>
</html>

Practice: <script>
var x = 5;
var y = 6;
var z = x + y;
[Link]("demo").innerHTML ="The value of z is: " + z;
</script>

Dept. CSE Page 9


FSD

Practice: <script>
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
[Link]("demo").innerHTML ="The total is: " + total;
</script>

Constants: Variables defined with const cannot be Redeclared and cannot be Reassigned.

const PI = 3.14;

Data types

DataTypes Description Example

String represents textual data 'hello', "hello world!" etc

Number an integer or a floating-point 3, 3.234, 3e-2 etc.

an integer with arbitrary 900719925124740999n , 1n


BigInt
precision etc.

Any of two values: true or


Boolean true and false
false

a data type whose variable is


undefined let a;
not initialized

null denotes a null value let a = null;

Symbol unique and immutable let value = Symbol('hello');

key-value pairs of collection


Object let student = { };
of data

Dept. CSE Page 10


FSD

Interaction
alert
This one we’ve seen already. It shows a message and waits for the user to press “OK”
<script>
alert('HI there'); // with specified content
alert(); // without any specified content
</script>

prompt
The function prompt accepts two arguments:
<script>
// prompt example
let age = prompt('How old are you?');

alert(`You are ${age} years old!`);


</script>

confirm
The syntax:
result = confirm(question);
The function confirm shows a modal window with a question and two buttons: OK and Cancel.
<script>
// confirm example
let isHappy = confirm('Are you Happy?');
alert(`You are ${isHappy}`);
</script>

Dept. CSE Page 11


FSD

Types of JavaScript Operators


There are different types of JavaScript operators:
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• Logical Operators
• Conditional Operators
• Type Operators

Comparisons
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to

Control flow
Control flow in JavaScript is how your computer runs code from top to bottom. It starts from the
first line and ends at the last line, unless it hits any statement that changes the control flow of the
program such as loops, conditionals, or functions.

Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
<html>
<body>
<script>

Dept. CSE Page 12


FSD

function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>

<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>

Setting Up the Environment and Tools for front end development


Installing VS Code
VS Code is a free code editor that runs on Windows, Mac and Linux.
Download VS Code from [Link]

Dept. CSE Page 13


FSD

Install Visual Studio Code by opening the downloaded setup file and following the prompts.

Dept. CSE Page 14


FSD

VS Code extensions
VS Code extensions let you add languages, debuggers, and tools to your installation to support
your development workflow. VS Code's rich extensibility model lets extension authors plug
directly into the VS Code UI and contribute functionality through the same APIs used by VS
Code.
Bring up the Extensions view by clicking on the Extensions icon in the Activity Bar on the side
of VS Code or the View: Extensions command (Ctrl+Shift+X)

JSON
• JSON stands for JavaScript Object Notation
• JSON is a text format for storing and transporting data
• JSON is "self-describing" and easy to understand
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent

Why Use JSON?


The JSON format is syntactically similar to the code for creating JavaScript objects.
JavaScript program can easily convert JSON data into JavaScript objects.
JSON data can easily be sent between computers, and used by any programming language.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
[Link]()
JavaScript also has a built in function for converting an object into a JSON string:
[Link]()

Dept. CSE Page 15


FSD

JSON Syntax Rules


JSON syntax is derived from JavaScript object notation syntax:
• Data is in name/value (key/value) pairs: A name/value pair consists of a field name (in
double quotes), followed by a colon, followed by a value
"name":"John"
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays

JSON Values
In JSON, values must be one of the following data types:
• a string
• a number
• an object
• an array
• a boolean
• null

Practice: <html>
<body>
<h2>Access a JavaScript object</h2>
<p id="demo"></p>
<script>
const myObj = {name:"John", age:30, city:"New York"};
[Link]("demo").innerHTML = [Link];
or
[Link]("demo").innerHTML = myObj["name"];
</script>
</body>
</html>

Dept. CSE Page 16


FSD

[Link]()
A common use of JSON is to exchange data to/from a web server.
When receiving data from a web server, the data is always a string.
Parse the data with [Link](), and the data becomes a JavaScript object.
Practice: <html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = [Link](txt);
[Link]("demo").innerHTML = [Link] + ", " + [Link];
</script>
</body>
</html>

Array as JSON
When using the [Link]() on a JSON derived from an array, the method will return a
JavaScript array, instead of a JavaScript object.
Practice: <html>
<body>
<h2>Parsing a JSON Array.</h2>
<p>Data written as an JSON array will be parsed into a JavaScript array.</p>
<p id="demo"></p>
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = [Link](text);
[Link]("demo").innerHTML = myArr[0];
</script>
</body>
</html>

Dept. CSE Page 17


FSD

[Link]()
A common use of JSON is to exchange data to/from a web server.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with [Link]().
Practice: <html><body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = [Link](obj);
[Link]("demo").innerHTML = myJSON;
</script>
</body></html>

JavaScript Objects
Objects are variables too. But objects can contain many values.
The values are written as name:value pairs (name and value separated by a colon).
Practice: <script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Display some data from the object:
[Link]("demo").innerHTML =[Link] + " is " + [Link] + "
years old.";
or
[Link]("demo").innerHTML =person["firstName"] + " " + person["age"];
</script>

Dept. CSE Page 18


FSD

Object Properties
The name:values pairs in JavaScript objects are called properties
Accessing Object Properties
[Link]
or
objectName["propertyName"]

Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

Property Property Value

firstName John

lastName Doe

age 50

fullName function() {return [Link] + " " + [Link];}

const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};
Note: this refers to the person object.

Dept. CSE Page 19


FSD

Accessing Object Methods


[Link]()
Practice: <script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return [Link] + " " + [Link];
}
};
// Display data from the object:
[Link]("demo").innerHTML = [Link]();
</script>

Constructors: A constructor in Java is a special method that is used to initialize objects


Practice: <script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
[Link] = first;
[Link] = last;
[Link] = age;
}
// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
// Display age
[Link]("demo").innerHTML =
"My father is " + [Link] + ".";
</script>

Dept. CSE Page 20


FSD

JavaScript Object Accessors


Getters and setters allow you to get and set object properties via methods.
This example uses a lang property to get the value of the language property:
Practice: <script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return [Link];
}
};
// Display data from the object using a getter:
[Link]("demo").innerHTML = [Link];
</script>
Practice: <script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "NO",
set lang(value) {
[Link] = value;
}
};
// Set a property using set:
[Link] = "en";
// Display data from the object:
[Link]("demo").innerHTML = [Link];
</script>

Dept. CSE Page 21


FSD

Prototype
All JavaScript objects inherit properties and methods from a prototype.
The prototype property allows you to add new methods to objects constructors:
Practice: <script>
function Person(first, last, age, eye) {
[Link] = first;
[Link] = last;
}
[Link] = "English";
const myFather = new Person("John", "Doe", 50, "blue");
[Link]("demo").innerHTML =
"The nationality of my father is " + [Link];
</script>

ES6
ECMAScript (European Computer Manufacturers Association Script) is a scripting language
based on JavaScript
ECMAScript 2015 was the second major revision to JavaScript.
ECMAScript 2015 is also known as ES6 and ECMAScript 6.

Arrow functions
Arrow functions allows a short syntax for writing function expressions.
You don't need the function keyword, the return keyword, and the curly brackets.
Practice:
<script>
const x = (x, y) => x * y;
[Link]("demo").innerHTML = x(5, 5);
</script>

Dept. CSE Page 22


FSD

Template strings
Template Literals use back-ticks (``) rather than the quotes ("") to define a string:
Practice: <script>
let text = `Hello world!`;
[Link]("demo").innerHTML = text;
</script>

Interpolation
Template literals provide an easy way to interpolate variables and expressions into strings.
The method is called string interpolation.
The syntax is:
${...}

Variable Substitutions
Template literals allow variables in strings:
Practice: <script>
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
[Link]("demo").innerHTML = text;
</script>

JavaScript Object Prototypes


All JavaScript objects inherit properties and methods from a prototype.
Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype:
• Date objects inherit from [Link]
• Array objects inherit from [Link]
• Person objects inherit from [Link]
The [Link] is on the top of the prototype inheritance chain:

Dept. CSE Page 23


FSD

Date objects, Array objects, and Person objects inherit from [Link].
Adding Properties and Methods to Objects
Sometimes you want to add new properties (or methods) to all existing objects of a given type.
Sometimes you want to add new properties (or methods) to an object constructor.

Using the prototype Property


The JavaScript prototype property allows you to add new properties to object constructors:
Practice: <script>
function Person(first, last) {
[Link] = first;
[Link] = last;
}
[Link] = "English";
const myFather = new Person("John", "Doe");
[Link]("demo").innerHTML =
"The nationality of my father is " + [Link];
</script>

The JavaScript prototype property also allows you to add new methods to objects constructors:
Practice: <script>
function Person(first, last, age, eye) {
[Link] = first;
[Link] = last;
[Link] = age;
[Link] = eye;
}
[Link] = function() {
return [Link] + " " + [Link]
};
const myFather = new Person("John", "Doe", 50, "blue");
[Link]("demo").innerHTML ="My father is " + [Link]();

Dept. CSE Page 24


FSD

</script>
The Spread (...) Operator
The ... operator expands an iterable (like an array) into more elements:
Practice: <script>
const cars1 = ["Saab", "Volvo", ..."BMW"];
const cars2 = ["Fiat", "Toyota"];
const combined = [cars1, ...cars2];
[Link]("demo").innerHTML = combined;
</script>

Map
Creating a Map from an Array
A Map holds key-value pairs where the keys can be any datatype.
A Map remembers the original insertion order of the keys.
A Map has a property that represents the size of the map

How to Create a Map


You can create a JavaScript Map by:
• Passing an Array to new Map()
• Create a Map and use [Link]()

new Map()
You can create a Map by passing an Array to the new Map() constructor:
Practice: <script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link]("apples");

Dept. CSE Page 25


FSD

</script>
[Link]()
You can add elements to a Map with the set() method:
Practice:
<script>
// Create a Map
const fruits = new Map();
// Set Map Values
[Link]("apples", 500);
[Link]("bananas", 300);
[Link]("oranges", 200);
[Link]("demo").innerHTML = [Link]("apples");
</script>

Map Methods

Method Description

new Map() Creates a new Map object

set() Sets the value for a key in a Map

get() Gets the value for a key in a Map

clear() Removes all the elements from a Map

delete() Removes a Map element specified by a key

has() Returns true if a key exists in a Map

forEach() Invokes a callback for each key/value pair in a Map

entries() Returns an iterator object with the [key, value] pairs in a Map

keys() Returns an iterator object with the keys in a Map

Dept. CSE Page 26


FSD

values() Returns an iterator object of the values in a Map

Property Description

size Returns the number of Map elements

JavaScript Set
A JavaScript Set is a collection of unique values.
Each value can only occur once in a Set.
A Set can hold any value of any data type.

How to Create a Set


You can create a JavaScript Set by:
• Passing an Array to new Set()
• Create a new Set and use add() to add values
• Create a new Set and use add() to add variables

The new Set() Method


Pass an Array to the new Set() constructor:
<script>
// Create a Set
const letters = new Set(["a","b","c"]);
// Display [Link]
[Link]("demo").innerHTML = [Link];
</script>

Create a Set and add literal values:


<script>
// Create a Set
const letters = new Set();

Dept. CSE Page 27


FSD

// Add Values to the Set


[Link]("a");
[Link]("b");
[Link]("c");
// Display [Link]
[Link]("demo").innerHTML = [Link];
</script>

Create a Set and add variables:


<script>
const letters = new Set(); // Create a Set
// Create Variables
const a = "a";
const b = "b";
const c = "c";
// Add the Variables to the Set
[Link](a);
[Link](b);
[Link](c);
// Display [Link]
[Link]("demo").innerHTML = [Link];
</script>
Practice:<script>
// Create a new Set
const letters = new Set(["a","b","c"]);
// Add a new Element
[Link]("d");
[Link]("e");
// Display [Link]
[Link]("demo").innerHTML = [Link];
</script>

Dept. CSE Page 28


FSD

Set Methods

Method Description

new Set() Creates a new Set

add() Adds a new element to the Set

delete() Removes an element from a Set

has() Returns true if a value exists

clear() Removes all elements from a Set

forEach() Invokes a callback for each element

values() Returns an Iterator with all the values in a Set

keys() Same as values()

entries() Returns an Iterator with the [value,value] pairs from a Set

Property Description

size Returns the number elements in a Set

Dept. CSE Page 29


FSD

What is meant by TypeScript?


• TypeScript is a syntactic superset of JavaScript which adds static typing.
• This basically means that TypeScript adds syntax on top of JavaScript, allowing
developers to add types.
• TypeScript being a "Syntactic Superset" means that it shares the same base syntax as
JavaScript, but adds something to it.

Why TypeScript?
• TypeScript uses compile time type checking. Which means it checks if the specified
types match before running the code, not while running the code
• JavaScript is better suited for small-scale applications, while TypeScript is better for
larger applications.
• TypeScript is better than JavaScript in terms of language features, reference validation,
project scalability, collaboration within and between teams, developer experience, and
code maintainability.

Setting up development environment for TypeScript


Pre-requisite to install TypeScript
1. Text Editor or IDE
2. [Link] Package Manager (npm)
3. The TypeScript compiler

Ways to install TypeScript


There are two ways to install TypeScript:
1. Install TypeScript using [Link] Package Manager (npm).
2. Install the TypeScript plug-in in your IDE (Integrated Development Environment).

Install TypeScript using [Link] Package Manager (npm)


Step-1 Install [Link]. It is used to setup TypeScript on our local computer.
To install [Link] on Windows, go to the following link: [Link]
nodejs

Dept. CSE Page 30


FSD

To verify the installation was successful, enter the following command in the Terminal Window.
node -v
npm -v

Step-2 Install TypeScript. To install TypeScript, enter the following command in the Terminal
Window.
• npm install typescript --save-dev //As dev dependency
• npm install typescript -g //Install as a global module
or
• npm install -g typescript
• npm install typescript@latest -g //Install latest if you have an older version

Step-3 To verify the installation was successful, enter the command $ tsc -v in the Terminal
Window.

Install Live server


npm install -g live-server

Create and run first program in TypeScript

• open command prompt


• go to d: drive(any drive)
• d:\>mkdir typescript
• d:\>cd typescript
• d:\typescript> npm install typescript --save-dev
• open visual studio code
• file-open folder-choose typescript folder from d:
• create new file- save it as [Link](any [Link])
• Write the below code and save it
• [Link]("Hello World");

Dept. CSE Page 31


FSD

• go to command prompt and compile the program


• tsc [Link]
• run the program
• node [Link]
• Observe the output

Basic Types

Built-in Data
Type keyword Description

It is used to represent both Integer as well as Floating-Point


Number number numbers

Boolean boolean Represents true and false

String string It is used to represent a sequence of characters

Void void Generally used on function return-types

Null null It is used when an object does not have any value

Undefined undefined Denotes value given to uninitialized variable

If variable is declared with any data-type then any type of


Any any value can be assigned to that variable

Dept. CSE Page 32


FSD

Example
let a: null = null;
let b: number = 123;
let c: number = 123.456;
let d: string = ‘Geeks’;
let e: undefined = undefined;
let f: boolean = true;
[Link](a);
[Link](b);
[Link](c);
[Link](d);
[Link](e);
[Link](f);
let a: any = null;
let b: any =123;
let c: any = 123.456;
let d: any = ‘Geeks’;
let e: any = undefined;
let f: any = true;

Control flow statement


TypeScript control statements:
1. If Statement
2. If else statement
3. if else if statement

TypeScript If Statement:
If statement is used to execute a block of statements if specified condition is true.
if(condition){
//Block of TypeScript statements.
}

Dept. CSE Page 33


FSD

TypeScript If Else Statement:


If else statement is used to execute either of two block of statements depends upon the condition.
If condition is true then if block will execute otherwise else block will execute.
if(condition){
//Block of TypeScript statements1.
}else{
//Block of TypeScript statements2.
}

TypeScript If Else If Statement:


If else statement is used to execute one block of statements from many depends upon the
condition. If condition1 is true then block of statements1 will be executed, else if condition2 is
true block of statements2 is executed and so on. If no condition is true, then else block of
statements will be executed.
if(condition1){
//Block of TypeScript statements1.
}else if(condition2){
//Block of TypeScript statements2.
} . . . else if(conditionn){
//Block of TypeScript statementsn.
}else{
//Block of TypeScript statements.
}

Example
var num:number = 2;
if(num==1){
[Link]("TypeScript Statement 1");
}
else if(num==2){
[Link]("TypeScript Statement 2");

Dept. CSE Page 34


FSD

}
else if(num==3){
[Link]("TypeScript Statement 3");
}
else{
[Link]("TypeScript Statement n");
}

TypeScript - for Loops


1. for loop
2. for..of loop
3. for..in loop
for Loop
The for loop is used to execute a block of code a given number of times, which is specified by
a condition.
for (first expression; second expression; third expression ) {
// statements to be executed repeatedly
}

for (let i = 0; i < 3; i++) {


[Link] ("Block statement execution no." + i);
}

for...of Loop
TypeScript includes the for...of loop to iterate and access elements of an array, list, or tuple
collection.
let arr = [10, 20, 30, 40];
for (var val of arr) {
[Link](val); // prints values: 10, 20, 30, 40
}

Dept. CSE Page 35


FSD

for...in Loop
Another form of the for loop is for...in. This can be used with an array, list, or tuple.
let arr = [10, 20, 30, 40];
for (var index in arr) {
[Link](index); // prints indexes: 0, 1, 2, 3
[Link](arr[index]); // prints elements: 10, 20, 30, 40
}

TypeScript - while Loop


The while loop is another type of loop that checks for a specified condition before beginning
to execute the block of statements. The loop runs until the condition value is met.
while (condition expression) {
// code block to be executed
}

let i: number = 2;
while (i < 4) {
[Link]( "Block statement execution no." + i )
i++;
}

do..while loop
The do..while loop is similar to the while loop, except that the condition is given at the end of
the loop. The do..while loop runs the block of code at least once before checking for the
specified condition.
do {
// code block to be executed
}
while (condition expression);

Dept. CSE Page 36


FSD

let i: number = 2;
do {
[Link]("Block statement execution no." + i )
i++;
} while ( i < 4)

Functions
In TypeScript, functions can be of two types: named and anonymous.
Named Functions
A named function is one where you declare and call a function by its given name.
function display() {
[Link]("Hello TypeScript!");
}
display(); //Output: Hello TypeScript

Functions can also include parameter types and return type.


function Sum(x: number, y: number) : number {
return x + y;
}
Sum(2,3); // returns 5

Anonymous Function
• An anonymous function is one which is defined as an expression.
• This expression is stored in a variable.
• So, the function itself does not have a name.
• These functions are invoked using the variable name that the function is stored in.

let display = function() {


[Link]("Hello TypeScript!");
};
display (); //Output: Hello TypeScript!

Dept. CSE Page 37


FSD

An anonymous function can also include parameter types and return type.
let Sum = function(x: number, y: number) : number
{
return x + y;
}
Sum(2,3); // returns 5

Function Parameters
Parameters are values or arguments passed to a function. In TypeScript, the compiler expects
a function to receive the exact number and type of arguments as defined in the function
signature.
function Greet(greeting: string, name: string ) : string {
return greeting + ' ' + name + '!';
}
Greet('Hello','Steve');

Default Parameters
TypeScript provides the option to add default values to parameters.
function Greet(name: string, greeting: string = "Hello") : string {
return greeting + ' ' + name + '!';
}
Greet('Steve');//OK, returns "Hello Steve!"
Modern UI technologies
1. React
2. Angular
3. Flutter
4. [Link]
5. JQuery
6. Emberjs
7. Semantic UI
8 Backbonejs
9. Foundation
10. Svelte

Dept. CSE Page 38


FSD

Week 5

Introduction to React
React is an open source frontend JavaScript library for building complex UIs; it allows the
programmers to create complex UIs from smaller components.
React is a declarative, efficient, and flexible JavaScript library for building user interfaces.

Setting up React development

Step 1: Install NodeJS.


Download [Link] and npm from [Link]

Dept. of CSE, JSSPN Page 1


FSD

Test that [Link] and npm were installed successfully by running the commands
node -v
npm -v.

Dept. of CSE, JSSPN Page 2


FSD

Step 2:
npx create-react-app myapp
cd myapp
npm start

Anatomy of React app (Folder structure)


• [Link] is a markdown file that includes a lot of helpful tips and links that can help
you while learning to use Create React App.
• node_modules is a folder that includes all of the dependency-related code that Create React
App has installed.
• [Link] that manages our app dependencies
• .gitignore is a file that is used to exclude files and folders from being tracked by Git.
• public is a folder that we can use to store our static assets, such as images, svgs, and fonts for
our React app.
• src is a folder that contains our source code.

What is [Link]?
• [Link] is an open source server environment (free)
• [Link] runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• [Link] uses JavaScript on the server

Dept. of CSE, JSSPN Page 3


FSD

What Can [Link] Do?


• [Link] can generate dynamic page content
• [Link] can create, open, read, write, delete, and close files on the server
• [Link] can collect form data
• [Link] can add, delete, modify data in your database

What is JSX?
• JSX stands for JavaScript XML.
• JSX allows us to write HTML in React.
• JSX makes it easier to write and add HTML in React.
• Consider this variable declaration:
• const element = <h1>Hello, world!</h1>;
• JSX is a XML syntax extension. Just like HTML, JSX tags can have a tag names,
attributes, and children. If an attribute is wrapped in curly braces, the value is a
JavaScript expression.

import React from 'react';


import ReactDOM from 'react-dom/client';

const myFirstElement = <h1>Hello React!</h1>

const root = [Link]([Link]('root'));


[Link](myFirstElement);

Expressions in JSX
With JSX you can write expressions inside curly braces { }
The expression can be a React variable, or property, or any other valid JavaScript expression.
JSX will execute the expression and return the result

Ex:
import React from 'react';
import ReactDOM from 'react-dom/client';

const name='niranjan';
const element=<h1>Hello, { name }</h1>;
const root = [Link]([Link]('root'));
[Link](element);

Dept. of CSE, JSSPN Page 4


FSD

Ex2:
import React from 'react';
import ReactDOM from 'react-dom/client';

const myElement = <h1>React is {5 + 5} times better with JSX</h1>;

const root = [Link]([Link]('root'));


[Link](myElement);

Ex3:
import React from 'react';
import ReactDOM from 'react-dom/client';

const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
const root = [Link]([Link]('root'));
[Link](myElement);

Specifying Attributes with JSX


JSX allows us to use attributes with the HTML elements.
JSX uses camelcase convention for attributes.
import React from 'react';
import ReactDOM from 'react-dom/client';
const myElement = <h1 className="myclass">Hello World</h1>;
const root = [Link]([Link]('root'));
[Link](myElement);

Specifying Children with JSX


JSX tags may contain children:
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);

Dept. of CSE, JSSPN Page 5


FSD

Rendering
React renders HTML to the web page by using a function called render().
The purpose of the function is to display the specified HTML code inside the specified
HTML element.

Rendering Elements
Rendering an Element in React: In order to render any element into the Browser DOM, we
need to have a container or root DOM element. It is almost a convention to have a div
element with the id=”root” or id=”app” to be used as the root DOM element. Let’s suppose
our [Link] file has the following statement inside it.
<div id="root"></div>

Filename [Link]: Now, in order to render a simple React Element to the root node, we
must write the following in the [Link] file.
import React,{ Component } from 'react';
class App extends Component {
render() {
return (
<div>
<h1>Welcome to GeeksforGeeks!</h1>
</div>
);
}
} export default App;

What is the DOM?


The DOM (Document Object Model) represents the web page as a tree structure. Any piece
of HTML that we write is added as a node, to this tree.
With JavaScript, we can access any of these nodes (HTML elements) and update their styles,
attributes, and so on.

Dept. of CSE, JSSPN Page 6


FSD

React-DOM
ReactDOM is a package that provides DOM specific methods that can be used at the top
level of a web app to enable an efficient way of managing DOM elements of the web page.

Pre-requisite: To use the ReactDOM in any React web app we must first import
ReactDOM from the react-dom package by using the following code snippet:

import ReactDOM from 'react-dom'

render() Function
This function is used to render a single React Component or several Components wrapped
together in a Component or a div element.
[Link](element, container, callback)
Parameters: This method can take a maximum of three parameters as described below.
• element: This parameter expects a JSX expression or a React Element to be rendered.
• container: This parameter expects the container in which the element has to be
rendered.
• callback: This is an optional parameter that expects a function that is to be executed
once the render is complete.

Dept. of CSE, JSSPN Page 7


FSD

Virtual DOM in React


Virtual DOM in React is a “virtual” representation of the actual DOM. It is nothing but an
object created to replicate the actual DOM.

What are React Components?


• React components are independent and reusable code.
• They are the building blocks of any React application.
• Components serve the same purpose as JavaScript functions, but work individually to
return JSX code as elements for our UI.
• Components usually come in two types, functional components and class components

Functional Components

import React from 'react';


import ReactDOM from 'react-dom/client';

function Car() {
return <h2>Hi, I am a Car!</h2>;
}

const root = [Link]([Link]('root'));


[Link](<Car />);

Class Components
A class component must include the extends [Link] statement.
The component also requires a render() method, this method returns HTML.

import React from 'react';


import ReactDOM from 'react-dom/client';

class Car extends [Link] {


render() {
return <h2>Hi, I am a Car!</h2>;
}
}

const root = [Link]([Link]('root'));


[Link](<Car />);

Dept. of CSE, JSSPN Page 8


FSD

Rendering a Component
import React from 'react';
import ReactDOM from 'react-dom/client';
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
const root = [Link]([Link]('root'));
[Link](<Car />);

Composing Components
function Welcome(props) {
return <h1>Hello, {[Link]}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div> );
}
const root = [Link]([Link]('root'));
[Link](<App />);

Create your first React Component.


When creating a React component, the component's name MUST start with an upper case
letter.
import React from 'react';
import ReactDOM from 'react-dom/client';
function Car() {
return <h2>Hi, I am a Car!</h2>;
}const root = [Link]([Link]('root'));
[Link](<Car />);

Dept. of CSE, JSSPN Page 9


FSD

What are props?


Props is short for properties and they are used to pass data between React components.
React’s data flow between components is uni-directional (from parent to child only).
import React from 'react';
import ReactDOM from 'react-dom/client';

class ParentComponent extends [Link] {


render() {
return (
<ChildComponent name="First Child" />
);
}
}
const ChildComponent = (props) => {
return <p>{[Link]}</p>;
};
const root = [Link]([Link]('root'));
[Link](<ParentComponent />);

import React from 'react';


import ReactDOM from 'react-dom/client';

function Name(props) {
return <h2>My name { [Link] }!</h2>;
}

function Display() {
return (
<>
<Name name="Niranjan" />
</>
);
}

const root = [Link]([Link]('root'));


[Link](<Display />);

Dept. of CSE, JSSPN Page 10


FSD

What is state?
React has another special built-in object called state, which allows components to create and
manage their own data. So unlike props, components cannot pass data with state, but they can
create and manage it internally.

import React from 'react';


import ReactDOM from 'react-dom/client';

class Test extends [Link] {


constructor(props) {
super(props);
[Link] = {
id: 1,
name: "test"
};
}

render() {
return (
<div>
<p>{[Link]}</p>
<p>{[Link]}</p>
</div>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Test />);

Communication between components using Props


You can pass props down to child components.
import React from 'react';
class Parent extends [Link] {
render() {
const variable = 5;
return (
<div>
<Child message="message for child" />
<Child message={variable} />
</div>
);
}
}
Dept. of CSE, JSSPN Page 11
FSD

class Child extends [Link] {


render() {
return <h1>{[Link]}</h1>
}
}
export default Parent;

What is the React component lifecycle?


In React, components go through a lifecycle of events:
1. Mounting (adding nodes to the DOM)
2. Updating (altering existing nodes in the DOM)
3. Unmounting (removing nodes from the DOM)
4. Error handling (verifying that your code works and is bug-free)
Mounting
Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when mounting a component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()
The render() method is required and will always be called, the others are optional and will be
called if you define them.
constructor
The constructor() method is called with the props, as arguments, and you should always start
by calling the super(props) before anything else, this will initiate the parent's constructor
method and allows the component to inherit methods from its parent ([Link]).

getDerivedStateFromProps
The getDerivedStateFromProps() method is called right before rendering the element(s) in
the [Link] is the natural place to set the state object based on the initial props.
It takes state as an argument, and returns an object with changes to the state.
import React from 'react';
import ReactDOM from 'react-dom/client';

Dept. of CSE, JSSPN Page 12


FSD

class Header extends [Link] {


constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: [Link] };
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Header favcol="yellow"/>);

render
The render() method is required, and is the method that actually outputs the HTML to the
DOM.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Header extends [Link] {
render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Header />);

Dept. of CSE, JSSPN Page 13


FSD

componentDidMount
The componentDidMount() method is called after the component is rendered.
This is where you run statements that requires that the component is already placed in the
DOM.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Header extends [Link] {
constructor(props) {
super(props);
[Link] = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
[Link]({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {[Link]}</h1>
);
}
}
const root = [Link]([Link]('root'));
[Link](<Header />);

Updating
A component is updated whenever there is a change in the component's state or props.
React has five built-in methods that gets called, in this order, when a component is updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()

Dept. of CSE, JSSPN Page 14


FSD

Unmounting
The next phase in the lifecycle is when a component is removed from the DOM,
or unmounting as React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
• componentWillUnmount()

Error Handling
Error Handling methods are called when there is an error during rendering, in a lifecycle
method, or in the constructor of any child component.
• static getDerivedStateFromError()
• componentDidCatch()

import React from 'react';


import ReactDOM from 'react-dom/client';

import { Component } from "react";

class ErrorBoundary extends [Link] {


constructor(props) {
super(props);
[Link] = { hasError: false };
}

static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}

componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}

render() {
if ([Link]) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}

return [Link];

Dept. of CSE, JSSPN Page 15


FSD

}
}

export default ErrorBoundary;

Handling Events
React events are written in camelCase syntax:
onClick instead of onclick.
React event handlers are written inside curly braces:
onClick={shoot} instead of onClick="shoot()".

import React from 'react';


import ReactDOM from 'react-dom/client';

function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
const root = [Link]([Link]('root'));
[Link](<Football />);

Passing Arguments
To pass an argument to an event handler, use an arrow function.
import React from 'react';
import ReactDOM from 'react-dom/client';

function Football() {
const shoot = (a) => {
alert(a);
}

Dept. of CSE, JSSPN Page 16


FSD

return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
const root = [Link]([Link]('root'));
[Link](<Football />);

Conditional Rendering
if Statement
We can use the if JavaScript operator to decide which component to render.

import React from 'react';


import ReactDOM from 'react-dom/client';

function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = [Link];
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
const root = [Link]([Link]('root'));
// Try changing to isLoggedIn={true}:
[Link](<Greeting isLoggedIn={false} />);

Dept. of CSE, JSSPN Page 17


FSD

Ternary Operator
condition ? true : false

import React from 'react';


import ReactDOM from 'react-dom/client';

function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = [Link];
return (
<>
{ isLoggedIn ? <UserGreeting/> : <GuestGreeting/> }
</>
);
}
const root = [Link]([Link]('root'));
// Try changing to isLoggedIn={true}:
[Link](<Greeting isLoggedIn={true} />);

Lists & Keys

Rendering Multiple Components


You can build collections of elements and include them in JSX using curly braces {}.
• The list is used to display data in an ordered format and is traversed using the map()
function.
• lists are a continuous group of text or images.

Dept. of CSE, JSSPN Page 18


FSD

import React from 'react';


import ReactDOM from 'react-dom/client';
function NumberList(props) {
const numbers = [Link];
const listItems = [Link]((number) =><li>{number}</li>);
return (
<ul>{listItems}</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
const root = [Link]([Link]('root'));
[Link](<NumberList numbers={numbers} />);
Keys
• Keys are used to identify which items have changed, are added, or are removed.
• Keys should be given inside the array to give the elements a stable identity.

import React from 'react';


import ReactDOM from 'react-dom';
function App(props) {
const numbers = [Link];
return (
<div>
<ul>
{[Link]((number) =>
<li key={[Link]()}>{number}</li>
)}
</ul>
</div>
);
}
const numbers = ['Indore', 'Mumbai', 'Pune', 'Hyderabad', 'Banglore'];
const root = [Link]([Link]('root'));

Dept. of CSE, JSSPN Page 19


FSD

[Link](<App numbers={numbers} />);


export default App;

Use of HTML tags in forms like select, input, file, textarea, etc.

<html>
<head>
<title>Form Elements</title>
</head>
<body>
<form>
<lable>Text Box</lable>
<input type="text" id="t1" name="name" value=""/><br><br>
Radio Button: <br>
<input type="radio" id="r1" name="" value=""/>Male<br> <br>
<input type="radio" id="r1" name="" value=""/>FeMale<br><br>
Check Box:<input type="checkbox" id="c1" name="" value=""/><br><br>
File:<input type="file" id="e1" name="file" value=""/><br><br>

Select:<br>
<label>Sem</label>
<select name="sem" id="sem">
<option value="1">1 Sem</option>
<option value="2">2 Sem</option>
</select><br><br>

Text Area:<br>
<textarea id="ta1" name="textarea" rows="4" cols="50">
At [Link] you will learn how to make a website.
</textarea><br><br>

<fieldset>

Dept. of CSE, JSSPN Page 20


FSD

<legend>Personal Details:</legend>
<label>First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label>Last name:</label>
<input type="text" id="lname" name="lname"><br><br>

</fieldset><br><br>

Button:<input type="button" id="t1" name="" value="Submit"/><br>


</form>
</body>
</html>

Controlled components
• In HTML, form elements such as <input>, <textarea>, and <select> typically
maintain their own state and update it based on user input.
• In React, mutable state is typically kept in the state property of components, and only
updated with setState().

The input Tag


import React from 'react';
import ReactDOM from 'react-dom/client';
class NameForm extends [Link] {
constructor(props) {
super(props);
[Link] = {value: ''};
[Link] = [Link](this);
[Link] = [Link](this);
}
handleChange(event) {
[Link]({value: [Link]});
}
handleSubmit(event) {

Dept. of CSE, JSSPN Page 21


FSD

alert('A name was submitted: ' + [Link]);


[Link]();
}
render() {
return (
<form onSubmit={[Link]}>
<label>
Name:
<input type="text" value={[Link]} onChange={[Link]} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
const root = [Link]([Link]('root'));
[Link](<NameForm />);

The textarea Tag


render() {
return (
<form onSubmit={[Link]}>
<label>
Essay:
<textarea value={[Link]} onChange={[Link]} />
</label>
<input type="submit" value="Submit" />
</form>
);
}

The select Tag


render() {

Dept. of CSE, JSSPN Page 22


FSD

return (
<form onSubmit={[Link]}>
<label>Pick your favorite flavor:
<select value={[Link]} onChange={[Link]}>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
The file input Tag

<input type="file" />

Uncontrolled components
• In a controlled component, form data is handled by a React component. The
alternative is uncontrolled components, where form data is handled by the DOM
itself.
• To write an uncontrolled component, instead of writing an event handler for every
state update, you can use a ref to get form values from the DOM.

The input Tag


import React from 'react';
import ReactDOM from 'react-dom/client';
class NameForm extends [Link] {
constructor(props) {
super(props);
[Link] = [Link](this);
[Link] = [Link]();
}

Dept. of CSE, JSSPN Page 23


FSD

handleSubmit(event) {
alert('A name was submitted: ' + [Link]);
[Link]();
}
render() {
return (
<form onSubmit={[Link]}>
<label>
Name:
<input type="text" ref={[Link]} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
const root = [Link]([Link]('root'));
[Link](<NameForm />);

The file input Tag


import React from 'react';
import ReactDOM from 'react-dom/client';
class FileInput extends [Link] {
constructor(props) {
super(props);
[Link] = [Link](this);
[Link] = [Link]();
}
handleSubmit(event) {
[Link]();
alert(
`Selected file - ${[Link][0].name}`
);

Dept. of CSE, JSSPN Page 24


FSD

}
render() {
return (
<form onSubmit={[Link]}>
<label>Upload file:
<input type="file" ref={[Link]} />
</label>
<br />
<button type="submit">Submit</button>
</form>
); }}
const root = [Link]([Link]('root'));
[Link](<FileInput />);
Lifting State Up
In React, it is recommended to make a common pattern while using the same state in multiple
components. “Lifting state up” is a common pattern used in React to share state among
multiple components to avoid complex and unnecessary patterns for state management.

Testing single page application


Filename: [Link]
.App {
text-align: center;
background-color:green;
}
.label{
display: block;
font-size: larger;
color: white;
padding: 5px;
}
.input{
font-size: larger;
padding: 5px;
margin: 2px;

Dept. of CSE, JSSPN Page 25


FSD

}
.btn{
color: white;
display: block;
margin: 10px auto;
}
.messages{
display: flex;
justify-content: center;
}

Filename: [Link]
import './[Link]';
import Form from "./Form"
function App() {
return (
<div className="App">
<Form />
</div>
);
}
export default App;

Filename: [Link]
import { useState } from 'react';
export default function Form() {
// States for registration
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
// States for checking the errors
const [submitted, setSubmitted] = useState(false);
const [error, setError] = useState(false);

Dept. of CSE, JSSPN Page 26


FSD

// Handling the name change


const handleName = (e) => {
setName([Link]);
setSubmitted(false);
};
// Handling the email change
const handleEmail = (e) => {
setEmail([Link]);
setSubmitted(false);
};
// Handling the password change
const handlePassword = (e) => {
setPassword([Link]);
setSubmitted(false);
};
// Handling the form submission
const handleSubmit = (e) => {
[Link]();
if (name === '' || email === '' || password === '') {
setError(true);
} else {
setSubmitted(true);
setError(false);
}
};
// Showing success message
const successMessage = () => {
return (
<div
className="success"
style={{
display: submitted ? '' : 'none',

Dept. of CSE, JSSPN Page 27


FSD

}}>
<h1>User {name} successfully registered!!</h1>
</div>
);
};

// Showing error message if error is true


const errorMessage = () => {
return (
<div
className="error"
style={{
display: error ? '' : 'none',
}}>
<h1>Please enter all the fields</h1>
</div>
);
};
return (
<div className="form">
<div>
<h1>User Registration</h1>
</div>
{/* Calling to the methods */}
<div className="messages">
{errorMessage()}
{successMessage()}
</div>
<form>
{/* Labels and inputs for form data */}
<label className="label">Name</label>
<input onChange={handleName} className="input"
value={name} type="text" />

Dept. of CSE, JSSPN Page 28


FSD

<label className="label">Email</label>
<input onChange={handleEmail} className="input"
value={email} type="email" />
<label className="label">Password</label>
<input onChange={handlePassword} className="input"
value={password} type="password" />
<button onClick={handleSubmit} className="btn" type="submit">
Submit
</button>
</form>
</div>
);
}

Dept. of CSE, JSSPN Page 29


FSD

Week 6
Context
• Context provides a way to pass data through the component tree without having to pass
props down manually at every level.
• In a typical React application, data is passed top-down (parent to child) via props.
• Context provides a way to share values between components without having to explicitly
pass a prop through every level of the tree.

import React from 'react';


import ReactDOM from 'react-dom/client';
import { createContext, useContext } from "react";

const Context = createContext("abc");

export function Main() {


const value = "My Context Value";

return (
<[Link] value={value}>
<MyComponent />
</[Link]>
);
}

function MyComponent() {
const value = useContext(Context);

return <span>{value}</span>;
}
const root = [Link]([Link]('root'));
[Link](<MyComponent/>);

By using Props
import React from 'react';
import ReactDOM from 'react-dom/client';

function Name(props) {
return <h2>My name { [Link] }!</h2>; }

Dept. of CSE, JSSPN Page 1


FSD

function Display() {
return (
<>
<Name name="Niranjan" />
</>
);
}
const root = [Link]([Link]('root'));
[Link](<Display />);

React Fragments
• Allow you to wrap or group multiple elements without adding an extra node to the DOM.
• This can be useful when rendering multiple child elements/components in a single parent
component.

import React from 'react';


import ReactDOM from 'react-dom/client';
function Column() {
return (
<[Link]>
<h1>JSS</h1>
<h2>Polytechnic</h2>
</[Link]>
);
}
const root = [Link]([Link]('root'));
[Link](<Column/>);

React Higher-Order Component


• The React Higher-Order Components is an advanced technique that takes a component and
returns a new component. It is used for reusing component logic.

function sub (x, y) {


return x - y }
function higherOrderComp(x, subReference) {
return subReference(x, 10) }
higherOrderComp(50, sub)

Dept. of CSE, JSSPN Page 2


FSD

React Router
• React Router is a standard library for routing in React.
• It enables the navigation among views of various components in a React Application,
allows changing the browser URL, and keeps the UI in sync with the URL

• Route params are parameters whose values are set dynamically in a page’s URL.
• This allows a route to render the same component while passing that component the
dynamic portion of the URL, so that it can change its data based on the parameter.
• Examples include things like IDs for products, books, movies, users etc
<Route exact path="/movie/:id" component={MovieDetailsContainer} />

React router key components


• routers, like <BrowserRouter> and <HashRouter>
<BrowserRouter>: It is used for handling the dynamic URL.
<HashRouter>: It is used for handling the static request.

function App() {
return <h1>Hello React Router</h1>;
}

[Link](
<BrowserRouter>
<App />
</BrowserRouter>,
[Link]("root")
);

• route matchers, like <Route> and <Switch>


<div>
<Switch>
{ /* If the current URL is /contact, this route is rendered */
}
<Route path="/contact">
<AllContacts />
</Route>
{ /*If none of the previous routes render anything, this route acts as a fallback */ }

Dept. of CSE, JSSPN Page 3


FSD

<Route path="/">
<Home />
</Route>
</Switch>
</div>

• navigation, like <Link>, <NavLink>, and <Redirect>


i. React Router provides a <Link> component to create links in your application.
Wherever you render a <Link>, an anchor (<a>) will be rendered in your HTML
document.
Syntax: <Link to="/">Home</Link>
// <a href="/">Home</a>

ii. The <NavLink> is a special type of <Link> that can style itself as “active” when
its to prop matches the current location.
Syntax: <NavLink to="/react" activeClassName="hurray">
React
</NavLink>

iii. Any time that you want to force navigation, you can render a <Redirect>. When
a <Redirect> renders, it will navigate using its to prop.
Syntax: <Redirect to="/login" />

Add React Router


• To add React Router in your application, run this in the terminal from the root directory of
the application:
Command: npm i -D react-router-dom
Create a folder name called pages. Within a pages create following files.
[Link]
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";

Dept. of CSE, JSSPN Page 4


FSD

import Contact from "./pages/Contact";


import NoPage from "./pages/NoPage";

export default function App() {


return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="blogs" element={<Blogs />} />
<Route path="contact" element={<Contact />} />
<Route path="*" element={<NoPage />} />
</Route>
</Routes>
</BrowserRouter>
);
}

const root = [Link]([Link]('root'));


[Link](<App />);

[Link]
const Blogs = () => {
return <h1>Blog Articles</h1>;
};

export default Blogs;

[Link]
const Contact = () => {
return <h1>Contact Me</h1>;
};

export default Contact;

[Link]
const Home = () => {
return <h1>Home</h1>;
};
export default Home;

Dept. of CSE, JSSPN Page 5


FSD

[Link]
import { Outlet, Link } from "react-router-dom";

const Layout = () => {


return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/blogs">Blogs</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>

<Outlet />
</>
)
};

export default Layout;

[Link]
const NoPage = () => {
return <h1>404</h1>;
};

export default NoPage;

React Hooks – Introduction


• Hooks (Receive or Steal) are the new feature introduced in the React 16.8 version. It allows
you to use state and other React features without writing a class.

Dept. of CSE, JSSPN Page 6


FSD

useState
• The React useState Hook allows us to track state in a function component.
• State generally refers to data or properties that need to be tracking in an application.
• To use the useState Hook, we first need to import it into our component.
Syntax: import { useState } from "react";

• We initialize our state by calling useState in our function component.


• useState accepts an initial state and returns two values:
i. The current state.
ii. A function that updates the state.

Initialization
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("");
}

Example for update and Read state


import { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteColor() {
const [color, setColor] = useState("red");
return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
</>
)}
const root = [Link]([Link]('root'));
[Link](<FavoriteColor />);

Dept. of CSE, JSSPN Page 7


FSD

useEffect:
• The useEffect Hook allows you to perform side effects in your components.
• Some examples of side effects are: fetching data, directly updating the DOM, and timers.
• useEffect accepts two arguments. The second argument is optional.
Syntax: useEffect(<function>, <dependency>)

Example to set timer:


import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Timer() {
const [count, setCount] = useState(0);

useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});

return <h1>I have rendered {count} times!</h1>;


}
const root = [Link]([Link]('root'));
[Link](<Timer />);

Example to clear timer:


import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);

return () => clearTimeout(timer)


}, []);

Dept. of CSE, JSSPN Page 8


FSD

return <h1>I've rendered {count} times!</h1>;


}

const root = [Link]([Link]('root'));


[Link](<Timer />);

useContext
• React Context is a way to manage state globally.
• It can be used together with the useState Hook to share state between deeply nested
components more easily than with useState alone.

Create Context: You must Import createContext and initialize it:

import { useState, createContext } from "react";


import ReactDOM from "react-dom/client";
const UserContext = createContext()

Context Provider: Wrap child components in the Context Provider and supply the state value.
useContext: To use the Context in a child component, we need to access it using
the useContext Hook.
import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";
const UserContext = createContext();

function Component1() {
const [user, setUser] = useState("Jesse Hall");
return (
<[Link] value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 />
</[Link]>
);
}
function Component2() {
return (
<>

Dept. of CSE, JSSPN Page 9


FSD

<h1>Component 2</h1>
<Component3 />
</>
);
}

const root = [Link]([Link]('root'));


[Link](<Component1 />);

useReducer
• The useReducer Hook is similar to the useState Hook.
• It allows for custom state logic.
• If you find yourself keeping track of multiple pieces of state.
Syntax: useReducer(<reducer>, <initialState>)
• The reducer function contains your custom state logic and the initialStatecan be a simple
value but generally will contain an object.
Example:
import React, { useReducer } from "react";

// Defining the initial state and the reducer


const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "add":
return state + 1;
case "subtract":
return state - 1;
case "reset":
return 0;
default:
throw new Error("Unexpected action");
}
};

const App = () => {


// Initialising useReducer hook
const [count, dispatch] = useReducer(reducer, initialState);

Dept. of CSE, JSSPN Page 10


FSD

return (
<div>
<h2>{count}</h2>
<button onClick={() => dispatch("add")}>
add
</button>
<button onClick={() => dispatch("subtract")}>
subtract
</button>
<button onClick={() => dispatch("reset")}>
reset
</button>
</div>
);
};

export default App;

Custom Hooks
• Hooks are reusable functions.
• When you have component logic that needs to be used by multiple components, we can
extract that logic to a custom Hook.
• Custom Hooks start with "use". Example: useFetch.

Object oriented concepts and design principles

Dept. of CSE, JSSPN Page 11


FSD

Data Structure:
A data structure is a specialized format for organizing, processing, retrieving and
storing data.

Database Concepts:
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by a database management
system (DBMS).
• Database Schema: It is a design of the database.
• Data Constraints: Constraints are used to put some restriction on the table.
• Data dictionary or Metadata: Metadata is known as the data about the data
• Database instance: used to define the complete database environment and its
components.
• Query: query is used to access data from the database.
• Data manipulation: manipulation can be done using three main operations that is
Insertion, Deletion, and updation.
• Data Engine: used to create and manage various database queries.

Java and servlet basics


• Java is a popular programming language.
• Java is used to develop mobile apps, web apps, desktop apps, games and much more.

Dept. of CSE, JSSPN Page 12


FSD

Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the webserver, process the request, produce
the response, then send a response back to the webserver.

Java Collections (List, Set, Map)


A List in java extends the collection interface and represent an sequenced or ordered group of
elements. It can contain duplicate elements.
It also defines some additional methods which it inherits from Collection interface.

import [Link].*;
public class Main {
public static void main(String args[]){
List<String> mySubjects = new ArrayList<>();
[Link]("Java");
[Link]("Spring");
[Link]("My Subjects:");
for(String subject : mySubjects){
[Link](subject);
}
}
}

Set
• A set represents a group or collection of items. Set has a special property that is unique
items, it can not contain a duplicate item or element. It extends the collection interface.
import [Link].*;
public class Main {
public static void main(String args[]){
Set<String> mySubjects = new HashSet<>();
[Link]("Java");
[Link]("Spring");
[Link]("My Subjects:");
for(String subject : mySubjects){
[Link](subject);
}
}
}

Dept. of CSE, JSSPN Page 13


FSD

Map
• It represents a group of special elements or objects. Every map element or object contains
key and value pair. A map can’t contain duplicate keys and one key can refer to at most
one value.

import [Link].*;
public class Main {

public static void main(String args[]){


Map<Integer,String> mysubjects = new HashMap<Integer,String>();

[Link](1,"Java");
[Link](2,"Spring");
for([Link] subject : [Link]())
[Link]([Link]()+" - "+[Link]());

}
}

Thread:
• Threads allows a program to operate more efficiently by doing multiple things at the
same time.
• Threads can be used to perform complicated tasks in the background without interrupting
the main program.

Install java (latest stable version) and addenvironment variable

1. Install and Setup java environment


Step 1: Download JDK
@ [Link]
Step 2: Install JDK
Step 3: Include JDK's "bin" Directory in the PATH
Step 4: Verify the JDK Installation

Dept. of CSE, JSSPN Page 14


FSD

Install java editor (Eclipse for Enterprise Java) and configure workspace
Step 1) Installing Eclipse
Open your browser and type [Link]

Step 2) Click on “Download” button.

Step 3) Click on “Download 64 bit” button

Step 4) Install Eclipse.


Click on Run button

Dept. of CSE, JSSPN Page 15


FSD

Step 5) Click on “Eclipse IDE for Java Developers”

Step 6) Click on “INSTALL” button

Step 7) Click on “LAUNCH” button.

Dept. of CSE, JSSPN Page 16


FSD

Step 8) Click on “Launch” button.

Step 9) Click on “Create a new Java project” link.

Step 10) Create a new Java Project


1. Write project name.
2. Click on “Finish button”.
Step 11) Create Java Package.
1. Goto “src”.
2. Click on “New”.
3. Click on “Package”.
Step 12) Writing package name.
1. Write name of the package
2. Click on Finish button.
Step 13) Creating Java Class
1. Click on package you have created.
2. Click on “New”.
3. Click on “Class”.
Step 14) Defining Java Class.
1. Write class name
2. Click on “public static void main (String[] args)” checkbox.
3. Click on “Finish” button.
Step 15) Click on “Run” button.

Dept. of CSE, JSSPN Page 17


FSD

Redux
Redux is used by ReactJS for building the user interface and to manage the application
state. The official React binding for Redux is React Redux which is used to read data from
a Redux Store, and dispatch Actions to the Store to update data. It also helps the apps to
scale.
State Management with Redux
State management is essentially a way to facilitate communication and sharing of data
across components. It creates a tangible data structure to represent the state of your app
that you can read from and write to.

Build single page application – like shopping Cart

Dept. of CSE, JSSPN Page 18


FSD

Week 7
Basics of Apache Maven
• Apache Maven is a software project management and comprehension tool.
• Based on the concept of a project object model (POM), Maven can manage a project's
build, reporting and documentation from a central piece of information.
• Using maven we can build and manage any Java based project.

Project management tool


• Apache Maven is a build tool.
• This is a software project management tool that gives a new concept of the project object
model (POM).
• Maven allows the developer to automate the handling of the creation of the original
folder format, performing the assortment and testing and the packaging and deployment
of the final output.
• It cuts down the considerable number of steps in the base process, and it makes it jus one-
step process to do a build.

Understanding [Link]
• POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an
XML file that resides in the base directory of the project as [Link].
• The POM contains information about the project and various configuration detail used by
Maven to build the project(s).
• POM also contains the goals and plugins. While executing a task or goal, Maven looks
for the POM in the current directory. It reads the POM, gets the needed configuration
information, and then executes the goal.
• Some of the configuration that can be specified in the POM are following
• project dependencies
• plugins
• goals
• build profiles
• project version

Dept. of CSE, JSSPN Page 1


FSD

• developers
• mailing list

Before creating a POM, we should first decide the project group (groupId), its name (artifactId)
and its version as these attributes help in uniquely identifying the project in repository.
POM Example
<project xmlns = "[Link]
xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
</project>

It should be noted that there should be a single POM file for each project.
• All POM files require the project element and three mandatory fields: groupId, artifactId,
version.
• Projects notation in repository is groupId:artifactId:version.
• Minimal requirements for a POM −

[Link]. Node & Description

1 Project root
This is project root tag. You need to specify the basic schema settings such as apache
schema and [Link] specification.

Dept. of CSE, JSSPN Page 2


FSD

2 Model version
Model version should be 4.0.0.

3 groupId
This is an Id of project's group. This is generally unique amongst an organization or a
project. For example, a banking group [Link] has all bank related projects.

4 artifactId
This is an Id of the project. This is generally name of the project. For example,
consumer-banking. Along with the groupId, the artifactId defines the artifact's location
within the repository.

5 version
This is the version of the project. Along with the groupId, It is used within an artifact's
repository to separate versions from each other. For example −
[Link]:consumer-banking:1.0
[Link]:consumer-banking:1.1.

Dept. of CSE, JSSPN Page 3


FSD

What is Spring?
• The Spring Framework (Spring) is an open-source application framework that provides
infrastructure support for developing Java applications.
• One of the most popular Java Enterprise Edition (Java EE) frameworks, Spring helps
developers create high performing applications using plain old Java objects (POJOs).
• Spring is a lightweight framework. It can be thought of as a framework of
frameworks because it provides support to various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc.

Why Spring?
1. Easy, Simple, and Lightweight
• Spring is easy to learn and implement which is composed of modules where we can
write spring applications normally with interfaces and abstract classes just like java
applications.
• Spring helps in coupling and wiring the components which make working with Spring
easier and simpler.
• It is lightweight as we can inject dependencies as per our need

2. Builds Secure Web Applications


• Spring provides security if Spring Security is on the classpath and we can customize the
security settings further for basic authentication and prevent vulnerabilities in our
project.

3. MVC Pattern
• Model View Controller which helps in separating implementation and business logic
• The view is where requests are received first which are taken by the controller to the
corresponding model for results which are then taken to view to show at the front side
of the application.

Dept. of CSE, JSSPN Page 4


FSD

4. Easy Communication with Databases


• With the support of DAO(Data Access Object) in Spring, data access related
technologies such as Hibernate, JDBC, and JPA make it easier to communicate with
databases.

5. Modular Design
• It is divided into components such as core container, data access / integration, web, and
test which work together but independently.
• Implementation can also be divided in Spring according to the MVC pattern

6. Can be Integrated with Other Frameworks


• It can be used with other frameworks such as Struts, and Hibernate.

7. Dependency Injection
• Dependency Injection helps in decreasing coupling and dependency between classes
in Spring projects so that the program becomes maintainable and reusable.
• Modules of one project can be used effectively in another project like a login page, and
registration page which not only saves them time but also promotes code reusability

8. Follows Aspect-Oriented Programming


• Aspect-Oriented Programming allows us to think differently about the structure of the
program by enabling the modularization of concerns.
• It helps in breaking down the logic into parts known as concerns and the concerns help
in dividing the business logic of an application and in increasing the modularity.

9. Testing becomes easy


• classes can be tested independently without having to depend on one another

10. Handle external resources easily


• Resource and ResourceLoader are the interfaces present in Spring to handle external
resources

Dept. of CSE, JSSPN Page 5


FSD

How Spring works


A web application (layered architecture) commonly includes three layers:
1. Presentation/view layer (UI) - This is the outermost layer which handles the presentation of
content and interaction with the user.
2. Business logic layer - The central layer that deals with the logic of a program.
3. Data access layer - The deep layer that deals with data retrieval from sources.

Important terms
Autowiring - The process by which Spring identifies dependencies and matches and populates
them.
Bean - A Spring bean is an object that is instantiated, created, and managed by the IoC container.
Beans are the backbone of an application.
Dependency injection - A programming design pattern that makes code loosely coupled,
meaning that any change in the application of one, will not affect the other.
Inversion of control (IoC) - Taking control away from the class and giving it to the Spring
Framework.
Inversion of control container - This is the core of the Spring Framework where objects are
created, wired together, configured, and managed throughout their life cycle.

Dept. of CSE, JSSPN Page 6


FSD

Spring Framework Architecture

Core Container
The Core Container consists of the Core, Beans, Context, and Expression Language modules
• The Core module provides the fundamental parts of the framework, including the IoC
and Dependency Injection features.
• The Bean module provides BeanFactory, which is a sophisticated implementation of the
factory pattern.
• The Context module builds on the solid base provided by the Core and Beans modules
and it is a medium to access any objects defined and configured. The ApplicationContext
interface is the focal point of the Context module.
• The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.

Dept. of CSE, JSSPN Page 7


FSD

Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction
modules
• The JDBC module provides a JDBC-abstraction layer that removes the need for tedious
JDBC related coding.
• The ORM module provides integration layers for popular object-relational mapping
APIs, including JPA, JDO, Hibernate, and iBatis.
• The OXM module provides an abstraction layer that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
• The Java Messaging Service JMS module contains features for producing and consuming
messages.
• The Transaction module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your POJOs.
Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules
• The Web module provides basic web-oriented integration features such as multipart file-
upload functionality and the initialization of the IoC container using servlet listeners and a
web-oriented application context.
• The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
• The Web-Socket module provides support for WebSocket-based, two-way
communication between the client and the server in web applications.
• The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.

Miscellaneous
There are few other important modules like AOP, Aspects, Instrumentation, Web and Test
modules
• The AOP module provides an aspect-oriented programming implementation allowing
you to define method-interceptors and pointcuts to cleanly decouple code that implements
functionality that should be separated.

Dept. of CSE, JSSPN Page 8


FSD

• The Aspects module provides integration with AspectJ, which is again a powerful and
mature AOP framework.
• The Instrumentation module provides class instrumentation support and class loader
implementations to be used in certain application servers.
• The Messaging module provides support for STOMP as the WebSocket sub-protocol to
use in applications. It also supports an annotation programming model for routing and
processing STOMP messages from WebSocket clients.
• The Test module supports the testing of Spring components with JUnit or TestNG
frameworks.

Key components of Spring Framework


• Spring Core
• Spring AOP
• Spring Web MVC
• Spring DAO
• Spring ORM
• Spring context
• Spring Web flow

SpringBoot
• Spring Boot is an open source Java-based framework used to create a micro Service.
• Spring Boot provides a good platform for Java developers to develop a stand-alone and
production-grade spring application that you can just run. You can get started with
minimum configurations without the need for an entire Spring configuration setup
Advantages
Spring Boot offers the following advantages to its developers −
• Easy to understand and develop spring applications
• Increases productivity
• Reduces the development time

Why SpringBoot?
• It provides a flexible way to configure Java Beans, XML configurations, and Database
Transactions.

Dept. of CSE, JSSPN Page 9


FSD

• It provides a powerful batch processing and manages REST endpoints.


• In Spring Boot, everything is auto configured; no manual configurations are needed.
• It offers annotation-based spring application
• Eases dependency management
• It includes Embedded Servlet Container

Compare Spring and SpringBoot

Spring Spring Boot

Spring Framework is a widely used Spring Boot Framework is widely used to


Java EE framework for building develop REST APIs.
applications.

It aims to simplify Java EE It aims to shorten the code length and provide the
development that makes developers easiest way to develop Web Applications.
more productive.

The primary feature of the Spring The primary feature of Spring Boot
Framework is dependency injection. is Autoconfiguration. It automatically configures the
classes based on the requirement.

It helps to make things simpler by It helps to create a stand-alone application with less
allowing us to develop loosely configuration.
coupled applications.

The developer writes a lot of code It reduces boilerplate code.


(boilerplate code) to do the minimal
task.

To test the Spring project, we need to Spring Boot offers embedded server such
set up the sever explicitly. as Jetty and Tomcat, etc.

Dept. of CSE, JSSPN Page 10


FSD

It does not provide support for an in- It offers several plugins for working with an
memory database. embedded and in-memory database such as H2.

Developers manually define Spring Boot comes with the concept of starter in
dependencies for the Spring project [Link] file that internally takes care of downloading
in [Link]. the dependencies JARs based on Spring Boot
Requirement.

understanding the spring initializer interface


Spring Initializer is a web-based tool. With the help of Spring Initializer, we can easily generate
the structure of the Spring Boot Project. It offers extensible API for creating JVM-based projects.

Annotations
Annotations are used to provide supplemental information about a program.
• Annotations start with ‘@’.
• Annotations help to associate metadata (information) to the program elements i.e. instance
variables, constructors, methods, classes, etc.
• Annotations basically are used to provide additional information, so could be an alternative
to XML and Java marker interfaces.

Spring Annotations List


@Service
Annotate all your service classes with @Service. All your business logic should be in Service
classes.
@Service
public class CompanyServiceImpl implements CompanyService {
...
}
@Repository
Annotate all your DAO classes with @Repository. All your database access logic should be in
DAO classes.

Dept. of CSE, JSSPN Page 11


FSD

@Repository
public class CompanyDAOImpl implements CompanyDAO {
...
}

@Component
Annotate your other components (for example REST resource classes) with @Component
@Component
public class ContactResource {
...
}

@Component is a generic stereotype for any Spring-managed component. @Repository,


@Service, and @Controller are specializations of @Component for more specific use cases, for
example, in the persistence, service, and presentation layers, respectively.

@Autowired
Let Spring auto-wire other beans into your classes using @Autowired annotation.

@Service
public class CompanyServiceImpl implements CompanyService {

@Autowired
private CompanyDAO companyDAO;

...
}

Dept. of CSE, JSSPN Page 12


FSD

@Transactional
Configure your transactions with @Transactional spring annotation.

@Service
public class CompanyServiceImpl implements CompanyService {

@Autowired
private CompanyDAO companyDAO;

@Transactional
public Company findByName(String name) {

Company company = [Link](name);


return company;
}
...
}

@Scope
To change default behavior, use @Scope spring annotation.
@Component
@Scope("request")
public class ContactResource {
...
}

What is inversion of control?


• Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates
the objects, configures and assembles their dependencies, manages their entire life cycle.
• Inversion of Control (IoC) is a design principle that allows classes to be loosely coupled
and, therefore, easier to test and maintain.
• IoC refers to transferring the control of objects and their dependencies from the main
program to a container or framework.

Dept. of CSE, JSSPN Page 13


FSD

What is dependency injection?


• Dependency Injection is the main functionality provided by Spring IOC(Inversion of
Control).
• The Spring-Core module is responsible for injecting dependencies through either
Constructor or Setter methods.

Types of Spring Dependency Injection.


1. Constructor Injection: In the constructor injection, the injector supplies the service
(dependency) through the client class constructor.
2. Property Injection: In the property injection (aka the Setter Injection), the injector
supplies the dependency through a public property of the client class.
3. Method Injection: In this type of injection, the client class implements an interface
which declares the method(s) to supply the dependency and the injector uses this
interface to supply the dependency to the client class.

Practice:

Spring IoC container


The IoC container is responsible to instantiate, configure and assemble the objects. The IoC
container gets informations from the XML file and works accordingly. The main tasks performed
by IoC container are:
o to instantiate the application class
o to configure the object
o to assemble the dependencies between the objects
There are two types of IoC containers. They are:
1. BeanFactory
2. ApplicationContext

Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface.
Resource resource=new ClassPathResource("[Link]");

Dept. of CSE, JSSPN Page 14


FSD

BeanFactory factory=new XmlBeanFactory(resource);

Using ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext
interface.
ApplicationContext context =
new ClassPathXmlApplicationContext("[Link]");

ComponentScanning
• we use the @ComponentScan annotation along with the @Configuration annotation to
specify the packages that we want to be scanned.
• @ComponentScan without arguments tells Spring to scan the current package and all of
its sub-packages.

@Configuration @ComponentScan
public class SpringComponentScanApp {
private static ApplicationContext applicationContext;
@Bean
public ExampleBean exampleBean() {
return new ExampleBean();
}
public static void main(String[] args) {
applicationContext = new
AnnotationConfigApplicationContext([Link]);
for (String beanName : [Link]()) {
[Link](beanName);
}
}
}

Dept. of CSE, JSSPN Page 15


FSD

package [Link];
// ...
@Component
public class Cat {}

package [Link];
// ...
@Component
public class Dog {}

DI in spring Boot
Dependency Injection is the ability of an object to supply dependencies of another object.
It mainly has three classes involved:
• Client Class: This is the dependent class and is dependent on the Service class.
• Service Class: This class provides a service to the client class.
• Injector Class: This class is responsible for injecting the service class object into the client
class

There are mainly three types of Dependency Injection:


• Constructor Injection: In this type of injection, the injector supplies dependency through
the client class constructor.
• Setter Injection / Property Injection: In this type of injection, the injector method injects
the dependency to the setter method exposed by the client.
• Interface Injection: In this type of injection, the injector uses Interface to provide
dependency to the client class. The clients must implement an interface that will expose a
setter method which accepts the dependency.

Autowiring

Dept. of CSE, JSSPN Page 16


FSD

Autowiring feature of spring framework enables you to inject the object dependency implicitly.
It internally uses setter or constructor injection.

Qualifier
@Qualifier is an annotation used to specify which Spring managed bean should be injected
via @Autowired.

Bean
• Any object in the Spring framework that we initialize through Spring container is called
Spring Bean.
• Any normal Java POJO class can be a Spring Bean if it's configured to be initialized via
container by providing configuration metadata information.
• In Spring, the objects that form the backbone of your application and that are managed by
the Spring IoC container are called beans.
• A bean is an object that is instantiated, assembled, and managed by a Spring IoC
container.

Spring Bean Scopes

[Link]. Scope & Description

1 singleton
This scopes the bean definition to a single instance per Spring IoC container (default).

2 prototype
This scopes a single bean definition to have any number of object instances.

3 request
This scopes a bean definition to an HTTP request. Only valid in the context of a web-
aware Spring ApplicationContext.

Dept. of CSE, JSSPN Page 17


FSD

4 session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-
aware Spring ApplicationContext.

5 global-session
This scopes a bean definition to a global HTTP session. Only valid in the context of a
web-aware Spring ApplicationContext.

Converting monolithic application to microservices architecture

Step 1: Split the code.


Step 2: Split the database.
Step 3: Define a standalone Delivery Service.
Step 4: Use the standalone Delivery Service.
Step 5: Remove the delivery management functionality from the FTGO monolith.

Dept. of CSE, JSSPN Page 18


FSD

Step 1: Split the code

The first step is to split the code and convert delivery management into a separate, loosely
coupled module within the monolith.
Step 2: Split the database

Dept. of CSE, JSSPN Page 19


FSD

The second step is split the database and define a separate database schema for the ftgo-delivery-
service module.

Step 3: Define a standalone Delivery Service

The third step of the refactoring process is to define a standalone Delivery Service and deploy it.
The service does not, however, handle production traffic. Instead, it can, for example, be tested
in production.

Step 4: Use the standalone Delivery Service

The fourth step of the refactoring process is to use the standalone Delivery Service.

Dept. of CSE, JSSPN Page 20


FSD

Step 5: Remove the delivery management functionality from the FTGO monolith

The fifth step of the refactoring process is to remove the now obsolete delivery management
logic from the monolith.

Dept. of CSE, JSSPN Page 21


FSD

Week 8
What is an Application Programming Interface (API)?
Application Programming Interface (API) is a software interface that allows two
applications or software’s to interact, communicate and exchange data with each other
without any user intervention.
API is a collection of software functions and procedures.

How API works?


• An API is a set of defined rules that explain how computers or applications communicate
with one another.
• APIs sit between an application and the web server, acting as an intermediary layer that
processes data transfer between systems.
• Here’s how an API works:
1. A client application initiates an API call to retrieve information—also known as
a request. This request is processed from an application to the web server via the API’s
Uniform Resource Identifier (URI) and includes a request verb, headers, and
sometimes, a request body.
2. After receiving a valid request, the API makes a call to the external program or web
server.
3. The server sends a response to the API with the requested information.
4. The API transfers the data to the initial requesting application.

Why we need APIs?


• API helps two different software’s to communicate and exchange data with each other.
• It helps you to embed content from any site or application more efficiently.
• APIs can access app components. The delivery of services and information is more
flexible.
• Content generated can be published automatically.
• It allows the user or a company to customize the content and services which they use the
most.
• Software needs to change over time, and APIs help to anticipate changes.

Dept. of CSE, JSSPN Page 1


FSD

API types (Open APIs, Partner APIs, Internal APIs, Composite APIs)
There are mainly four main types of APIs:
• Open APIs: These types of APIs are publicly available to use like OAuth APIs from
Google. It has also not given any restriction to use them. So, they are also known as
Public APIs.
• Partner APIs: Specific rights or licenses to access this type of API because they are not
available to the public.
• Internal APIs: Internal or private. These APIs are developed by companies to use in
their internal systems. It helps you to enhance the productivity of your teams.
• Composite APIs: This type of API combines different data and service APIs.

Types of API Protocols (SOAP, REST)


SOAP (Simple Objects Access Protocol)
• It is the oldest API protocol in use, emerging in 1998.
• SOAP uses XML files to transfer data between web services.
• These XML files are sent over HTTP/HTTPS transmissions as is common on the internet.
• SOAP also provides flexibility and enables data transmission over other protocols as well
such as Transmission Control Protocol(TCP), Simple Mail Transport Protocol(SMTP),
User Data Protocol (UDP), etc.
Messages in SOAP are encoded in XML specifically and have a proper defined format:
1. Envelope : Literally envelopes the entire message/data in tags.
2. Header : Defines all extra information that might be needed to process this data. This is
an optional element.
3. Body : This is where we actually write the request for data required/ where all the
requested data is added.
4. Fault : Defines all the errors that may arise in the data during/due to transmission and
measures to handle them.

Dept. of CSE, JSSPN Page 2


FSD

REST(Representational State Transfer)


• REST protocols overcome SOAP's dependency on XML by supporting data transmission
in multiple formats such as JSON (most prominent), HTML, Python, plain text as well as
media files
• REST APIs follow a client-server architecture and must be stateless.
• Stateless communication implies that no client data is stored between GET requests.
• These GET requests must be distinct and [Link] assigns every operation a
unique URL, so when the server receives a request, it knows which instructions to
execute to fulfil the request.
• REST also supports caching. So, the browser can store the results obtained from the
request locally and retrieve it periodically as needed, thereby increasing speed and
efficiency.
A typical REST request has the following components:
1. Endpoint : The destination URL from which data is being requested.
2. Method : We use predefined methods such as GET, POST, PUT or DELETE to fetch the
data. These methods vary from one other. Ex. in when using GET, the data is appended to
the end of the URL string, whereas in POST, the data is sent along with the HTTP
request.
3. Headers : They define the request's details and dictate the proper format in which the
response must be received.
4. body (data) : The actual data sent by the service.

Common API examples:


1. Twitter Bots.
2. Log-In Using XYZ.
3. Weather Snippers.
4. Pay with PayPal.
5. Google Maps.
6. Travel Booking.
7. E-Commerce.

Dept. of CSE, JSSPN Page 3


FSD

What is API endpoint?


• An endpoint is one end of a communication channel. When an API interacts with
another system, the touchpoints of this communication are considered endpoints. For
APIs, an endpoint can include a URL of a server or service.
• Each endpoint is the location from which APIs can access the resources they need to
carry out their function.

Why are API endpoints important?


• Endpoints help to depict the exact location of the resources to be accessed
by API and also play a vital role in ensuring that the software which is
interacting with the API is functioning correctly.
• The performance and productivity of APIs depend on its ability to interact
and communicate with endpoints effectively.
API endpoint examples
• Twitter API Endpoint
• Spotify API Endpoint
• YouTube API Endpoint
HTTP Concepts
o HTTP stands for Hypertext Transfer Protocol.
o Hypertext Transfer Protocol is a set of rule which is used for transferring the files like,
audio, video, image, text and other multimedia files on the WWW.
o HTTP is an application-level protocol. The communication usually takes place through
TCP/IP sockets, but any reliable transport can also be used.
o This latest version is already in use on the web with the help of UDP (User Datagram
Protocol) instead of TCP (Transmission Control Protocol) for the underlying transport
protocol.
o HTTP is used to make communication between a variety of hosts and clients. It supports
a mixture of network configuration.
o HTTP is a protocol that is used to transfer the hypertext from the client end to the server
end, but HTTP does not have any security.
o Whenever a user opens their Web Browser, that means the user indirectly uses HTTP

Dept. of CSE, JSSPN Page 4


FSD

HTTP working
• As a request-response protocol, HTTP gives users a way to interact with web resources such
as HTML files by transmitting hypertext messages between clients and servers. HTTP
clients generally use Transmission Control Protocol (TCP) connections to communicate
with servers.
HTTP Method (GET, POST, PUT, DELETE)
1. GET requests a specific resource in its entirety
2. POST adds content, messages, or data to a new page under an existing web resource
3. PUT directly modifies an existing web resource or creates a new URI if need be
4. DELETE gets rid of a specified resource

Understanding of JSON structure for API request and response data

Limitations of JDBC API


• Since a PreparedStatement object represents only one SQL statement at a time, we can
execute only one statement by one prepared statement object.
• To prevent injection attacks it does not allow more than one value to a place holder.

Object relational Mapping – features and benefits


• ORM stands for object-relational mapping, where objects are used to connect the
programming language on to the database systems, with the facility to work SQL and
object-oriented programming concepts.

Features:
• Idiomatic persistence : It enables you to write the persistence classes using object
oriented classes.
• High Performance : It has many fetching techniques and hopeful locking techniques.
• Reliable : It is highly stable and eminent. Used by many industrial programmers.

Dept. of CSE, JSSPN Page 5


FSD

Benefits:
• It speeds up development time for teams.
• Decreases the cost of development.
• Handles the logic required to interact with databases.
• Improves security. ORM tools are built to eliminate the possibility of SQL injection
attacks.
• You write less code when using ORM tools than with SQL.

JPA – Java Persistent API


• The Java Persistence API (JPA) is a specification of Java. It is used to persist data
between Java object and relational database.
• JPA acts as a bridge between object-oriented domain models and relational database
systems.
• As JPA is just a specification, it doesn't perform any operation by itself. It requires an
implementation.
• So, ORM tools like Hibernate, TopLink and iBatis implements JPA specifications for
data persistence.

Spring REST controller


Spring RestController annotation is used to create RESTful web services using Spring MVC.
Spring RestController takes care of mapping request data to the defined request handler method.

Dept. of CSE, JSSPN Page 6


FSD

Basics of REST
Evolution of API

Overview of REST
• Representational State Transfer (REST) is an architectural style that defines a set of
constraints(rules) to be used for creating web services.
• REST API is a way of accessing web services in a simple and flexible way without
having any processing.
• REST technology is generally preferred to the more robust Simple Object Access
Protocol (SOAP) technology, simple and flexible making it more suitable for internet
usage.
• It’s used to fetch or give some information from a web service. All communication
done via REST API uses only HTTP request.

Working
• A request is sent from client to server in the form of a web URL as HTTP GET or
POST or PUT or DELETE request.
• After that, a response comes back from the server in the form of a resource which can
be anything like HTML, XML, Image, or JSON.
• But now JSON is the most popular format being used in Web Services.

Dept. of CSE, JSSPN Page 7


FSD

HTTP methods
Following four HTTP methods are commonly used in REST based architecture.
• GET − Provides a read only access to a resource.
• POST − Used to create a new resource.
• DELETE − Used to remove a resource.
• PUT − Used to update a existing resource or create a new resource.

REST architectural style


• REST is a software architectural style that defines the set of rules to be used for
creating web services. Web services which follow the REST architectural style are
known as RESTful web services. It allows requesting systems to access and manipulate
web resources by using a uniform and predefined set of rules.
• Interaction in REST based systems happen through Internet’s Hypertext Transfer
Protocol (HTTP).
• A Restful system consists of a
o client who requests for the resources.
o server who has the resources.
Components
• POST—Creates a resource.
• GET—Retrieves one or more resources.
• PUT—Updates a resource.
• DELETE—Deletes a resource.

Dept. of CSE, JSSPN Page 8


FSD

REST Architectural Views


Process View: Process view illustrates the interaction relationship among components. The
interaction is in the form of data flow in a system.

Connector View: A connector view of architecture tells on the mechanics of the communication
between components.
Data View: A data view of architecture tells the application state as information flows through the
components.

Architectural Constraints of RESTful API


There are six architectural constraints.
• Uniform Interface: uniform way of interacting with a given server
• Stateless: server would not store anything related to the session. In REST, the client must
include all information for the server to fulfill the request.
• Cacheable: Every response should include whether the response is cacheable or not and
for how much duration responses can be cached at the client side. Client will return the
data from its cache for any subsequent request and there would be no need to send the
request again to the server.
• Client-Server: REST application should have a client-server architecture. A Client is
someone who is requesting resources and server is someone who holds the resources.
• Layered System: A REST API can consist of multiple layers, eg., business logic,
presentation, data access
• Code on Demand: It is an optional feature. According to this, servers can also provide
executable code to the client.

Properties of REST API


1. Performance: REST can support the Performance goal by using caches to keep available data
close to where it is being processed.
2 Scalability: Scalability means to consistently provide service regardless of the increase or
decrease of web users.
3. Simplicity: By separating the functionality within components in a system, we can induce the
simplicity of the architectural styles.

Dept. of CSE, JSSPN Page 9


FSD

4. Modifiability: Modifiability represents the ease at which changes can be incorporated into the
architecture.
5. Visibility: Visibility refers to the ability of a component to monitor or mediate the interaction
between two components.
6. Portability: Portability represents the each with which a system can be moved from one
deployed location to other. portability of components by moving program code with the data;
7. Reliability: An architecture style can improve reliability by avoiding single points of failure,
using failover mechanisms, and be relying on monitoring features that can dynamically
anticipate and respond to failure conditions.

REST API Design Principles


• REST APIs are designed around resources, which are any kind of object, data, or service that
can be accessed by the client.
• A resource has an identifier, which is a URI that uniquely identifies that resource. For
example, the URI for a particular customer order might be:
[Link]
• Clients interact with a service by exchanging representations of resources. Many web APIs
use JSON as the exchange format. For example, a GET request to the URI listed above might
return this response body:
{"orderId":1,"orderValue":99.90,"productId":1,"quantity":1}
• REST APIs use a uniform interface, which helps to decouple the client and service
implementations. For REST APIs built on HTTP, the uniform interface includes using
standard HTTP verbs to perform operations on resources. The most common operations are
GET, POST, PUT, PATCH, and DELETE.
• REST APIs use a stateless request model. HTTP requests should be independent and may
occur in any order
• REST APIs are driven by hypermedia links that are contained in the representation.

Dept. of CSE, JSSPN Page 10


FSD

What is API?
An Application Programming Interface (API) establishes a connection between computers or
between computer programs (applications) by providing readily available codes and information
pipelines. It is a type of software interface that acts as a mediator among other pieces of software
to streamline the interaction with one other.

What is REST API?


Representational State Transfer, also known as REST, is basically a standardized Software
Architecture Style, or in simple words, a specific type of API used by the industry to establish a
connection between Client and Server. REST API is built to guide the development and design
of the World Wide Web’s architecture.
REST APIs provide a flexible, lightweight way of integrating computer applications. REST APIs
are a simple and standardized approach to communication, which means you don’t have to worry
about how to format your data, it’s all standardized and industry use.

What is Spring Boot RESTful service?


RESTful Web Services are client and server applications that communicate over the WWW.
RESTful Web Services are REST Architecture based Web Services. In REST Architecture,
everything is a resource. RESTful Web Services provides communication between software
applications running on different platforms and frameworks.

What are examples of RESTful web services?


Facebook, Twitter, and Google expose their functionality in the form of Restful web services.

How to create RESTful service

Step 1: Download the Spring Tool Suite (STS) from [Link]

and extract it.

Step 2: Launch the STS.

Dept. of CSE, JSSPN Page 11


FSD

Step 3: Click on File menu -> New -> Spring Starter Project ->

If the Spring Starter Project is not enlisted, then click on Other at the bottom of the
menu. A dialog box appears on the screen. Type Spring Starter Project in
the Wizards text box and click on the Next button.

Step 4: provide the name, group, and package of the project. We have provided:

Name: restful-web-services

Group: [Link]

Package: [Link]

Click on the Next button.

Dept. of CSE, JSSPN Page 12


FSD

Step 5: Choose the Spring Boot Version 2.1.8 and add Spring Web MVC, Spring Boot
DevTools, JPA, and H2 dependencies in the [Link].

Dept. of CSE, JSSPN Page 13


FSD

Step 6: We can see the project structure in the project explorer window.

Dept. of CSE, JSSPN Page 14


FSD

Step 7: Now open the [Link] file and Run the file as Java
Application.

Creating a Hello World Service


Step 1: Create a new class with the name HelloWorldController in the
package [Link].

Step 2: Whenever we create a web service, we need to define two things Get method
and the URI. Now create the helloWorld() method which returns the string "Hello
World." If we want to tell the spring MVC that it is going to handle the REST request, we
have to add @RestController annotation. Now it becomes a rest controller which can
handle the Rest request.

package [Link];
import [Link];
import [Link];
//Controller
@RestController
public class HelloWorldController
{
//using get method and hello-world as URI
@GetMapping(path="/hello-world")
public String helloWorld()
{
return "Hello World";
}
}
Step 3: Run the RestfulWebServiceApplication. It displays the string Hello World on the
browser.

Enhancing the Hello World Service to Return a Bean


In this section, we are going to generate a bean for the method helloWorld().

Step 1: Create a helloWorldBean() method in [Link] file. Map the


URI to "/hello-world-bean" and return HelloWorldBean.

Dept. of CSE, JSSPN Page 15


FSD

[Link]

package [Link];
import [Link];
import [Link];
//Controller
@RestController
public class HelloWorldController
{
//using get method and hello-world URI
@GetMapping(path="/hello-world")
public String helloWorld()
{
return "Hello World";
}
@GetMapping(path="/hello-world-bean")
public HelloWorldBean helloWorldBean()
{
return new HelloWorldBean("Hello World"); //constructor of HelloWorldBean
}
}

Step 2: Create a class HelloWorldBean.

Step 3: Generate Getters and Setters.

Right-click -> Source -> Generate Getters and Setters -> check the box -> Ok

Step 4: Generate toString()..

Right-click -> Source -> Generate toString().. -> Ok

package [Link];
public class HelloWorldBean
{
public String message;
//constructor of HelloWorldBean

Dept. of CSE, JSSPN Page 16


FSD

public HelloWorldBean(String message)


{
[Link]=message;
}
//generating getters and setters
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
[Link] = message;
}
@Override
//generate toString
public String toString()
{
return [Link] ("HelloWorldBean [message=%s]", message);
}
}

Step 5: Launch the HelloWorldController. The URL of the browser


changesto localhost:8080/hello-world-bean.

It returns the message "Hello World" in JSON format.

Output:

{ message: "Hello World" }

Dept. of CSE, JSSPN Page 17


FSD

Week 9

Transaction management and compliance to ACID principles


• A transaction is a single logical unit of work that accesses and possibly modifies the
contents of a database. Transactions access data using read and write operations.
• In order to maintain consistency in a database, before and after the transaction, certain
properties are followed. These are called ACID properties.

A.C.I.D. properties: Atomicity, Consistency, Isolation, and Durability


If a database operation has these ACID properties, it can be called an ACID transaction, and
data storage systems that apply these operations are called transactional systems.
ACID transactions guarantee that each read, write, or modification of a table has the
following properties:
• Atomicity - It means if any operation is performed on the data, either it should be
performed or executed completely or should not be executed at all.
• Consistency – Consistency guarantees that changes made within a transaction are
consistent with database constraints.
This includes all rules, constraints, and triggers. If the data gets into an illegal
state, the whole transaction fails.
• Isolation – Isolation is the property of a database where no data should affect the other
one and may occur concurrently.
It means if two operations are being performed on two different databases, they
may not affect the value of one another.
• Durability - ensures that the data after the successful execution of the operation becomes
permanent in the database..

Dept. of CSE, JSSPN Page 1


FSD

Securing REST APIs with Spring Security


In order to add security to our Spring Boot application, we need to add the security starter
dependency

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

This will also include the SecurityAutoConfiguration class containing the initial/default security
configuration.
By default, the Authentication gets enabled for the Application. Also, content negotiation is used
to determine if basic or formLogin should be used.

There are some predefined properties:


[Link]=root
[Link]=root

If we don't configure the password using the predefined


property [Link] and start the application, a default password is randomly
generated and printed in the console log:

Using default security password: c8be15de-4488-4490-9dc6-fab3f91435c6

File - new – Project - spring starter project


Name: spring-basic-security
Package: [Link]
Click Next - Add Dependencies: Spring Web, Spring Security, Spring Boot Dev Tools….
Finish
Name: SpringBasicSecurityApplication
package [Link];

Dept. of CSE, JSSPN Page 2


FSD

[Link]

import [Link];
import [Link];
import [Link];
@SpringBootApplication
@EnableWebSecurity
public class SpringBasicSecurityApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

Create Package
Name: [Link]
Create Class
Name: ApplicationController

package [Link];
import [Link];
import [Link];
import [Link];
@RestController
@RequestMapping("/auth")
public class ApplicationController {
@GetMapping("/getmsg")
public String greeting()
{
return "Spring Security Example";
}
}

Dept. of CSE, JSSPN Page 3


FSD

[Link] File
[Link]=niranjan
[Link]=murthy
[Link]=8090

JUnit Tutorials
Testing: Testing is the process of checking an application that it is working as expected. In other
words testing is a process of verification and validation.

Unit testing: Unit testing is the testing of an individual unit (class/method) or group of related
units

Types of unit testing:


• Manual testing:Manual testing is the process of executing a test case without any tool
support.
• Automated testing: Automated testing is the process of executing a test case with any
tool support.

JUnit: JUnit is an open-source unit testing framework for java programmers. It is only used for
unit testing. Integration testing is done by TestNG.

Unit test case:


Unit test case is part of code which executes to check that another part of the code works as
expected.

Dept. of CSE, JSSPN Page 4


FSD

Annotations for Junit testing:


1. @Test: It is used to specify the test method.
2. @BeforeClass: It is used to specify that method will be called only once, before starting all
the test cases.
3. @AfterClass: It is used to specify that method will be called only once, after finishing all the
test cases.
4. @Before: It is used to specify that method will be called before each test case.
5. @After: It is used to specify that method will be called after each test case.
6. @Ignore: It is used to ignore the test case.

Assert class:
JUnit provides the Assert class to check the certain conditions. Assert class methods compare the
output value to the expected value.
Commonly used methods of Assert class:
1. assertTrue(boolean condition): It assert that the specified boolean condition is true.
2. assertFalse(boolean condition): It assert that the specified boolean condition is false
3. assertNull(Object obj): It assert that the specified object is null.
4. assertNotNull(Object obj): It assert that the specified object is not null.
5. assertEquals(Object expected, Object actual): It assert that two objects are equal.
6. assertSame(Object expected, Object actual): It assert that two objects refer to the same
object.

Dept. of CSE, JSSPN Page 5


FSD

Writing Junit test cases for CRUD operations


Download JUnit from [Link]
Goto download & install
Find Plain-old Jar & Download the following
• [Link]
• [Link]
• Create a folder in any drive by giving relevant name, copy and paste both jar files to the
folder.
• Create a project in eclipse
• Right click on project select build path, click on configure build path
• Select java build path, Click on Libraries and click on class path in libraries, go to Add
External JAR’s, select [Link] and [Link] files, click on apply and then apply
and close.
• Goto src/test/java folder find default package and Testclass
• Write the below code

package [Link];
import static [Link];
import static [Link];
import static [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@SpringBootTest
class SpringbootFirstAppApplicationTests {
@Autowired
UserRepository userRepo;

Dept. of CSE, JSSPN Page 6


FSD

@Test
public void testCreate()
{
User u=new User();
[Link](3L);
[Link]("Kavya");
[Link]("shree");
[Link](u);
assertNotNull([Link](902L).get());
}
@Test
public void testReadAll()
{
List<User> list=[Link]();
assertThat(list).size().isGreaterThan(0);
}
@Test
public void testUpdate()
{
User u=[Link](902L).get();
[Link]("Murthy");
[Link](u);
assertNotEquals("Niranjan",[Link](902L).get().getFirstname());
}
@Test
public void testDelete()
{
[Link](852L);
assertThat([Link](852L)).isFalse();
}
}

Dept. of CSE, JSSPN Page 7


FSD

Introduction NoSQL
A database Management System provides the mechanism to store and retrieve the data. There
are different kinds of database Management Systems:
1. RDBMS (Relational Database Management Systems)
2. OLAP (Online Analytical Processing)
3. NoSQL (Not only SQL)

NoSql
• NoSQL database stands for “Not Only SQL” or “Not SQL.”
• NoSQL Database is a non-relational Data Management System that does not require a
fixed schema.
• It avoids joins, and is easy to scale. The major purpose of using a NoSQL database is
for distributed data stores with huge data storage needs.
• NoSQL is used for Big data and real-time web apps. For example, companies like
Twitter, Face book and Google collect terabytes of user data every single day.
• NoSQL can store structured, semi-structured, unstructured and polymorphic data

Dept. of CSE, JSSPN Page 8


FSD

Brief History:
• 1998- Carlo Strozzi use the term NoSQL for his lightweight, open-source relational
database
• 2000- Graph database Neo4j is launched
• 2004- Google BigTable is launched
• 2005- CouchDB is launched
• 2007- The research paper on Amazon Dynamo is released
• 2008- Facebooks open sources the Cassandra project
• 2009- The term NoSQL was reintroduced

Features of NoSQL
Non-relational
• NoSQL databases never follow the relational model
• Never provide tables with flat fixed-column records
• Work with self-contained aggregates
• Doesn’t require object-relational mapping and data normalization
• No complex features like query languages, query planners, referential integrity joins,
ACID

Schema-free
• NoSQL databases are either schema-free or have relaxed schemas
• Do not require any sort of definition of the schema of the data
• Offers heterogeneous structures of data in the same domain

Simple API
• Offers easy to use interfaces for storage and querying data provided
• APIs allow low-level data manipulation & selection methods
• Text-based protocols mostly used with HTTP REST with JSON
• Mostly used no standard based NoSQL query language
• Web-enabled databases running as internet-facing services

Dept. of CSE, JSSPN Page 9


FSD

Distributed
• Multiple NoSQL databases can be executed in a distributed fashion
• Offers auto-scaling and fail-over capabilities
• Often ACID concept can be sacrificed for scalability and throughput
• Only providing eventual consistency

Types of NoSQL Databases


1. Key-value Pair Based:
• Data is stored in key/value pairs. It is designed in such a way to handle lots of data and
heavy load.
• Key-value pair storage databases store data as a hash table where each key is unique, and
the value can be a JSON, BLOB(Binary Large Objects), string, etc.
• For example, a key-value pair may contain a key like “Website” associated with a value
like “Sanpoly”.

2. Column-oriented Graph
• They store data in tables, rows, and dynamic columns. Here each row doesn’t need to
have the same columns.
• These were created to store and process very large amounts of data distributed over many
machines.

Dept. of CSE, JSSPN Page 10


FSD

3. Graphs based
• A graph type database stores entities as well the relations amongst those entities. The
entity is stored as a node with the relationship as edges. An edge gives a relationship
between nodes. Every node and edge has a unique identifier.

4. Document-oriented
• Document-Oriented NoSQL DB stores and retrieves data as a key value pair but the value
part is stored as a document.
• The document is stored in JSON or XML formats. The value is understood by the DB
and can be queried.

Benefits
There are many advantages of working with NoSQL databases such as MongoDB and
Cassandra. The main advantages are high scalability and high availability.
1. High scalability – NoSQL databases use sharding(dividing a larger part into smaller parts)
for horizontal scaling. Partitioning of data and placing it on multiple machines in such a
way that the order of the data is preserved is sharding. Vertical scaling means adding more
resources to the existing machine whereas horizontal scaling means adding more machines
to handle the data. Vertical scaling is not that easy to implement but horizontal scaling is
easy to implement. Examples of horizontal scaling databases are MongoDB, Cassandra,

Dept. of CSE, JSSPN Page 11


FSD

etc. NoSQL can handle a huge amount of data because of scalability, as the data grows
NoSQL scale itself to handle that data in an efficient manner.
2. High availability – Auto replication feature in NoSQL databases makes it highly available
because in case of any failure data replicates itself to the previous consistent state.

Cap Theorm
The CAP theorem is a belief from theoretical computer science about distributed data
stores that claims, in the event of a network failure on a distributed database, it is possible to
provide either consistency or availability—but not both.
• Consistency:
The data should remain consistent even after the execution of an operation. This means once data
is written, any future read request should contain that data. For example, after updating the order
status, all the clients should be able to see the same data.
• Availability:
The database should always be available and responsive. It should not have any downtime.
• Partition Tolerance:
Partition Tolerance means that the system should continue to function even if the communication
among the servers is not stable. For example, the servers can be partitioned into multiple groups
which may not communicate with each other. Here, if part of the database is unavailable, other
parts are always unaffected.

BASE: Basically Available, Soft state, Eventual consistency


• Basically, available means DB is available all the time as per CAP theorem
• Soft state means even without an input; the system state may change
• Eventual consistency means that the system will become consistent over time.

Dept. of CSE, JSSPN Page 12


FSD

Mongo DB
• MongoDB is a document-oriented NoSQL database used for high volume data storage.
• Instead of using tables and rows, MongoDB makes use of collections and documents.
• Documents consist of key-value pairs which are the basic unit of data in MongoDB.
• Collections contain sets of documents and function which is the equivalent of relational
database tables.

MongoDB Features

• MongoDB provides high performance. Most of the operations in the MongoDB are
faster compared to relational databases.
• MongoDB provides auto replication feature that allows you to quickly recover data in
case of a failure.
• Horizontal scaling is possible in MongoDB because of sharing. Sharding is partitioning
of data and placing it on multiple machines in such a way that the order of the data is
preserved.
• Vertical scaling means adding more resources to the existing machine.
• Load balancing: horizontal scaling allows MongoDB to balance the load.
• High Availability: Auto Replication improves the availability of MongoDB database.
• Indexing: Index is a single field within the document. Indexes are used to quickly locate
data without having to search every document.

Dept. of CSE, JSSPN Page 13


FSD

Key Components of MongoDB Architecture


1._id:
• The _id field represents a unique value in the MongoDB document.
• The _id field is like the document’s primary key.
• If you create a new document without an _id field, MongoDB will automatically create
the field.
2. Collection: This is a grouping of MongoDB documents. A collection is the equivalent of a
table.
3. Cursor: This is a pointer to the result set of a query. Clients can iterate through a cursor to
retrieve results.
4. Database: This is a container for collections (tables).
5. Document: A record in a MongoDB collection is basically called a document. The document,
in turn, will consist of field name and values.
6. Field: A name-value pair in a document. A document has zero or more fields. Fields are
analogous to columns in relational databases.
7. JSON: This is known as JavaScript Object Notation. This is a human-readable, plain text
format for expressing structured data.

Data Modelling in MongoDB


MongoDB provides two types of data models
• Embedded data model: In this model, you can have (embed) all the related data in a
single document, it is also known as de-normalized data model
{
_id: , Emp_ID: "10025AE336"
Personal_details:
{
First_Name: "Radhika",
Date_Of_Birth: "1995-09-26"
},
Address:
{
city: "Mysore",
}
}

Dept. of CSE, JSSPN Page 14


FSD

• Normalized data model: In this model, you can refer the sub documents in the original
document, using references.
Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"
}

Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Date_Of_Birth: "1995-09-26"
}

Address:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
city: "Mysore"
}

Working with MongoDB

Mongo Compass GUI Setup


Download and Install MongoDB Community Server
• Visit [Link] and click on MongoDB Community Edition, select a version,
platform, and package to download.
• To install follow the instructions.

MongoDB Shell – mongosh


• MongoDB Shell is the quickest way to connect, configure, query, and work with your
MongoDB database. It acts as a command-line client of the MongoDB server.

Install mongosh
• Visit [Link] and click on Product menu -> Tools -> Compass, then click on
Download.

Dept. of CSE, JSSPN Page 15


FSD

• This will take you to a page where you can select a version, platform, and package to
download. Zip file will be downloaded.
• Extract the file.
• Open mongosh folder, goto bin, double click on mongosh, press enter
• Type show dbs

Mongo Compass GUI Setup


Download and Install MongoDB Community Server
• Visit [Link] and click on MongoDB Community Edition, select a version,
platform, and package to download.
• To install follow the instructions.

Create and Manage MongoDB

test>show dbs → display list of existing database

test> use jsspn → switch to jsspn database

jsspn>

Datatypes and Operators:

MongoDB's data types allow us to store data more efficiently while simultaneously performing
very efficient and robust queries.

1. String: To represent text, the string type is utilized

2. Integer: Numeric values are stored using the integer data type. Depending on the server, it
can store 32-bit or 64-bit numbers.

3. Double: Numeric numbers containing 8 bytes floating-point are stored using the double data
type.

4. Boolean: Boolean (true or false) values are stored with the boolean data type

5. Array: We can store several values in a single key of the document with an array data type.

6. Object : An embedded document is a key-value pair that is put inside another document.
Embedded documents are stored using the object data type.

Dept. of CSE, JSSPN Page 16


FSD

7. Date : The current date or time is stored in the ‘Date’ data type. The returning date
can be done in a variety of ways; either a string or a date object. There are three
strategies that can be used in this situation.

1. The Date() function returns a string.

2. Return a date object with New Date().

3. ISODate() returns a date object as well.

8. Timestamp : The term "Timestamp" refers to a set of characters used to describe the date
and time of an occurrence. The timestamp data type is commonly used to track the creation,
editing, and updating of documents. Such characters are stored in the timestamp data type. To
construct a timestamp, use the new Timestamp().

9. Null: The NULL data type is used to represent a value of zero or no value, as the name
implies.

10. Binary: This data type is used in fields to hold binary data.

"_id": "1",

"product_code": "1234-ABCD",

"product_name": "TV",

"product_price": 49999.99,.

"product_feature": ["HD", "10wt"],

"product_dimensions": {

"product _height": 55,

"product_width": 75,

},

"mfd_date": ISODate("2022-04-10T12:45:42"),

Dept. of CSE, JSSPN Page 17


FSD

"product_created": Timestamp(1531456567, 1),

"product_availability": true,

"product_picture":BinData(1, "rk56tyvbu5677ghugf456.")

Operators are special symbols or keywords that inform a compiler or an interpreter


to carry out mathematical or logical operations.
MongoDB offers the following query operator types:

• Comparison
• Logical
• Element
• Evaluation
• Geospatial
• Array
• Bitwise
• Comments

Comparison Operators
MongoDB comparison operators can be used to compare values in a document. The
following table contains the common comparison operators.

Operator Description

$eq Matches values that are equal to the given value.

$gt Matches if values are greater than the given value.

$lt Matches if values are less than the given value.

$gte Matches if values are greater or equal to the given value.

$lte Matches if values are less or equal to the given value.

Dept. of CSE, JSSPN Page 18


FSD

$in Matches any of the values in an array.

$ne Matches values that are not equal to the given value.

$nin Matches none of the values specified in an array.

Logical Operators
MongoDB logical operators can be used to filter data based on given conditions. These operators
provide a way to combine multiple conditions. Each operator equates the given condition to a
true or false value.

Operator Description

Joins two or more queries with a logical AND and returns the documents
$and that match all the conditions.

Join two or more queries with a logical OR and return the documents
$or that match either query.

The opposite of the OR operator. The logical NOR operator will join
two or more queries and return documents that do not match the given
$nor query conditions.

$not Returns the documents that do not match the given query expression.

Array Operators
MongoDB array operators are designed to query documents with arrays. Here are the
array operators provided by MongoDB.

Operator Description

Dept. of CSE, JSSPN Page 19


FSD

Matches arrays that contain all the specified values in the


$all query condition.

Matches the documents if the array size is equal to the


$size specified size in a query.

Matches documents that match specified $elemMatch


$elemMatch conditions within each array element.

Dept. of CSE, JSSPN Page 20


FSD

Week 10
Create and Drop database
MongoDB use DATABASE_NAME is used to create database. The command will create a new
database if it doesn't exist, otherwise it will return the existing database.
Syntax: use DATABASE_NAME
>use mydb
switched to db mydb

If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB

MongoDB [Link]() command is used to drop a existing database.


Syntax [Link]()
>use mydb
switched to db mydb
>[Link]()
>{ "dropped" : "mydb", "ok" : 1 }

Create and Drop Collections


[Link](name, options) is used to create collection.
Syntax: [Link](name, options)
>use test
switched to db test
>[Link]("mycollection")
{ "ok" : 1 }

>show collections

Dept of CSE, JSSPN Page 1


FSD

mycollection
[Link]

[Link]() is used to drop a collection from the database.


Syntax: db.COLLECTION_NAME.drop()
>[Link]()
true

CRUD Operation on Mongo db

Creating a Table.
[Link]("student")
{ ok: 1 }
show tables
student

insert() Method
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
Syntax: db.COLLECTION_NAME.insert(document)
[Link]({"id":1,"name":"chandru","mark":300})

[Link]([{"id":1,"name":"chandru","mark":300},
{"id":2,"name":"suman","mark":290}])

View data from Table.


[Link]({})

Update.
[Link]({"name":"chandru"},{$set:{"name":"sekar",id:5}})

Delete only one data.

Dept of CSE, JSSPN Page 2


FSD

[Link]({"name":"sekar"})

Indexing
[Link]({"name":1})
'name_1'

equal.
[Link]({name:{$eq:"chandru"}})

GreaterThan.
[Link]({mark:{$gt:300}})

LessThen.
[Link]({mark:{$lt:400}})

GreaterThen and Lessthen in Between


[Link]({mark:{$gt:290,$lt:400}})

Sort
[Link]({},{id:0}).sort({"name":1})

Count.
[Link]()
[Link]({"name":"chandru"})

Limit: limit() method limits the number of records or documents that you want.
[Link]().limit(2)

Cursor
When the [Link] () function is used to search for documents in the collection, the
result returns a pointer to the collection of documents returned which is called a cursor.
By default, the cursor will be iterated automatically when the result of the query is returned.

Dept of CSE, JSSPN Page 3


FSD

Indexing
• The index stores the value of a specific field or set of fields, ordered by the value of the
field as specified in the index.

The createIndex() Method


Syntax: createIndex()
>db.COLLECTION_NAME.createIndex({KEY:1})
• Here key is the name of the field on which you want to create index and 1 is for
ascending order.
• To create index in descending order you need to use -1.

>[Link]({"title":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,

Dept of CSE, JSSPN Page 4


FSD

"ok" : 1
}

In createIndex() method you can pass multiple fields, to create index on multiple fields.
>[Link]({"title":1,"description":-1})

The dropIndex() method


Syntax: DropIndex()
>db.COLLECTION_NAME.dropIndex({KEY:1})
Here, "key" is the name of the file on which you want to remove an existing index.

You can also specify the name of the index directly as:
dropIndex("name_of_the_index")
> [Link]({"title":1})
{
"ok" : 0,
"errmsg" : "can't find index with key: { title: 1.0 }",
"code" : 27,
"codeName" : "IndexNotFound"
}
The dropIndexes() method
This method deletes multiple (specified) indexes on a collection.
Syntax: db.COLLECTION_NAME.dropIndexes()

> [Link]({"title":1,"description":-1})

>[Link]({"title":1,"description":-1})
{ "nIndexesWas" : 2, "ok" : 1 }

Dept of CSE, JSSPN Page 5


FSD

The getIndexes() method


This method returns the description of all the indexes int the collection.
Syntax: db.COLLECTION_NAME.getIndexes()
> [Link]()
[{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "[Link]"
},
{
"v" : 2,
"key" : {
"title" : 1,
"description" : -1
},
"name" : "title_1_description_-1",
"ns" : "[Link]"
}]
Aggregation
• Aggregations operations process data records and return computed results.
• Aggregation operations group values from multiple documents together, and can perform
a variety of operations on the grouped data to return a single result.
• In SQL count(*) and with group by is an equivalent of MongoDB aggregation.

The aggregate() Method


Syntax: aggregate()
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

Dept of CSE, JSSPN Page 6


FSD

{
_id: ObjectId(7df78ad8902c)

by_user: 'tutorials point',


url: '[Link]
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
by_user: 'tutorials point',
url: '[Link]
likes: 10
},

Expression Description Example

Sums up the defined value from all [Link]([{$group : {_id :


$sum documents in the collection. "$by_user", num_tutorial : {$sum :
"$likes"}}}])

Calculates the average of all given values [Link]([{$group : {_id :


$avg from all documents in the collection. "$by_user", num_tutorial : {$avg :
"$likes"}}}])

Gets the minimum of the corresponding [Link]([{$group : {_id :


$min values from all documents in the collection. "$by_user", num_tutorial : {$min :
"$likes"}}}])

Gets the maximum of the corresponding [Link]([{$group : {_id :


$max
values from all documents in the collection. "$by_user", num_tutorial : {$max :

Dept of CSE, JSSPN Page 7


FSD

"$likes"}}}])

Inserts the value to an array in the resulting [Link]([{$group : {_id :


$push
document. "$by_user", url : {$push: "$url"}}}])

Inserts the value to an array in the resulting [Link]([{$group : {_id :


$addToSet
document but does not create duplicates. "$by_user", url : {$addToSet : "$url"}}}])

Gets the first document from the source [Link]([{$group : {_id :


documents according to the grouping. "$by_user", first_url : {$first : "$url"}}}])
$first
Typically this makes only sense together
with some previously applied “$sort”-stage.

Gets the last document from the source [Link]([{$group : {_id :


documents according to the grouping. "$by_user", last_url : {$last : "$url"}}}])
$last
Typically this makes only sense together
with some previously applied “$sort”-stage.

Perform CRUD Operations on MongoDB through REST API using Spring Boot Starter
Data MongoDB

Step 1: Create a Spring Boot project.


Step 2: Add the following dependency
• Spring Web
• MongoDB
• Lombok
• DevTools

Step 3: Create 3 packages and create some classes and interfaces inside these packages
• entity
• repository
• controller

Dept of CSE, JSSPN Page 8


FSD

Step 4: Inside the entity package create a [Link] file.


package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "Book")
public class Book {
@Id
private int id;
private String bookName;
private String authorName;
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
[Link] = bookName;
}
public String getAuthorName() {
return authorName;
}

Dept of CSE, JSSPN Page 9


FSD

public void setAuthorName(String authorName) {


[Link] = authorName;
}

Step 5: Inside the repository package


Create a simple interface and name the interface as BookRepo. This interface is going to
extend the MongoRepository

package [Link];
import [Link];
import [Link];
public interface BookRepo
extends MongoRepository<Book, Integer> {
}

Step 6: Inside the controller package. Inside the package create one class named
as BookController

package [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
@RestController
public class BookController {
@Autowired
private BookRepo repo;

Dept of CSE, JSSPN Page 10


FSD

@PostMapping("/addBook")
public String saveBook(@RequestBody Book book){
[Link](book);
return "Added Successfully";
}
@GetMapping("/findAllBooks")
public List<Book> getBooks() {
return [Link]();
}
@DeleteMapping("/delete/{id}")
public String deleteBook(@PathVariable int id){
[Link](id);
return "Deleted Successfully";
}
}
Step 7: Below is the code for the [Link] file

[Link]
[Link]=localhost
[Link]=27017
[Link]=jss

Step 8: Inside the MongoDB Compass


Go to your MongoDB Compass and create a Database named BookStore and inside the
database create a collection named Book

Testing the Endpoint in Postman


POST – [Link]
GET – [Link]
DELETE – [Link]

Dept of CSE, JSSPN Page 11


FSD

Week 11
Application Testing
What is Application Testing?
Application Testing is defined as a software testing type conducted through scripts with the
motive of finding errors in software. It deals with tests for the entire application.

It helps to enhance the quality of your applications while reducing costs, maximizing ROI, and
saving development time.

What is Manual Testing?

Manual testing is testing of the software where tests are executed manually by a QA Analyst. It
is performed to discover bugs in software under development.

What is Automation Testing?


In Automated Software Testing, testers write code/test scripts to automate test execution. Testers
use appropriate automation tools to develop the test scripts and validate the software. The goal is
to complete test execution in a less amount of time.

Manual Testing Vs. Automation Testing

Parameter Automation Testing Manual Testing

Automation Testing uses automation tools In manual testing, test cases are executed
Definition
to execute test cases. by a human tester and software.

Automated testing is significantly faster Manual testing is time-consuming and


Processing time
than a manual approach. takes up human resources.

Automated testing is a reliable method, as


Manual testing is not as accurate because
Reliability it is performed by tools and scripts. There
of the possibility of the human errors.
is no testing Fatigue.

Investment is required for testing tools as


Investment Investment is needed for human resources.
well as automation engineers

Not cost effective for low volume Not cost effective for high volume
Cost-effective
regression regression.

With automation testing, all stakeholders Manual Tests are usually recorded in an
Test Report
can login into the automation system and Excel or Word, and test results are not
Visibility
check test execution results readily/ readily available.

Dept. of CSE, JSSP Page 1


FSD

Parameter Automation Testing Manual Testing

You can Batch multiple Test Scripts for


Batch testing Manual tests cannot be batched.
nightly execution.

Programming Programming knowledge is a must in No need for programming in Manual


knowledge automation testing. Testing.

Automated Tests have zero risks of Manual Testing has a higher risk of
Deadlines
missing out a pre-decided test. missing out the pre-decided test deadline.

Automated Testing is suited for Manual Testing is suitable for


Regression Testing, Performance Testing, Exploratory, Usability and Adhoc Testing.
When to Use?
Load Testing or highly repeatable It should also be used where the AUT
functional test cases. changes frequently.

Application testing tools

There are various testing tools for Application Testing. Selection of tools depends on what type
of testing you want to perform. For different platform different tools are recommended.
Application testing tools ensure performance, usability and functionality of applications across a
variety of devices.

• Selenium
• IBM Rational Robot
• RFT (Rational Functional Tester)
• Load Runner ( HP Performance Tester)
• Apache Jmeter

FUNCTIONAL TESTING

Functional testing is a type of software testing that validates the software system against the
functional requirements/specifications. The purpose of Functional tests is to test each function of
the software application, by providing appropriate input, verifying the output against the
Functional requirements.

How to do Functional Testing :

• Understand the Functional Requirements

Dept. of CSE, JSSP Page 2


FSD

• Identify test input or test data based on requirements


• Compute the expected outcomes with selected test input values
• Execute test cases
• Compare actual and computed expected results

What is GUI Testing?


GUI Testing is a software testing type that checks the Graphical User Interface of the Software.
The purpose of Graphical User Interface (GUI) Testing is to ensure the functionalities of
software application work as per specifications by checking screens and controls like menus,
buttons, icons, etc.

What do you Check-in GUI Testing?


The following checklist will ensure detailed GUI Testing in Software Testing.

• Check all the GUI elements for size, position, width, length, and acceptance of characters
or numbers. For instance, you must be able to provide inputs to the input fields.
• Check you can execute the intended functionality of the application using the GUI
• Check Error Messages are displayed correctly
• Check for Clear demarcation of different sections on screen
• Check Font used in an application is readable
• Check the alignment of the text is proper
• Check the Color of the font and warning messages is aesthetically pleasing
• Check that the images have good clarity
• Check that the images are properly aligned
• Check the positioning of GUI elements for different screen resolution.

What is Integration Testing?


Integration Testing is defined as a type of testing where software modules are integrated
logically and tested as a group. A typical software project consists of multiple software modules,
coded by different programmers. The purpose of this level of testing is to expose defects in the
interaction between these software modules when they are integrated

Dept. of CSE, JSSP Page 3


FSD

System testing
System Testing is a level of testing that validates the complete and fully integrated software
product. The purpose of a system test is to evaluate the end-to-end system specifications.

Integrate the work of each group and carry out integration testing

Acceptance testing

Acceptance Testing is the last phase of software testing performed after System Testing and
before making the system available for actual use.

Dept. of CSE, JSSP Page 4


FSD

Acceptance tests and test plan


The acceptance test plan or system test plan is based on the requirement specifications and is
required for a formal test environment.
Acceptance evaluates the functionality and performance of the entire application and consists of
a variety of tests like.
a) Performance Tests
b) Usability Tests
c) Stress Tests
d) Documentation Tests
e) Security Tests
f) Volume Tests
g) Recovery Tests etc.

User acceptance testing

User Acceptance Testing (UAT) is a type of testing performed by the end user or the client to
verify/accept the software system before moving the software application to the production
environment. UAT is done in the final phase of testing after functional, integration and system
testing is done.
UAT is performed by –

Client
End users

Dept. of CSE, JSSP Page 5


FSD

Bug tracking – using Jira or similar tools

Bug and issue tracking tools help software teams find, record, and track bugs in their software.
It's critical that everyone on your team is able to find and record bugs, and even more important,
assign them to the right team members at the right time.

Step 1 - Capture and track bugs in your software

Step 2 - Assign and prioritize with ease

Step 3 - Track bugs from backlog to done

Dept. of CSE, JSSP Page 6


FSD

Step 4 - Stay up to date with notifications

Step 5 - Go from backlog to release with ease

Deployment process
• Software deployment includes all of the steps, processes, and activities that are required
to make a software system or update available to its intended users.

• Today, most IT organizations and software developers deploy software updates, patches
and new applications with a combination of manual and automated processes.

Different types of application or software deployment strategies are:

• Basic
• Multi-service
• Rolling
• Blue Green Deployment
• Canary
• A/B Testing

Manual deployment
Manual configuration is intended for advanced users when more control of the application server
environment is required. When the configuration utility is run with the manual deployment mode
selected, it makes necessary changes to the database, but your application server is not changed.
Deployable application files, installation scripts, and properties files are generated in
the <repository installation directory>/toDeploy/<timestamp> directory.

Automated deployment
Deployment automation is the use of automated processes to move your software between
testing and production environments. This process is both reliable and repeatable across
the software delivery lifecycle (SDLC).

Dept. of CSE, JSSP Page 7


FSD

Some of the best deployment automation tools available include:

• Jenkins
• Visual Studio
• AWS CodeDeploy

Deployment automation benefits

• Anyone can deploy


• Faster, more efficient deployment
• Increased productivity
• Fewer errors
• More frequent releases
• Immediate feedback

How to Implement Automated Deployment

Follow these steps to set up a basic deployment pipeline:

1. Set up a Continuous Integration server


• Choose an existing server, such as Jenkins, or [Link].
• Set up your first build (a link to your source code, for example, on GitHub and a
command to build the application)

• Ensure that it runs every time a change is checked into source control.

2. Set up a few test suites


• Set up a separate build for each test suit and link the builds like dominos, so that each is
triggered by the one before it. This way you see very quickly if there is some problem -
the problematic code change stops at the first test that recognizes it and does not go any
further.

3. Add a deployment step


• On your Continuous Integration server, set a build that runs your script to deploy your
application to a testing or staging environment. Ensure that it runs only when all the
tests pass.

Dept. of CSE, JSSP Page 8


FSD

Top Deployment tools and their features

1. Bamboo
Key Features:

• Language agnostic integration with many platforms


• Dedicated agents focus on specific build projects
• Full reporting of upcoming code changes and issues

2. TeamCity
Key Features:

• Start within minutes from installation


• Support for third-party tools without plugins or modifications
• Comprehensive version control system
• Customization and extension of the server

3. AWS CodeDeploy
Key Features:

• Automated and repeatable deployments


• Centralized control
• Applications still accessible during deployments

4. Octopus Deploy
Key Features:

• Dashboard showing deployment statuses


• Installation and set up completed quickly
• Automatic deployments for virtual machines on site or in cloud services

5. ElectricFlow
Key Features:

• Build and deploy microservices


• View release status and milestone dates
• Automate and track cloud-native, container, and legacy application deployments

6. PDQ Deploy

Dept. of CSE, JSSP Page 9


FSD

Key Features:

• Customize installs
• Installs to multiple computers simultaneously
• Real-time status monitoring

7. Ansible Tower
Key Features:

• Visual dashboard includes statuses, job activity, and job snapshots


• Playbooks allow multiple workflows to be chained together
• API and command line interface tools
• Role-based access control
• Job scheduling
• Integrated notifications
• Graphical inventory management

8. Chef
Key Features:

• Manage data centers and cloud environments as one infrastructure


• Migrate workloads to the cloud quickly
• Cloud agnostic — promises integration with any provider

9. Codeship
Key Features:

• Docker support
• Parallel deployments and testing
• Debugging via SSH access and command line interface

10. AppVeyor
Key Features:

• No setup or maintenance required


• Developer-friendly build configs using UI or YAML
• Fast builds on dedicated hardware with SSD drives
• Multi-branch builds
• Staff and community support
• Pay-as-you-go pricing

Dept. of CSE, JSSP Page 10


FSD

Best Deployment practices

1. Argonaut

Deploy apps and infrastructure on your cloud in minutes. Support for custom and third-party app
deployments on Kubernetes and Lambda environments.

2. Flosum
Flosum is a native DevOps solution that handles the development lifecycle including merging
components, version control, continuous deployments, static code analysis, user story
management, and regression testing. Flosum works together with Salesforce to identify changes
in a particular component.

3. Codefresh
Codefresh is an enterprise continuous delivery platform for cloud-native applications. It
automates GitOps workflows and advanced deployments such as Canary and Blue/Green.

4. Launch Darkly

LaunchDarkly is a feature management application that enables teams to deploy code at any
time, even if a feature isn’t ready to be released to all users.

5. Harness
Harness Continuous Delivery is a software delivery solution that automatically deploys, verifies,
and rolls back artifacts. You can leverage automated canary and blue-green deployments for
faster, safer, and more efficient rollouts.

6. Juju

Juju is an open source application and service modeling tool from Ubuntu that helps you deploy,
manage and scale your applications on any cloud. With Juju, different authors are able to create
service formulas, called charms, independently, and make those services coordinate their
communication and configuration through a simple protocol. Juju can also be used together with
Orchestra for physical deployments.

7. Rundeck

Dept. of CSE, JSSP Page 11


FSD

Rundeck is an open source operations management platform that helps to automate routine
operational procedures in data center or cloud environments. It enables you to run tasks on any
number of nodes from a web-based or command-line interface.

Setup deployment pipeline

In software development, a deployment pipeline is a system of automated processes designed to


quickly and accurately move new code additions and updates from version control to
production.

1. Step 1: Create a deployment environment. ...


2. Step 2: Get a copy of the sample code. ...
3. Step 3: Create your pipeline. ...
4. Step 4: Activate your pipeline to deploy your code. ...
5. Step 5: Commit a change and then update your app. ...
6. Step 6: Clean up your resources.

Refer : [Link]

Continuous deployment

Continuous deployment is a strategy for software releases wherein any code commit that passes
the automated testing phase is automatically released into the production environment, making
changes that are visible to the software's users.
Continuous deployment eliminates the human safeguards against unproven code in live software.
It should only be implemented when the development and IT teams rigorously adhere to
production-ready development practices and thorough testing, and when they apply
sophisticated, real-time monitoring in production to discover any issues with new releases.

Static code analysis

Static analysis is a method of debugging that is done by automatically examining the source code
without having to execute the program. This provides developers with an understanding of their
code base and helps ensure that it is compliant, safe, and secure.
When Is Static Code Analysis Performed?

Static code analysis is performed early in development, before software testing begins. For
organizations practicing DevOps, static code analysis takes place during the “Create” phase.

Practice – code analysis using tools

Dept. of CSE, JSSP Page 12


FSD

Containers
A container is a standard unit of software that packages up code and all its dependencies so the
application runs quickly and reliably from one computing environment to another.

Why containers?

Containers require less system resources than traditional or hardware virtual machine
environments because they don't include operating system images. Applications running in
containers can be deployed easily to multiple different operating systems and hardware
platforms.

What is a docker?
Docker is an open source platform for building, deploying, and managing containerized
applications.

How docker works?

Docker uses a client-server architecture. The Docker client talks to the Docker daemon, which
does the heavy lifting of building, running, and distributing your Docker containers. The Docker
client and daemon can run on the same system, or you can connect a Docker client to a remote
Docker daemon.

Dept. of CSE, JSSP Page 13


FSD

Components of docker

- Docker container
Docker containers are the live, running instances of Docker images. While Docker images are
read-only files, containers are life, ephemeral, executable content. Users can interact with them,
and administrators can adjust their settings and conditions using Docker commands.

- Docker client
Docker client is an application for Mac or Windows that includes Docker Engine, Docker CLI
client, Docker Compose, Kubernetes, and others. It also includes access to Docker Hub.

- Docker daemon
Docker daemon is a service that creates and manages Docker images, using the commands from
the client. Essentially Docker daemon serves as the control center of your Docker
implementation. The server on which Docker daemon runs is called the Docker host.

-Docker image
Docker images contain executable application source code as well as all the tools, libraries, and
dependencies that the application code needs to run as a container. When you run the Docker
image, it becomes one instance (or multiple instances) of the container.

- Docker registry
A Docker registry is a scalable open-source storage and distribution system for Docker images.
The registry enables you to track image versions in repositories, using tagging for identification.
This is accomplished using git, a version control tool.

Install docker on desktop and start the docker tool.

a – Download the Docker Toolbox executable


b – Run the Docker Toolbox installer for Windows.

Dept. of CSE, JSSP Page 14


FSD

Click on Next.
For the second screen, choose a location where to store your Docker files, and click on Next.

Click on Next.
For the additional tasks, you can let the default options and click on Next.

Finally, click on Install to start the Docker Toolbox installation.

After a short while, your installation should complete. Leave the checkbox checked in order to
see the shortcuts created by Docker.

Dept. of CSE, JSSP Page 15


FSD

To verify your current Docker version, run the following command

$ docker version

Docker file
Every Docker container starts with a simple text file containing instructions for how to build the
Docker container image. DockerFile automates the process of Docker image creation. It’s
essentially a list of command-line interface (CLI) instructions that Docker Engine will run in
order to assemble the image. The list of Docker commands is huge, but standardized: Docker
operations work the same regardless of contents, infrastructure, or other environment variables.

Docker image
Docker images contain executable application source code as well as all the tools, libraries, and
dependencies that the application code needs to run as a container. When you run the Docker
image, it becomes one instance (or multiple instances) of the container.

Commands to create docker file.

ADD – Defines files to copy from the Host file system onto the Container

▪ ADD ./local/[Link] /etc/service/[Link]


▪ CMD – This is the command that will run when the Container starts
▪ CMD [“nginx”, “-g”, “daemon off;”]
▪ ENTRYPOINT – Sets the default application used every time a Container is created from the
Image. If used in conjunction with CMD, you can remove the application and just define the
arguments there
▪ CMD Hello World!
▪ ENTRYPOINT echo
▪ ENV – Set/modify the environment variables within Containers created from the Image.

Dept. of CSE, JSSP Page 16


FSD

▪ ENV VERSION 1.0


▪ EXPOSE – Define which Container ports to expose
▪ EXPOSE 80
▪ FROM – Select the base image to build the new image on top of
▪ FROM ubuntu:latest
▪ LABEL maintainer – Optional field to let you identify yourself as the maintainer of this
image. This is just a label (it used to be a dedicated Docker directive).
▪ LABEL maintainer=someone@[Link]”
▪ RUN – Specify commands to make changes to your Image and subsequently the Containers
started from this Image. This includes updating packages, installing software, adding users,
creating an initial database, setting up certificates, etc. These are the commands you would run
at the command line to install and configure your application. This is one of the most important
dockerfile directives.
▪ RUN apt-get update && apt-get upgrade -y && apt-get install -y nginx && rm -rf
/var/lib/apt/lists/*
▪ USER – Define the default User all commands will be run as within any Container created
from your Image. It can be either a UID or username
▪ USER docker
▪ VOLUME – Creates a mount point within the Container linking it back to file systems
accessible by the Docker Host. New Volumes get populated with the pre-existing contents of
the specified location in the image. It is specially relevant to mention is that defining Volumes
in a Dockerfile can lead to issues. Volumes should be managed with docker-compose or
“docker run” commands. Volumes are optional. If your application does not have any state (and
most web applications work like this) then you don’t need to use volumes.
▪ VOLUME /var/log
▪ WORKDIR – Define the default working directory for the command defined in the
“ENTRYPOINT” or “CMD” instructions
▪ WORKDIR /home

Build docker image with docker file

1. Write a Dockerfile for your application.


2. Build the image with docker build command.

Dept. of CSE, JSSP Page 17


FSD

3. Host your Docker image on a registry.


4. Pull and run the image on the target machine.

Refer : [Link]

create docker container from docker image


Step 1: Create a Base Container

The Docker create command will create a new container for us from the command line:

~ docker create --name nginx_base -p 80:80 nginx:alpine

Step 2: Inspect Images

Step 3: Inspect Containers


➜ ~ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
c365af6303e4 nginx:alpine "/docker-entrypoint.…" 6 minutes ago
Created nginx

Step 4: Start the Container


➜ ~ docker start nginx_base
nginx_base

Step 5: Modify the Running Container


Let’s create a new [Link] file and copy it onto the running container. Using an editor on your
machine, create an [Link] file in the same directory that you have been running Docker
commands from.

➜ ~ docker cp [Link] nginx_base:/usr/share/nginx/html/[Link]

Step 6: Create an Image From a Container


➜ ~ docker commit nginx_base
sha256:0c17f0798823c7febc5a67d5432b48f525320d671beb2e6f04303f3da2f10432

Dept. of CSE, JSSP Page 18


FSD

Step 7: Tag the Image


➜ ~ docker tag 0c17f0798823 hello_world_nginx

Step 8: Create Images With Tags

You can also tag the image as it is created by adding another argument to the end of the command
like this:

➜ ~ docker commit nginx_base hello_world_nginx

Step 9: Delete the Original Container


➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
c365af6303e4 nginx:alpine "/docker-entrypoint.…" 33 minutes ago Up
25 minutes 0.0.0.

Step 10: Look at Running Containers


➜ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7ca08e03862d hello_world_nginx "/docker-entrypoint.…" 2 minutes ago Up 2
minutes [Link]:80->

Step 11: Consider Your Options

Option A: Set Authorship

Option B: Create Commit Messages

Option C: Commit Without Pause

Option D: Change Configuration

Refer : [Link]

Run the docker container

The basic syntax for the command is:

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Dept. of CSE, JSSP Page 19


FSD

To run a container, the only thing you need to include in the command is the image on which it is
based:

docker run [docker_image]

As an example, we used a Dockerfile to create a sample Docker image with the task to echo the
message Hello World. For us, the image has the ID e98b6ec72f51. Your image name will differ
depending on the container you want to run.

The command to run our sample container would be:

docker run e98b6ec72f51

Refer : [Link]

Dept. of CSE, JSSP Page 20


[Type the document title]

Week12
Container
Containers are lightweight, executable application components that combine application source
code with all the operating system (OS) libraries and dependencies required to run the code in
any environment.

Orchestration
Orchestration is the automated configuration, management, and coordination of computer
systems, applications, and services. Orchestration helps IT to more easily manage complex tasks
and workflows.

Container orchestration
• Container orchestration automates the provisioning, deployment, networking, scaling,
availability, and lifecycle management of containers.
• Kubernetes is the most popular container orchestration platform, and most leading public
cloud providers - including Amazon Web Services (AWS), Google Cloud Platform, IBM
Cloud and Microsoft Azure - offer managed Kubernetes services.
• Other container orchestration tools include Docker Swarm and Apache Mesos.

What is container orchestration engine?


Container orchestration is the automation of much of the operational effort required to run
containerized workloads and services. This includes a wide range of things software teams need
to manage a container's lifecycle, including provisioning, deployment, scaling (up and down),
networking, load balancing and more.

Orchestration tools
1. Kubernetes
2. Openshift
3. Nomad
[Link] Swarm
5. Docker Compose

Dept of CSE, JSSPN Page 1


[Type the document title]

6. MiniKube
7. Marathon
8. Cloudify

Kubernetes
Kubernetes — also known as “k8s” or “kube” — is a container orchestration platform for
scheduling and automating the deployment, management, and scaling of containerized
applications.

Why Kubernetes?
• Service discovery and load balancing: If traffic to a container is high, Kubernetes is
able to load balance and distribute the network traffic so that the deployment is stable.

• Storage orchestration: allows you to automatically mount a storage system of your


choice, such as local storages, public cloud providers, and more

• Automated rollouts and rollbacks: it can change the actual state to the desired state at
a controlled rate. For example, you can automate Kubernetes to create new containers for
your deployment, remove existing containers and adopt all their resources to the new
container.

• Automatic bin packing: You provide Kubernetes with a cluster of nodes that it can use
to run containerized tasks. You tell Kubernetes how much CPU and memory (RAM) each
container needs. Kubernetes can fit containers onto your nodes to make the best use of
your resources.

• Self-healing: Kubernetes restarts containers that fail, replaces containers, kills containers
that don't respond to your user-defined health check, and doesn't advertise them to clients
until they are ready to serve.

Dept of CSE, JSSPN Page 2


[Type the document title]

• Secret and configuration management: Kubernetes lets you store and manage sensitive
information, such as passwords, OAuth tokens, and SSH keys. You can deploy and
update secrets and application configuration without rebuilding your container images,
and without exposing secrets in your stack configuration.

Kubernetes configuration
- Deployment

[Link] -LO "[Link]

- Service
- Load balancer/ingress

Deployment strategies:
A Deployment strategy defines how to create, upgrade, or downgrade different versions of
Kubernetes applications.
Blue green deployment :
Canary Deployment

Disaster recovery
Disaster recovery is the process by which an organization anticipates and addresses technology-
related disasters.
Kubernetes disaster recovery can be broken down into two phases: backup and recovery.
Backup is the process of preserving data before any disaster strikes, while recovery entails
getting back up after one has occurred.

Disaster recovery and their types:


1. Data Center Disaster Recovery
2. Network Disaster Recovery
3. Virtualized Disaster Recovery
4. Disaster Recovery in the Cloud
5. Disaster Recovery as a Service (DRaaS)

Dept of CSE, JSSPN Page 3


[Type the document title]

How does it work?

Dept of CSE, JSSPN Page 4


Basics of HTML
HTML Introduction:
What is HTML?
 HTML stands for hypertext markup language.
 HTML is the standard markup language for creating web pages.
 HTML describes the structure of a web page.
 HTML consists of a series of elements.
 HTML elements tell the browser how to display the content.
 HTML elements label pieces.
A simple HTML document example:
<!DOCTYPE HTML>
<html>
<head>
<title>page title</title>
</head>
<body>
<h1>This is my first Heading</h1>
<p>My first paragraph</P>
</body>
</html>
Example explained:
 The <!DOCTYPE HTML> declaration defines that this document is an HTML5
document.
 HTML5 is a markup language used for structuring and presenting content on the
world wide web. It is the fifth & final major HTML version that is a world wide web
consortium recommend. The current satisfaction. The current specification is known
as the HTML living standard.
 The <html> element is the root element of an HTML page
 The <head> element contains meta information about the HTML page.
 The <title> element specifies a title for the HTML page (which is shown in the
browser‟s title bar or in the page‟s tab).
 The <body> element defines the document‟s body. & it is a container for all the
visible contents. Such as heading, Paragraphs, images, hyperlinks, tables, lists etc..
 The <h1> elements defines a large heading
 The <p> element defines a paragraph.
What is an HTML element?
An HTML element is a defined by a start tag, some content & an end tag.
Example 1:
<!DOCTYPE html>
<html>
<head>
<title>welcome to mysure</title>
</head>
<body>
<h1>ultismart infotech</h1>
<p>ultismart infotech llp is it solutions,product development,outsourcing...</p>
</body>
</html>
Example 2:
<!DOCTYPE HTML>
<html>
<head>
<title> USING HTML STYLE</title>
</head>
<body>
<h1>HTML STYLE</h1>
<p>I AM AN ARMY GIRL</p>
<p style="color:red";>in the bangtan girl</p>
<p style="color:blue";>in the bangtan world</p>
<p style="color:orange";>my life is fantastic</p>
<p style="color:purple";>full of lifestick</p>
<p style="font-size:50px";>self-love is for important in this world</p>
</body>
</html>
Example 3:
<!DOCTYPE HTML>
<html>
<head>
<title>html style </title>
</head>
<body>
<h1>HTML STYLE BACKGROUND COLOR</h1>
<body style="background-color:powderblue;">
</body>
</html>
Example5:
<!DOCTYPE HTML>
<html>
<head>
<title>HTML HYPER LINK</title>
</head>
<body>
<h1>HTML HYPER LINK</h1>
<a href="[Link] this link</a>
</body>
</html>
Example 6:
<!DOCTYPE HTML>
<html>
<head>
<title>HTML IMAGE</title>
</head>
<body>
<h1>html image</h1>
<img src="C:\Users\RAJA\OneDrive\Pictures\camera\images\[Link]" "width="200"
height="300">
</body>
</html>
Example 7:
<!DOCTYPE HTML>
<html>
<head>
<title>this is my first webpage</title>
</head>
<body background-color:"pink";>
<h1>welcome to mysure</h1>
<h2>welcome to mysure</h2>
<h3>welcome to mysure</h3>
<h4>welcome to mysure</h4>
<h5>welcome to mysure</h5>
<h6>welcome to mysure</h6>
<pre>
<p>welcome to imagination world<br>where they can full fill our big [Link] my
imagination world,<br>i love myself more then others<br>there is no restriction and no
rules</p>
</pre>
</body>
</html>
Text size:
The CSS text-align property defines the horizontal text alignment for an HTML element:
HTML Formatting elements:
 <br> - Bold text
 <strong> - Important text
 <i> - Italic text
 <em> - emphasized text
 <mark> - marked text
 <small> - smaller text
 <del> - deleted text
 <ins> - inserted text
 <sub> - subscript text
 <sup> - superscript text
To display black set all color parameters to 0 like this: rgb(0,0,0).
To display white, set all color parameters to 255, like this: rgb(255,255,255).
HSL VALUE:
In HTML, a color can be specified using hue, saturation. And lightness (HSL) in the form.
Hsl (hue, saturation, lightness)
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, & 240 is blue
Saturation is a percentage value 0% means a shade of grey, and 100% is the full color.
Lightness is also a percentage, 0% is black, 50% is neither, light or dark, 100% is white.
CSS Describes:
CSS can be added to HTML elements in 3 ways:
 Inline – by using the style attribute in HTML elements.
 Internal – by using the <style> element in the <head> section.
 External-by using an external CSS file.
JavaScript: JavaScript are used to make HTML web pages are more dynamic & interactive.
And also it is easy to learn, it is a front end frame work.
It is a scripting language.
HTML JavaScript:
JavaScript makes HTML pages more dynamic and interactive. JavaScript is the world‟s most
popular programming language. JavaScript is the programming language of the web.
JavaScript is easy to learn.

The HTML <Script> tag


The <Script> tag is used to define a client-side(JavaScript).
The <Script> element either contains script statements. or it points to an external Script file
through the src attribute.
Common uses for JavaScript are image manipulation. Form validation, and dynamic changes
of content.

To select an HTML element, JavaScript most often uses the [Link]()


method.
This JavaScript example writes “hello JavaScript” into an html element.
JavaScript Statements:
JavaScript statements are composed of: values, operators, expressions, keywords, and
comments.
This statement tells the browser to write “Hello World!” inside an HTML element with
id=”demo”:
A JAVASCRIPT program is a list of programming statements.
In HTML, JavaScript programs are executed by the browser.

KEY WORDS DESCRIPTION


Var - Declares a variable
Let - Declares a block variable
Const - Declares a block constant
If - Marks a block of
statement to be executed in a condition.

Switch - Marks a block of statements to be executed in different cases.


For - Marks a block of statement to be
executed in a loop
Function - Declares a function
Return - Exists a function
Try - Implements error handling to a
block of statements.
JavaScript Code Blocks:
JavaScript statements can be grouped together in code blocks, inside curly brackets{----}.

The purpose of code blocks is to define statements to be executed together.


One place you will find statements grouped together in blocks, is in executed.

JavaScript Variables:
In a programming language, variables are used to
JavaScript uses the keywords var, and const to declare variables. An equal sign is used to
assign values to variables.

JavaScript variables:
4 ways to Declare a JavaScript Variable:

 Using var
 Using let
 Using const
 Using nothing
JavaScript is a case sensitive
All JavaScript identifies are case sensitive.
The variables lastName and lastname, are two different variables:

JavaScript Comments:
Not all JavaScript statements are “executed”.
Comments are ignored, and will not be executed:
Single line comment is begins with //
Multiline Comment is between /* */
Code after double slashes // or between /* and */ is treated as a comment.

JavaScript Operators:
JavaScript uses arithmetic operator (+ _ * /) to compute values.

JavaScript Data Types:


JavaScript variables can hold numbers like 100 and text values like “kim taehyung”.
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.

JavaScript Function:
A JavaScript Function is a block of code designed to perform a particular task. A JavaScript
Function is executed when “something” invokes it (calls it).
Why functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
JavaScript if, else, and else if
Conditional statements are used to perform different actions based on different conditions.

Conditional statements:
Very often when you write code, you want to perform different actions for decisions.
JavaScript Switch Statement:
The switch statement is used to perform different actions based on different conditions.
JavaScript JSON (JavaScript object Notation):
JSON is a format for storing and transporting data.
JSON is often used when data is sent from a server to a web page.

What is JSON?
 JSON stands for JavaScript object notation
 JSON is a lightweight data interchange format.
 JSON is language independent
 JSON is “self-describing” and easy to understand.
The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is
text only. Code for reading and generating JSON data can be written in any programming
language.\

JSON example
This example is a JSON string:
„{“name”:”john”,”age”:30,”car”:null‟}
It defines an object with 3 properties:
Name, age, car.
JavaScript Objects:
A JavaScript object is a collection of named values In JavaScript, objects are king. If you
understand objects you understand JavaScript.
IN JavaScript. Almost “everything” is an object.
 Booleans can be objects (if defined with The new keyword)
 Numbers can be objects(if defined with the key word)
 Data are always objects.
 Math are always objects.
 Regular Expressions are always object.
 Arrays are always objects.
 Functions are always object.
 Objects are always objects.
Object properties:
The named values, in JavaScript object
Property value
firstName kim
lastName Namjoon
age 28
eyeColor black

Object Methods:
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property Value
firstName kim
lastName Namjoon
age 28
eyeColor black
fullName function() {return [Link] + “” + [Link];}
JavaScript objects are containers for named values, called properties and methods.
JavaScript methods:
JavaScript methods are actions that can be performed on objects. A JavaScript method is a
property containing a function definition.
Property value
firstName kim

age 24
eyeColor blue
fullName function() {return [Link]+ “ “ +[Link];}
Methods are functions stored as object properties.
JavaScript Object Constructors:
Objects of the same type are created by calling the constructor function with the new
keyword.
The way to create an “object type”, is to use an object constructor function.
JavaScript Properties:
Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.
Accessing JavaScript Properties:
The syntax for accessing the property of an object is:
[Link] //[Link]
or
objectName[“property”] //person[“age”]
or
objectName[expression] //x=”age”;person[x]

prototype properties:
JavaScript objects inherit the properties of their
The delete keyword does not delete inherited properties. But if you delete a prototype
property. It will effect all objects inherited from the prototype.
JavaScript Sets:
A JavaScript set is a collection of unique values.
Each value can only occur once in a set.
A set can hold any value of any data type.
Set Methods:
Method Description
New set() Creates a new set
Add() Adds a new element to the set
Delete() removes an element of an set
Has() returns a true if a value exists
Clear() removes all element from a set
forEach() Invokes a callback for each element
values() Returns an Iterator with all the values in a set.
Keys() same as values()
Entries() Returns an Iterator with the [value, value] pairs from a set.
JavaScript Maps:
A Maps holds key-value pairs where the keys can be any data type.
A Map remembers the original insertion order of the keys.
A Maps has a property that represents the size of the map.
Map Methods:
Method Description
New map() Creates a new Map object
Set() Sets the value for a key in a map
Get() gets the value for a key in a map
Clear() removes all the elements from a map
Delete() removes a map element specified by a key
Has() returns true if a key exists in a map
forEach() invokes a callback for each key/value pair in a map.
Entries() returns an iterator object with the [key, value] pairs in a map.
Keys () returns an iterator object with the keys in a map
Values () returns an iterator object of the values in a map.

React:
React is JavaScript front-end, library sdevelopment by fbJsx JavaScript xmu.
 React is a JavaScript library for building user interfaces.
 React is used to build single-page applications.
 React allows us to create reusable UI components.
What is React?
React sometimes referred to as a front-end JavaScript framework, is a JavaScript library
created by facebook.
 React is tool for building component.
Setting up a react environment:
 If you have npx and [Link] installed, you can create a React application by using
create-react-app.
 If you‟ve previously installed create-react-app globally, it is recommended that you
install the package to ensure npx always uses the latest version of create-react-app.
 To uninstall, run this command: npm uninstalling create>react-app.
 Run this command to create a react application named ny-react-app.
Npx create-react-app my-react-app
Installing [Link] using webpack and babel
1. Please click on “install” button download Node JS platform version 0.12.
2. Please double click on “node.v0”.
3. Choose your required location to install.
4. Choose default values and click on “install” button.
5. Open [Link] platform home in your explores.
Run
To uninstall , run this command npm uninstalling create -react-app.
Run this command to create a react application named my-react-app
Run this command to move to the my-react-app directory.
Cd my-react-app

Run this command to run the react application my-react-app.


What is DOM?
 The DOM is a w3c (world wide web connection) standard.
 The DOM define a standard for accessing document
 The w3c document object model (DOM) is a platform and language- neutral interface
that allows programs and scripts to dynamically access and update the content.
Structure and style of a document.
 The w3c standard document is separated into 3 different parts:
1. Core DOM: standard model for all document types.
2. XML DOM: standard model for XML document.
3. HTML DOM: standard model for HTML documents.
What is HTML DOM?
The HTML DOM is a standard object mode and programming interface for HTML. It defines
 The HTML elements as objects.
 The properties of all HTML elements.
 The methods to access all HTML documents.
 The elements for all HTML elements.
In other words: the HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
React directly in HTML:
The quickest way to learning react is to write react directly in your HTML file.
React Render HTML:
React goal is in many ways to render HTML is a webpage.
React render HTML to the webpage by using a function called [Link]().
you will notice a single <div> in the body of this fete. This is where our react application will
be render.
Example: display a paragraph inside an element with the id of “root”.
[Link] <p> Hello </p> [Link](„root);
The result is designed in the <div id=”root”> element.
React getting started
React directly in HTML
<html>
<body>
<h2>example</h2>
<p>Hello</p>
</body>
</html>
Example:
<html>
<head>
<title>example</title>
</head>
<div id=”Mydiv”> </div>
<script type =”text/label”> //it is used in [Link]
function Hello(){
return<h1>hello word</h1>;
}
[Link]</hello>,
[Link]<‟mydiv‟>
</script>
</body>
</html>
Example:
Import React from „react‟;
Import ReactDOM from „[Link]/client‟;
[Link]<p>hello</p>,
[Link](„root‟);
Example1:
Import React from „react‟;
Import ReactDOM from „react-dom/client‟;
Const myelement =(
<table>
<tr>
<th>name<th>
</tr>
<tr>
<td>Jhon</td>
</tr>
<tr>
<td>alexa</td>
</tr>
</table>
);
[Link](myelement,[Link](„root‟));
Example3:
Import React from „react‟;
Import ReactDOM from „[Link]/client‟;
Const myElement=<h1>I LIKE js!</h1>;
Const root=[Link]([Link](„root‟));
[Link](„root‟);
Example4:
Import React from „react‟;
Import ReactDOM from „react-dom/client‟;
Const myElement=(
<ul>
<li>apples</li>
<li>bananas</li>
<li>cherries</li>
</ul>
);
Const root=[Link]([Link](„root‟));
[Link](myElement);

What is JSX?
JSX stands for JavaScript XML(xml is extention of HTML).
JSX allows to write HTML in react.
Also it makes easier to write and add HTML in react.
Example: create Element {---}
Append Child{----}
Expressions in JSX:
Expressions in JSX
The expressions can be react variable or property are any other valid JavaScript express.
Ex: const myElement = <header> react is {5+5} times better with JSX.</header>
Attribute class = className
A class attribute is a much used in HTML attribute, but since JSX is rendered JavaScript and
the class keyword is reserved word in JavaScript.
Ex: const myElement=<h1 className = “myclass”>Hello world</h1>;
React components:
Components are independent and reusable bits of code. They serve the same purpose as
javascript functions, but work in isolation and return in html.
React components they are two types:
1. Class components
2. Function components.
1. A class components includes the extents [Link] statements. This
statements create an inheritance to react component, and gives your components
excess to react component function.
ex: class car extends [Link] {
render() { return <h1> hi, I am not a car!</h1>;
}
A function components also returns html, and behaves much the same way as a class
components but function components can be return using much function less code, are
eiser to understand also it is a powerfull.
Ex:
Function car(){
Return <h1>hi, I am a car! </h1>;
}

Rendering a component:
To use this component in your application, use similar syntax as normal html. <car>
</car>
Display the car component in the root element “root” .
Ex:
Const root=[Link] ([Link](“root”));
[Link](<car/>);
Props: props are like function arguments, and you send them into the component as
attributes.
Ex:
Function car(prpos) {return<h2> I am a {[Link]} car!</h2>;
Const root =[Link]
([Link](„root‟));
Root render(<car color = “red” />;
React state:
The state object is where you store property values that belongs to the component.
Creating the state object is initialized in the constructor.
Ex:
Class car extends [Link]{
Constructor (props){
Super(props)
[Link]={brand: “BMW”};
}
Render(){
Return(
<div>
<h1> my car</h1>
</div>);
}
}

Understanding lifecycle of components:


Each components in react as a lifecycle which you can monitor and manipulate during its
three main phases:
[Link] phase
[Link] phase
[Link] phase
[Link] phase: mounting means putting elements into the DOM (document object
model).
React as 4 built in methods:
[Link] ()
[Link] ()
3. render ()
[Link]()
[Link] phase:
a component is updated whenever the is change in the component state or props.
React as 5 in built method:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]
[Link] phase:
When a component is removed from the dom or unmounting has react likes to call it .
React has only 1 built in method.
[Link]()
React event handlers:
Event handlers are like html DOM events react can perform actions based on user events.
React has the same events as html like click, change, mouseover etc..
Then react event handlers are using this curly bracket {}.
Ex: onClick ={shoot},
<button onClick = {shoot}> take the shoot</button>
Html
Ex: <button onclick =”shoot”()>take the shoot</button>.
Function football(){
Const shoot=(){
Alter(“Grout shot”);
}
Return(
<button onClick={shoot}>take the shoot!</button>
);
}
Const root=[Link]([Link](„root‟));
[Link](</football>);

React conditional rendering: in react, you can conditionally render components.


If statement: we can use the if statement JavaScript operator to decide which component of
render.
function goal(props){
Const isGoal = [Link];
If(isGoal){
Return<madeGoal/>;
}
Return<missedGoal/>;
}
Const root = [Link]([Link](„root‟));
[Link](<Goal isGoal={false}/>);

React list:
In react list, you will render list in some type of loop.
The JavaScript map array method is generally the prepared method.
Ex: function car(props){
Return<li> I am a {[Link]}</li>;
}
Function garage(){
Const cars=[„ford‟, „bmw‟, „audi‟];
Return(
<>
<h1> who lives in my garage?</h1>
<ul>
{[Link]((car)=><car brand={car}/>}
</ul>
<i>);
}
Const root=[Link]([Link](„root‟));
[Link](<garage/>);

React keys: react keys allows, react to keep track of element this way, if an a item is update
or removed only that item will be rerender instead of the entire list.
Ex: function car(props){
Return<li> I am a {[Link]}</li>;
}
function garage(){
Const cars={id:1,brand:‟ford‟}
{id:2,brand:‟bmw‟}
{id:3,brand:‟audi‟}
Return(
<>
<h1> who lives in my garage?</h1>
<ul>
{[Link]((car)=><car brand={car, id, brand={[Link]}/>}
</ul>
<i>);
}
Const root=[Link]([Link](„root‟));
[Link](<garage/>);

Example 1:
Import React from „react‟;
Import ReactDOM from „react-dom/client‟;
function MyForm() {
return (
<form>
<label>Enter your name:
<input type=”text”/>
</label>
</form>
)

Const root= [Link]([Link](„root‟));


[Link](<MyForm/>);
React Hooks:
Hooks allow function components to have access to state and other React features. Because
of this. Class components are generally no longer needed.
Although Hooks generally replace class components there are no plans to remove classes
from React.

What is HOOK?
Hooks allow us to “hook” into React features such as state and lifecycle methods.
Hook rules:
There are 3 rules for hooks:
 Hooks can only be called inside React function components.
 Hooks can only be called at the top level of a component.
 Hooks cannot be conditional.
React useState Hook:
The React useState Hook allows us to track state in a function component.
Import { useState } from “react”;
Import ReactDOM from “react-dom/client”;
Function FavoriteColor() {
Const [color, setColor] = useState(“red”);
Return (
<>
<h1>My favorite color is {color}! </h1>
<button
type=”button”
onClick= {() = >setColor (“blue”)}
>Blue </button>
</>
)
}
Const root = [Link]([Link](„root‟));
[Link](<FavoriteColor />);
Example2:
Import React, { useState } from “react”;
Import ReactDOM from “react-dom/client”;
function FavoriteColor(){
const [color, setColor] = useState(“red”);
return(
<>
<h1> MY favorite color is {color}! </h1>
<button
Type=”button”
onClick={() => setColor(“blue”)}
>Blue</button>
Type=”button”
onClick={() =>setColor(“red”)}
>Red</button>
<button
Type=”button”
onClick={() => setColor(“pink”)}
>pink</button>
<button
Type=”button”
onClick={() => setColor(“green”)}
>green</button>
</>
);
}
Const root=
[Link]([Link](„root‟));
[Link](<FavoriteColor />;

React useEffect Hooks:


The useEffect Hook allows you to perform side effects in your components.
Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffect accepts two arguments. The second argument is optional.
useEffect(<function>,<dependency>)
Example3:
Use setTimeout() to count 1 second after initial render:
Import ( useState, useEffect } from “react”;
Import ReactDOM from “react-dom/client”;
Function Timer(){
Const [count, setCount] = useState(0);
useEffect(() => {
setTimerout(() => {
setCount((count) => count +1);
},1000);
});
Return <h1> I have rendered {count} times! </h1>;
}
Const root =
[Link]([Link](„root‟));
[Link](<Timer/>;

React useContext Hook:


React context
React Context is a way to manage state globally.
It can be used together with the useState Hook to share state between deeply nested
components more easily than with useState alone.
Example 3:
Import { useState, createContext } from “react”;
Import ReactDOM from “react-dom/client”;
Const UserContext = createContext()
Example 4:
Function component1() {
Const [user, setUser] = useState(“ O My God”);
Return(
<[Link] value= {user}>
<h1> {„Hello $ {user}!‟} </h1>
<componet2 user={user} />
</[Link]>);
}
React Custom Hooks:
Hooks are reusable functions.
When you have components logic that needs to be used by multiple components, we can
extract that logic to a custom Hook.
Custom Hooks start with “use”. Example: useFetch.
Example 5:
[Link]:
import { useState, useEffect } from “react”;
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => [Link]())
.then((data) => setData(data));
}.[url]);
Return [data];
};

Type Script:
Type script is a syntactic super set of JavaScript which adds static typing.
Why should I use typescript?
JavaScript is a loosely typed language. It can be difficult to understand what types of data are
being passed around in JavaScript.
In JavaScript, function parameters and variables do not have any information. So developers
needs to look at documentation, or guess based on the implementation.
TypeScript compiler: TypeScript is transpiled into JavaScript using a compiler.
TypeScript being converted into JavaScript means turns anywhere that JavaScript runs.
(intel j ide app)
Installing the compiler: TypeScript is a installed compiler which can be installed through
notepad++ or NPM.
For running the TypeScript program [Link] to run typescript program. Suppose we use
nodejs we use npm.
Basic type or simple types (primitive): types script supports simple type or basic type
There are three main type of basic Type: or primitive
1. Boolean
2. String (typescript, rocks)
3. Number
TypeScript function: typescript has a specific syntax for typing function parameters and
a return values.
Example 6: function gettime(): number{
return new Date().gettime();
}
[Link](gettime());

What is an API?
Application programming interface (API) is a software interface that allows two
applications to interact with each other without any user intervention. API is a collection
of software functions and procedures. In simple terms, API means a software code that
can be accessed or executed. API is defined as a code that helps two different software‟s
to communicate and exchange data with each other.
Application programming interface

How API works?


Most web API‟S sit between the application and the web server. The user initiates the
API calls that tells the application to do something, then the application will use an API to
ask the web server to do something. The API is the mid map between the application and
the webserver and the API calls its request.
Why we need API?
 Application programming interface acronym API helps two different software‟s to
communicate and exchange data with each other.
 It helps you to embed content from any site or application more efficiently.
 APIs can access app components. The delivery of services and information is
more flexible.
 Content generated can be published automatically.
 It allows the user or a company to customize the content and services which they
use the most.
 Software needs to change over time, and API‟s help to anticipate changes.
Types of API:
1. Open API
2. Partner API
3. Internal API
4. Composite API
[Link] APIs: These types of APIs are publicly available to use like OAUTH APIs from
Google. It has also not given any restriction.
open API also called public API, is an application programming interface made publically
available to software developers .
open APIs are published on the internet and shared freely.
[Link] APIs: specific rights or licences to access this type of API because they are not
available to the public.
[Link] APIs: internal or private. These APIs are developed by companies to use in their
internal systems. It helps you to enchance the productivity of your terms.
[Link] APIs: this type of API combines different data and services APIs.
Types of API‟s protocol:
[Link]: simple object access protocol
SOAP is a standard protocol that was first designed so that applications built with different
languages and on different platforms could communicate.
Using SOAP, the request to the APIs is an HTTP post request with an XML request body.
2. REST: Representational state transfer it‟s a software architecture that imposes
conditions on how an API should work. REST was initially created as a guideline to
manage communication on a complex network like an internet.
Example: application programming interface.
REST API‟s can be called with all of the HTTP verbs. To get a resource. In this case, a
user, a GET request is used. While the SOAP request is hold‟s the user‟s name in the
body, a REST API accept GET parameters from the UPI.
GET [Link]
What is an endpoint?
An API endpoint is a digital location where an API receives requests about a specific
resource on its server. in APIs, an endpoint is typically a uniform resource on the server.
Why are API endpoints are important?
Endpoint specifies where resource can be accessed by API and play a key role in
guarantee the correct functioning of a software that interact with it.
APIs performance relies on its ability to communicate effectively with API endpoints.
API endpoint example: API server and base URL
All API endpoints are relative to the base URL.
For example: assuming the base URL of,
[Link]
endpoints reffers to For example: assuming the base URL of,
[Link] In open API 3.0, you use the server array to specify one
or more base URLs for your APIs.
How to test API endpoints?
When discussing web APIs we‟re usually talking about a type of API called a REST API,
which utilizes HTTP methods that tell the API what action to take. The four most
common HTTP methods in API requests are:
Get: retrieves a resource
POST: creates a resources
Put: updates an existing resource
Delete: removes a resource
Examples:[Link]

HTTP concepts: HTTP (HYPERTEXT TRANSMITTING PROTOCOL) is a set of


rule which is used for transferring the files like video, audio, graphics, image text and
other multimedia files.
How does HTTP WORKS: as a request response protocol HTTP gives users a way to
interact with web resources such as HTML files by transmitting hyper text messages
between client and serves.
HTTP clients generally use transmission control protocol or internet protocol.
Connections to communicate with server.
Web API: web API is a developers dream
 It can extend the functionality of the browser.
 It can greatly simplify complex functions
 It can provide easy syntax to complex code.
What is web API?
API stands for application programming interface.
A web API is an application programming interface for the web.
A browser API can extend the functionality of a web browser.
A server API can extend the functionality of a web server.
Example:
Get the latitude and longitude of the user‟s position:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript geolocation </h2>
<p>Click the button to get your coordinates.</p>
<button onClick=”getLocation()”>Try it</button>
<p id=”demo”></P>
<script>
Const x=[Link](“demo”);
Function getLocation (){

Try{
[Link](showPostion);
} catch {
[Link]=err;
}
}
Function showPostion (postion){
[Link] =”Latitude: “ + [Link] + “<br>Longitude: “
+[Link];
}
</script>
</body>
</html>
Meta character attribute: HTML <meta> tag which specifies the character encoding for the
HTML document
<head>
<meta> - character set chartset=UTF-8 the character set attribute specifies the character
encoding for the HTML document.
UTF-8: Unicode transformation format, it can be used to represent any Unicode character
depending on a Unicode numeric value. For corresponding UTF-8 code is 1,2or 3byte
sequence.

OOP (object oriented programming language) concepts:


Java : it is a object oriented programming language, it is used to develop mobile application,
web apps, desktop apps, games, webserver application and banking application and so on.
OOP (object oriented programming language) concepts and design principles:
There are four types of principles of object-oriented programming are encapsulation,
abstraction, inheritance and polymorphism.
OOPS concepts are as follows:
Class.
Object.
Method and method passing.
Pillars of OOPS. Abstraction, encapsulation, interface, polymorphism compile time
polymorphism run time polymorphism.
example:
public class s1{
public static void main(String [] args) {
[Link]("welcome to mysure");
}
Why use java?
 Java works on different platforms (windows, mac, linux, Raspberry Pi etc.)
 It is one of the most popular programming language in the world.
 It has a large market in the current job market.
 It is easy to learn and learn something
 It is open-source and free
 It is secure, fast and powerful.
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs.
 As Java is close to C++ and C#, it makes it easy for programmers to switch to java or
vice versa.
If you do not have java installed on your computer you can go through this for free
[Link].
Advantages of OOPS:
 OOP is faster and easier to execute.
 OOP provides a clear structure for the programs.
 OOP helps to keep the java code DRY “Don‟t Repeat Yourself”. And makes the code
easier to maintain, modify and debug.
 OOP makes it possible to create full reusable applications with less code and shorter
development time.

You might also like