Tuesday, June 16, 2020

NodeJs basic concepts

It is a server side runtime environment for java script running on google chrome v8 machine that allows java script to run on server side stand alone machine as a applications. Hence Nodejs is not a language. It has following benefits
1- It is Event driven. Means as in this we have event that is fired and depending on the type of event listener catch it and perform operations.
2- It is non blocking i.e. if we get three hit or nodejs request all are executed at the same time and one which complete the processing will be given the result first. It is not like old fashion where all ther request are queued and depending on FIFO algo they are taken for request processing on availability of server.
3- It is lightweight, fast and highly recommended for real time applications.
you can download the latest stable version of nodejs from https://nodejs.org/en/download/
Make sure to install both node and npm and check the version of Node and Npm using command
node -v
npm-v
to check if the nodejs is working fine on your machine just print node and perform this simple example
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node
Welcome to Node.js v14.2.0.
Type ".help" for more information.
> console.log ("hello world")
hello world
undefined
Now lets start to set up the working folder for the nodejs that we are going to us for our demo small projects.
I am using Microsoft Visual Source Code as an IDE which comes with inbuild many nodejs plugin for ease of development.
First we will set the working folder and then we will run the command as
npm init
This will create a package.json file that will contains all the base module that we are going to use in our application. In real world scenario we give our code with package.json file. At run time the developer/tester or Production/SAT environemnt can create the whole project just by running
npm install
The above command will by default look into package.json and install all the module register into that are mandate to running our application.
Whern we run npm init it will ask for some default informaion fill it and it wil create package.json files.
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (nodejsexample) nodejsexample
version: (1.0.0)
description: This package containes nodejs exmaple
entry point: (index.js)
test command:
git repository: (https://github.com/shdhumale/nodejsexample.git)
keywords:
author: Siddaratha dhumale
license: (ISC)
About to write to C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\package.json:
{
"name": "nodejsexample",
"version": "1.0.0",
"description": "This package containes nodejs exmaple",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/shdhumale/nodejsexample.git"
},
"author": "Siddaratha dhumale",
"license": "ISC",
"bugs": {
"url": "https://github.com/shdhumale/nodejsexample/issues"
},
"homepage": "https://github.com/shdhumale/nodejsexample#readme"
}

Is this OK? (yes) y
1- Package.json
{
"name": "nodejsexample",
"version": "1.0.0",
"description": "This package containes nodejs exmaple",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/shdhumale/nodejsexample.git"
},
"author": "Siddaratha dhumale",
"license": "ISC",
"bugs": {
"url": "https://github.com/shdhumale/nodejsexample/issues"
},
"homepage": "https://github.com/shdhumale/nodejsexample#readme"
}
now let create a new nodejs file and name it as siddhu.js

console.log("Hello world")
var a = 10
var b = 20
console.log(a + b)

and execute it using command as
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\siddhu.js
Hello world
30
3- Object, Anonymous and Arrow Function:-
In node js we can create an object as shown below
var user = { name: 'siddhu', surname: 'dhumale' }
console.log(JSON.stringify(user))
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\siddhuobject.js
{"name":"siddhu","surname":"dhumale"}

'- Anonymous funtoin :- This are the funtion which has no name we can define it as
var user = function (a) {
console.log("values are" + a)
}
user(10)
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\annonymus.js
values are10
'- Arrow funtion
const user = () => {
console.log("hello Arrow function")
}
user();
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\annonymus.js
hello Arrow function
4- Global Objects in node js:-
These are the few of the global object that are predefined object and user can use it as it is defualt available to the user while development
1- Dirname - give the directory names.
2- filename - give the file name full file name with paths.
3- exports - use to export the module/class/components so that it can be used by other component in the application.
4- console - use to print the value on prompt
5- module - this is used to export the module class/components etc
6- buffer
7- requires : to import the package that we are going to use in our applications.

'- anonymus.js
var user = function (a) {
console.log("values are" + a)
}
function testExport(a, b) {
var c = a + b
console.log("ans" + c)
}
user(10)
module.exports.user = user
module.exports.testExport = testExport
'- importtest.js
var user = require('./annonymus')
console.log('---------user---------------' + JSON.stringify(user))
console.log('-----------testExport-------------' + JSON.stringify(user.testExport(2, 3)))
output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\importtest.js
values are10
---------user---------------{}
ans5
-----------testExport-------------undefined

5- Some basic concept of What is ECMAScript
var, const and let
a) const :-
means it is consant and canno be changed but once you define it as an object it will allow you to change
const a =10
const a =20
//this will give error
const a = {
name:"siddharatha",
surname:"dhumale"
}
console.log(a.name)
output :- siddharatha
we can also modify it
const a = {
name:"siddharatha"
surname:"dhumale"
}
a.address="india"
//or a.name="siddhu"
console.log(a.address)
output :- india

b) let
can be used in templage literal
This means we cannot define same varibale again like const
let a =10
let a =20
//this will give error
but we can do the same in functions
let a = 10
function test()
{
let a= 20
console.log(a)
}
console.log(a)
test()
output:-
10
20
c) var
This will give the latest valye of the variable with out any error. it will allow duplicates.
var a=10
var a= 20
console.log(a)
Output :- 20
d) String literal
/* const a = {
name: "siddharatha",
surname: "dhumale"
}
a.name = "siddhu"
console.log(a.name) */
var a = "siddhu"
var b = "dhumale"
console.log("First name " + a + " surname " + b)
console.log(`string literal First name ${a} surname ${b}`)
output :-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\ecmsscript.js
First name siddhu surname dhumale
string literal First name siddhu surname dhumale
6- Prototype
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
var myFather = new Person("John", "Doe", 50, "blue");
console.log(myFather.nationality)
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample> node .\prototype.js
English

7- Module in node.js
Module is similar to package in java. It has collection of component that has unique functionality to be addressed.
Consider modules to be the same as JavaScript libraries.A set of functions you want to include in your application.
Let take example we are creating four component or module add,sub,div and mul for math operation
a) add.js
function add(a, b) {
return a + b
}
module.exports.add = add
b) sub.js
function sub(a, b) {
return a - b
}
module.exports.sub = sub
c) mul.js
function mul(a, b) {
return a * b
}
module.exports.mul = mul
d) divide.js
function divide(a, b) {
return a / b
}
module.exports.divide = divide
e) calculator.js
var add = require('./add')
var sub = require('./sub')
var divide = require('./divide')
var mul = require('./mul')
console.log(add.add(1, 2))
console.log(sub.sub(5, 2))
console.log(divide.divide(8, 2))
console.log(mul.mul(1, 2))
output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\calculator> node .\calculator.js
3
3
4
2

8- Http Module
This is the module used for making http request to fetch the data from the external webservice.
Lets first use for creating simple node http server
a) httpserver.js

first we have to require handle for http module using
var http = require('http');
after that we have to create a server using createServer function from http module
http.createServer()
Now also give listening port to http
http.createServer().listen(4000)
Now lets run this file and see the browser hitting url
http://localhost:4000
you will see you did not get any output on the screen and that is because we did not send any response back to broser. Now lets do that

var http = require('http');
http.createServer(
function (req, res) {
//below res inform what to do with the response.
res.write("hello world")
//below command indicate res is end and ready render the screen on the browser
res.end()
}
).listen(4000)
Now lets run this file and see the browser hitting url
http://localhost:4000
you will see hello world on the screen
Image11
9- Nodemon Installation
https://www.npmjs.com/package/nodemon
Additional when we start the server we did not get anything on the console that indicate that server is started for that we can add console.log as shown below
var http = require('http');
http.createServer(
function (req, res) {
res.setHeader("Content-Type", "html");
//res.setHeader("Content-Type", "text/plain");
res.write("<h1>hello world</h1>")
res.end()
}
).listen(4000, console.log("Server started"))

Now as you can see everytime we changes the node files we always need to restart the server once again to get ride of this we need to install nodemon.
we can install nodemon using below command. Generally it is prefered to install nodemon on global level.
npm install -g nodemon
or for dev mode
npm install --save-dev nodemon

to run the application make changes in package.json like this
"main": "./HttpModule/httpmodule.js",
"scripts": {
"start": "nodemon",
"test": "echo \"Error: no test specified\" && exit 1"
},

and use this command
npm start .\httpmodule.js
Note: If you get below error then follow the solution given below.
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> nodemon
nodemon : File C:\Users\Siddhartha\AppData\Roaming\npm\nodemon.ps1 cannot be loaded. The file C:\Users\Siddhartha\AppData\Roaming\npm\nodemon.ps1 is not digitally
signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ nodemon
+ ~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess

Solutions:-
1- PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> Get-ExecutionPolicy
Unrestricted
2- PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> Get-ExecutionPolicy -list
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Unrestricted
3- PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> Set-ExecutionPolicy unrestricted
For more information refer to the site
https://www.opentechguides.com/how-to/article/powershell/105/powershel-security-error.html
http://mvsourcecode.com/powershell-ps1-is-not-digitally-signed-you-cannot-run-this-script/
Now start the applicatoin using
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\HttpModule> nodemon .\httpmodule.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node .\httpmodule.js`
Server started
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node .\httpmodule.js`
Server started
10 - File System Module in node.js
Now lets understand the File operation using file module of Nodejs. As we know Nodejs is server side language it has capability to create/delete/update the file present on the server using this modules.
to use this module we need to use package called "fs"
var fs = require('fs');
fs.readFile(__dirname + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log(data);
}
}
)
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\Files> node .\fileoperation.js
This is siddhu text files used

You can also delete the file using below unlink
fs.unlink(__dirname + "/siddhu.txt", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("Files deleted:");
}
})
Now lets read the files from the text files and divert it to browser

var http = require('http');
var fs = require('fs');
http.createServer(
function (req, res) {
fs.readFile(__dirname + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("Read data:" + data);
res.setHeader("Content-Type", "text/plain");
//res.setHeader("Content-Type", "text/plain");
res.write(data)
res.end()
}
}
)
}
).listen(4000, console.log("Server started"))
Image2
11- Sync and Async function in file system
Difference between Sync and Async is that for Async the programe did not waite for data to come but it execute the next line in the programe.
Let me show you with this exmaple. By defualt all the function in Nodejs FS module is Asyn in nature

a) var fs = require('fs');
fs.readFile(__dirname + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log(data);
}
}
)
console.log("ASync programing")
If we execute above programe we will get
Output:-
ASync Program
Read data:This is siddhu text files used
As you see above "ASync Program" is printed first before real output of the file that is our programe did not waite for the output to come but directly execute the next line the programe and after that when it get the response from the files it show the files data.
b)
try {
var syncdata = fs.readFileSync(__dirname + "/siddhu.txt")
console.log("Read data:" + syncdata);
console.log("Sync Program")
}
catch (exception) {
console.log(exception)
}
Output:-
Read data:This is siddhu text files used
Sync Program

12- Events, Custom Events and Trigger Custom Event in Node.js
NodeJs is event driven languages. Means we fire the action or event and depending on the type of event of action we perform operations. For that we use event module
var event = require("event")
Let take one example

var events = require('events')
var eventEmitter = new events.EventEmitter()
//Assign the event handler to an event:
eventEmitter.on('scream', () => { console.log("this function is fired using eventemitter") });
//Fire the 'scream' event:
eventEmitter.emit('scream');
OutPut:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\events> node .\eventscript.js
this function is fired using eventemitter
We can also write the above code as
var events = require('events')
var eventEmitter = new events.EventEmitter()
/* function printLog() {
console.log("this function is fired using eventemitter")
}
*/
/* var printLog = function () {
console.log("this function is fired using eventemitter")
}
*/
var printLog = () => {
console.log("this function is fired using eventemitter")
}
//Assign the event handler to an event:
eventEmitter.on('scream', printLog)
//Fire the 'scream' event:
eventEmitter.emit('scream');

Now lets to execute the programe that will fire the event and then read the data from the files.

var events = require('events')
var eventEmitter = new events.EventEmitter()
var fs = require('fs');
/* function printLog() {
console.log("this function is fired using eventemitter")
}
*/
/* var printLog = function () {
console.log("this function is fired using eventemitter")
}
*/
var printLog = () => {
console.log("this function is fired using eventemitter")
fs.readFile(__dirname + "/../Files/" + "/siddhu.txt", "utf-8", (err, data) => {
if (err) {
console.log(err);
}
else {
console.log("Read data:" + data);
}
}
)
}
//Assign the event handler to an event:
eventEmitter.on('scream', printLog)
//Fire the 'scream' event:
eventEmitter.emit('scream');

Output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\events> node .\eventscript.js
this function is fired using eventemitter
Read data:This is siddhu text files used
We can also have nested event call i.e event calling the other event call.
var events = require('events')
var eventemitter = new events.EventEmitter()
var firstevent = (a, b) => {
console.log("first event trigger " + a * b)
eventemitter.emit("second_event")
}

var secondevent = () => {
console.log("second event trigger")
eventemitter.emit("third_event")
}
var thirdevent = () => {
console.log("third event trigger")
}
//on is used to listen the event
eventemitter.on("first_event", firstevent)
eventemitter.on("second_event", secondevent)
eventemitter.on("third_event", thirdevent)
//emit is used to fire the event
eventemitter.emit("first_event", 10, 20)

Output:-
PS C:\Visual_Source_Code_WorkSpace_NodeJS\nodejsexample\events> node .\nestedevent.js
first event trigger 200
second event trigger
third event trigger

Friday, June 12, 2020

Redux with ReactJs example for using state container

Redux and React are two different JavaScript language. React is more towards the view part of MVC and redux is third party library that handle state of the application globally.
So let first create a simple react application where in we will have local state which we will increase or decrease the local state with click on Increment and Decrement button
Step 1:- lets first create a new reactJS application using below command
npx create-react-app my-app
Once the application is installed execute the below command and check the ui.
cd my-app
npm start
Image1
Step 2:- We are going to create a simple reactjs application having a counter as number and having two button 1- for increment and 2- decrement
Please find the below code for the same.
import React from 'react'
class Simplereactredux extends React.Component {
constructor(props) {
super(props)

this.state = {
counter: 1

}
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}

increment() {
this.setState({ counter: this.state.counter + 1 })
}

decrement() {
this.setState({ counter: this.state.counter - 1 })
}

render() {
return (
<div>
<h1>This is parent component</h1>
<label > Counter: <span>{this.state.counter}</span> </label>
<br></br>
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
</div >
)
}
}

export default Simplereactredux

Image2
Now in above example we had used the normal state i.e. local state defined in class to do the increment and decrement operations.
Now lets move to take this local state to our Redux central state container so that it will be available for all the component to access direclty who had subscribe themself to this store and get notified when there is change in the state with the help of subscriber.

For doing this we will need to packages to be installed in our application
1- redux :- This package will provide us the environment to create a central store where we can keep the global state of the application which can be modified by firing the event or action through reducer.
2- react-redux :- As redux is external thrid party predictable state container management tool for interacting it with the redux we need to create a bridge that connect this two different packages.

Lets now install both of them using below commands
npm install redux --save
npm install react-redux --save
and check your package.json having this two package installed init.

Now as we know in Redux we have three main parts
1- Store
2- Reducer
3- Action
First we will create a reducer which is responsible to perform action as per the action_type on the global state store in the stores.
I am creating a folder inside src folder called as store and will create reducer.js
const intialState = {
counter: 1
}
const reducer = (state = intialState, action) => {
const newState = { ...state }
return newState
}

export default reducer

Now as we are going to use the store as global we need to inject it into the react at the top level or highest level of top level component which is our app.js where we inject out </simplereactredux> component. The package which we will use to inject the global store is Provider from react-redux.
//1- Need to import Provider packages from react-redux to inject the global store for our application.
import { Provider } from 'redux-react'
<Provider>
<Simplereactredux></Simplereactredux>
</Provider>

Now lets create the store using createStore packages of redux
//2- Create the store now that can be used by the react using redux
import myreducer from './store/reducer'
const store = createStore(myreducer)
and finally give this store to our entire React application as shown below
<Provider store={store}>
<Simplereactredux></Simplereactredux>
</Provider>
Now the next step would be to comment all the code that we were using to store the data a local state and need to plugin our store in our component so that we can use the global stores. This need to be done for all the components to map with stores for using this global stores. i.e. mapping the props.
Along with this also note we need to subscribe our react application to redux so that whenever there is a changes in the global state in redux our react application can be notified and also we must be able to fire/dispatch an action/event with action_type from react to the redux to modify the global state from redux.
In container/ReactJs applcation we use either local state or props. As now we are going to use the global state of redux only the option left for us is to use the props concept to get in touch with the Redux from reactjs application/containers.
for this we have follwing fucntion mapDispatchToProps
mapDispatchToProps = (dispatch) => {
return {
increment: () => dispatch({ type: 'action_type_increment' }),
decrement: () => dispatch({ type: 'action_type_decrement' }),
}
}
As shown above in this function we are mapping our button function with this props and further from this method we deliver/fire/dispacth event with action_type i.e. action_type_increment or action_type_decrement.
Now the question is where this action type will go ..yes you are right as per the Redux when ever the action is dispatched/fire from the application it will go to the reducer and depending on the action_type it will perform respective operation on global state.
Additional we also want the subscription of our reactjs application so that when ever there is change in the global state that state can be accessed/refresh at our container or pages. For that also we will need to map it with the props so that is automatically available for us using funtion mapStateToProps

mapStateToProps = (state) => {
return
{
counter: this.state.counter
}
}

Finally we need to contact our container/reactjs application to store and that is done using connect
//below package is used to connect react application or react component with Redux.
import { connect } from 'react-redux'
Use this connect as HOC as shown below
export default connect( mapStateToProps , mapDispatchToProps) (Simplereactredux)

whole code
import React from 'react'
//below package is used to connect react application or react component with Redux.
import { connect } from 'react-redux'
class Simplereactredux extends React.Component {
constructor(props) {
super(props)
this.state = {
// counter: 1
}
/* this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this); */
}
/* increment() {
this.setState({ counter: this.state.counter + 1 })
}

decrement() {
this.setState({ counter: this.state.counter - 1 })
}
*/

render() {
return (
<div>
<h1>This is parent component</h1>
<label > Counter: <span>{this.props.counter}</span> </label>
<br></br>
<button onClick={this.props.increment}>Increment</button>
<button onClick={this.props.decrement}>Decrement</button>
</div >
)
}

}
const mapStateToProps = (state) => {
return {
counter: state.counter
}
}
const mapDispatchToProps = (dispatch) => {
return {
increment: () => dispatch({ type: "action_type_increment" }),
decrement: () => dispatch({ type: "action_type_decrement" }),
}
}
// use the connect HOC to connect reactjs component to redux
export default connect(mapStateToProps, mapDispatchToProps)(Simplereactredux)
Image3
Note: You can download the source code from https://github.com/shdhumale/simplereactreduxexample

Thursday, June 11, 2020

Simple Redux example

Some of the follower has asked to explain Redux concept in more simple way as they found below explainination little bit hard to understand.

http://siddharathadhumale.blogspot.com/2020/04/redux-library-and-its-uses-in-java.html

Considering this i am trying to explain Redux with more simple form. I assume if you are not aware of the Redux concept please refer above url.
Redux is the third party extension that can be used as a predictable state container .
Following are the important aspect of the Redux
-> SAR – MA :-
‘- Store :- store the state of the Application as a central repository shared with all the applications.Create store , Getstate – to get the state of the application, susbcribe(listener) for subscrbing and unsubscribing the listener as the state change and dispatch(action) is used to make change in state in the store.
‘- Action :- indicate what need to be done with the state which is readonly. No Direct update is avaialble for the application to change the state in store.
‘- Reducer:- Actully carrier out the change in the state.

Simple_Redux
Lets take a simple example where in we have a varible named as counter whose value is store in the state. Through action we either increment or decrement the counter which in tern perform the increment or decrement of its state value in store. and fially we can get the updated inc/dec value of the counter stored as state in store.
Step :1 - Install redux from npm so that we can create store to accomodate state values. Use below command to install redux.
npm install redux --save
check in package.json file if the redux is added into dependencies. If you do not have package.json create it using command
npm init
Step 2:- First we need to create a store using below command
const { createStore } = require('redux')
const store = createStore()

Step 3:- Now store take Reducer as an argument so lets create a reducer
const myReducer = (state, action) => {
}
We can also define the initial state as shown below
const initialState = {
counter: 1
}
const myReducer = (state = initialState, action) => {
}
Step 4:- Now lets assign this myReducer to our create store
const store = createStore(myReducer)
step 5:- As we did not have any UI applicaton that can fire the event to change the value of the counter inside store we can do it manually by dispatch methond as shown below in which we tell reducer that action is dispatched with its type as increment
store.dispatch({ type: 'increment' })
Step 5:- Now inside reducer we can check this action type and confirm what action need to be done with counter variable that is stored in global or store state
for increment we want to increase the value of counter with 1 and need to update that value in global state in store.
const myReducer = (state = initialState, action) => {
const newState = { ...state }
if (action.type === 'increment') {
//as in react we do not directly modify the state without setState here we will do it by
//creating copy of the state using spread operators
newState.counter = newState.counter + 1
}
return newState
}
Step 5:- Now finally execute the below programe and you will see how we can do the increment and decrement of the counter value which is store as global state in store of redux.
const { createStore } = require('redux')

const initialState = {
counter: 1
}
const myReducer = (state = initialState, action) => {
const newState = { ...state }
if (action.type === 'increment') {
//as in react we do not directly modify the state without setState here we will do it by
//creating copy of the state using spread operators
newState.counter = newState.counter + 1
}
if (action.type === 'decrement') {
//as in react we do not directly modify the state without setState here we will do it by
//creating copy of the state using spread operators
newState.counter = newState.counter - 1
}
return newState
}
const store = createStore(myReducer)
console.log(store.getState())
store.dispatch({ type: 'increment' })
console.log(store.getState())
store.dispatch({ type: 'decrement' })
console.log(store.getState())
Out put
PS C:\Visual_Source_Code_WorkSpace_ReactJSNew\simplereduxexample> node .\simpleredux.js
{ counter: 1 }
{ counter: 2 }
{ counter: 1 }

now the question arise how i would be know automatically that value of global state i.e. counter inside store is changed. We dont want to manually track everytime checking global state change. For this we have beautiful concept of subscriber
store.subscribe(() => {
console.log("Nofied automatically that state is changed:- " + JSON.stringify(store.getState()))
})
and then we can remove all the console log.

const { createStore } = require('redux')
const initialState = {
counter: 1
}
const myReducer = (state = initialState, action) => {
const newState = { ...state }
if (action.type === 'increment') {
//as in react we do not directly modify the state without setState here we will do it by
//creating copy of the state using spread operators
newState.counter = newState.counter + 1
}
if (action.type === 'decrement') {
//as in react we do not directly modify the state without setState here we will do it by
//creating copy of the state using spread operators
newState.counter = newState.counter - 1
}
return newState
}
const store = createStore(myReducer)
store.subscribe(() => {
console.log("Nofied automatically that state is changed:- " + JSON.stringify(store.getState()))
})
//console.log(store.getState())
store.dispatch({ type: 'increment' })
//console.log(store.getState())
store.dispatch({ type: 'decrement' })
//console.log(store.getState())




now lets say we also want to pass a value that will indicate how much we want to do increment and decreament and this value is called payload

i.e.
const myReducer = (state = initialState, action) => {
    const newState = { ...state }
    if (action.type === 'increment') {
        //as in react we do not directly modify the state without setState here we will do it by
        //creating copy of the state using spread operators
        newState.counter = newState.counter + action.val
    }

    if (action.type === 'decrement') {
        //as in react we do not directly modify the state without setState here we will do it by
        //creating copy of the state using spread operators
        newState.counter = newState.counter - action.val
    }
    return newState
}
store.dispatch({ type: 'increment', val:10})


Final code will be 

const { createStore } = require('redux')

const initialState = {
    counter: 1
}
const myReducer = (state = initialState, action) => {
    const newState = { ...state }
    if (action.type === 'increment') {
        //as in react we do not directly modify the state without setState here we will do it by
        //creating copy of the state using spread operators
        newState.counter = newState.counter + action.val
    }

    if (action.type === 'decrement') {
        //as in react we do not directly modify the state without setState here we will do it by
        //creating copy of the state using spread operators
        newState.counter = newState.counter - action.val
    }
    return newState
}

const store = createStore(myReducer)
store.subscribe(() => {
    console.log("Notified automatically that state is changed:- " + JSON.stringify(store.getState()))
})
//console.log(store.getState())
store.dispatch({ type: 'increment', val: 10 })
//console.log(store.getState())
store.dispatch({ type: 'decrement', val: 10 })

//console.log(store.getState())

OutPut :-

PS C:\Visual_Source_Code_WorkSpace_ReactJSNew\simplereduxexample> node .\simpleredux.js
Notified automatically that state is changed:- {"counter":10}

Notified automatically that state is changed:- {"counter":1}

Thursday, June 04, 2020

SOLID Design Principle Concept

Whereever we talk about software development it is mandate to follow certain rules so that we did not get into troble in later aspect of software development. Few of the aspect that we should think before developing any softare is
1- What should be the Architecture we should follow i.e. MVC, MVP, MVVP etc
2- Design Principle
3- Design Pattern :- Which can be classified further into Creational, Behavioural and Structural Design Pattern.
Here we will discuss about the Design Principle. The reason behind using this design principle it helps software to
- Maintainability
- Testability
- Flexibility and extensibility
- Parallel development
- Loose coupling

There are lot of design principle provided my Robert.C.Martin out of which few espically 5 Design principle taken as subset from them by Micael Feathers usig the acronym SOLID. Having said this lets ellaborate this SOLID Acronym
S :- Single Responsibility Principle (SRP)
O :- Open Close Principle (OCP)
L :- Liskov substitution Principle (LSP)
I :- Interface segregation Principle (ISP)
D :- Dependency Inversion Principle (DIP)
Now lets take one by one and understand them in depth
1- S :- Single Responsibility Principle (SRP)
As the name suggest according to this principle each class/interface should be responsible for one and one task/action/activity/. i.e. Each module/class should be responsible over single part of the functionality provided by the software.
Simple way to explain if you we have one login class/interface that will be responsible for loggin only and not for other activities
/**
*
*/
package Interface;
/**
* @author Siddhartha
*
*/
public interface IUser {
Boolean logIn(String userName, String password);
Boolean Registration(String userName, String password);

//notificaiton
boolean sendMail(String emailId);
boolean sendSMS(String phoneNumber);

//Log Error
void Error(String error);


}
As shown above the interface contains method not only for login and registration but also for notification and error which break SRP. As per SRP it should satisfy only one functionality of the software application in our case for login functionality we need only logIn and Registration method rest method we can divide into another interface as shown below i.e.

/**
*
*/
package Interface;
/**
* @author Siddhartha
*
*/
public interface IUser {
Boolean logIn(String userName, String password);
Boolean Registration(String userName, String password);

}
/**
*
*/
package Interface;
/**
* @author Siddhartha
*
*/
public interface INotification {
boolean sendMail(String emailId);
boolean sendSMS(String phoneNumber);

}
/**
*
*/
package Interface;
/**
* @author Siddhartha
*
*/
public interface IError {

void Error(String error);
}

2- I :- Interface segregation Principle (ISP)
As per this principle we should not have bulk Interface i.e. keeping all the method in one interface. In long run modifying this interface result into modifying all the class that implement it even tough if they are not using that methods. Best way is to divide Interface as per the functionaliy. Lets take below example
/**
* @author Siddhartha
*
*/
public interface IUser {
Boolean logIn(String userName, String password);
Boolean Registration(String userName, String password);

//notificaiton
boolean sendMail(String emailId);
boolean sendSMS(String phoneNumber);

//Log Error
void Error(String error);


}
As shown above as the interface contain all the method those class which implement this interface eventhough if they dont want notification of error functionality they have to override the method with empty implementation. Along with this in future if this interface changes then again all the class need to be override the new method in them respectively with even implementing into it which may result into testing of all the module. So best approcah is to divide the interface into small specific functionality interface as we did above i.e. divide IUser into IError and INotifications.
3- O :- Open Close Principle (OCP)
As per this priciple class/module.functions should always be open to be extended but should be closed to be modified at individual level. This means you can develop your class in such a way where other class can extends them and add additional functionality using he current one but should be changed them self to address the new requirement. Lets understand this using simple example.
/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public class OpenClosePrinciple {

public void getBonus(int salary)
{
int bonus = salary*10/100;
System.out.println("bonus:"+bonus);
//return bonus;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OpenClosePrinciple objOpenClosePrinciple = new OpenClosePrinciple();
//For confirm employee

objOpenClosePrinciple.getBonus(1000);
}
}
OutPut:-
bonus:100
In above example we calculate bonus of the confirm employee. Everything working fine now lets say you have different type of employee i.e. confirm, contract, thirdparty and you want to canculate their bonus which is of different % i.e bonus for confirm employee is 10%, bonus for contract employee is 7% and bonus for third party employee is 5%. In this case there is two option either we modify the above class as given below
/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public class OpenClosePrinciple {

int bonus = 0;

public void getBonus(int salary, String employeeType)
{
if("Confirm".equals(employeeType))
{
bonus = salary*10/100;
System.out.println(" Confirm bonus:"+bonus);
}
else if("Contract".equals(employeeType))
{
bonus = salary*7/100;
System.out.println(" Contract bonus:"+bonus);
}
else
{
bonus = salary*5/100;
System.out.println("ThridParty bonus:"+bonus);
}

//return bonus;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OpenClosePrinciple objOpenClosePrinciple = new OpenClosePrinciple();
//For confirm employee

objOpenClosePrinciple.getBonus(1000, "Confirm");
objOpenClosePrinciple.getBonus(1000, "Contract");
objOpenClosePrinciple.getBonus(1000, "ThridParty");
}
}
OutPut :-
Confirm bonus:100
Contract bonus:70
ThridParty bonus:50

Above example is good to go but as per te OCP priciple it is not good to modify the original class functionality. We already had use OpenClosePrinciple and to accomodate new requirement i.e. different type of emplyee we had modified the original class better option would be as give below
/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public abstract class OpenClosePrinciple {


public abstract void getBonus(int salary);

/**
* @param args
*/
/*
* public static void main(String[] args) { // TODO Auto-generated method stub
* OpenClosePrinciple objOpenClosePrinciple = new OpenClosePrinciple(); //For
* confirm employee
*
* objOpenClosePrinciple.getBonus(1000, "Confirm");
* objOpenClosePrinciple.getBonus(1000, "Contract");
* objOpenClosePrinciple.getBonus(1000, "ThridParty");
*
*
* }
*/
}

/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public class ConfirmEmployee extends OpenClosePrinciple {
@Override
public void getBonus(int salary) {
// TODO Auto-generated method stub
int bonus = salary*10/100;
System.out.println(" Confirm bonus:"+bonus);

}
}
/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public class ContractEmployee extends OpenClosePrinciple {
@Override
public void getBonus(int salary) {
// TODO Auto-generated method stub
int bonus = salary*7/100;
System.out.println(" Contract bonus:"+bonus);

}
}
/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public class MainEmployeeClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OpenClosePrinciple objConfirmEmployee = new ConfirmEmployee();
objConfirmEmployee.getBonus(1000);

OpenClosePrinciple objContractEmployee = new ContractEmployee();
objContractEmployee.getBonus(1000);
}
}
OutPut:-
Confirm bonus:100
Contract bonus:70
As in above example we have made the getBonus method as abstract and allowed the different specific class to extend this class overide this method for their specific use we make sure that our abstract class will need not be changed in the future for specific type of employee bonus.
4- L :- Liskov substitution Principle (LSP)
As per this priciple when ever we child class extend parent class in that case Parent class object can be replaced by child class. Little bit confused...
If S is the subtype of Parent class P, then objects of type P may be replaced by the object of Type S. But the catch here is this rule it also state that the new derived class should not produce any exception that is not in the parent class.
In our above example we had implemented partially this principle i.e.
/**
* @author Siddhartha
*
*/
public class MainEmployeeClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OpenClosePrinciple objConfirmEmployee = new ConfirmEmployee();
objConfirmEmployee.getBonus(1000);

OpenClosePrinciple objContractEmployee = new ContractEmployee();
objContractEmployee.getBonus(1000);
}
}
here we have created Object of Child class ConfirmEmployee and ContractEmployee. Also we had replaced completely the original parent class object i.e. OpenClosePrinciple. Lets say we have another Employee type as thirdparty and they are not eligible for bonus. If using above concept if implement the same logic in that case we need to throw an exception as this thridparty employee is not eligible for bonus and this breaks our LSP principle where in derived class should not throw an exception that is not present in the base/parent class.
/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public class ThirdPartyEmployee extends OpenClosePrinciple {
@Override
public void getBonus(int salary) {
// TODO Auto-generated method stub
try {
throw new Exception("Not eligible for bonus");
}
catch(Exception e)
{
e.printStackTrace();
}

}
}
/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public class MainEmployeeClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OpenClosePrinciple objConfirmEmployee = new ConfirmEmployee();
objConfirmEmployee.getBonus(1000);

OpenClosePrinciple objContractEmployee = new ContractEmployee();
objContractEmployee.getBonus(1000);

OpenClosePrinciple objThirdPartyEmployee = new ThirdPartyEmployee();
objThirdPartyEmployee.getBonus(1000);

}
}
OutPut:-
Confirm bonus:100
Contract bonus:70
java.lang.Exception: Not eligible for bonus
at Classes.ThirdPartyEmployee.getBonus(ThirdPartyEmployee.java:16)
at Classes.MainEmployeeClass.main(MainEmployeeClass.java:24)
To over come this best option is to use Interface and use contract as required

/**
*
*/
package Classes;
/**
* @author Siddhartha
*
*/
public abstract class OpenClosePrinciple {


public abstract int getSalary(int salary);

/**
* @param args
*/
/*
* public static void main(String[] args) { // TODO Auto-generated method stub
* OpenClosePrinciple objOpenClosePrinciple = new OpenClosePrinciple(); //For
* confirm employee
*
* objOpenClosePrinciple.getBonus(1000, "Confirm");
* objOpenClosePrinciple.getBonus(1000, "Contract");
* objOpenClosePrinciple.getBonus(1000, "ThridParty");
*
*
* }
*/
}
package Interface;
/**
* @author Siddhartha
*
*/
public interface IEmployeeBonus {
public void getBonusInterface(int salary) ;
}
/**
*
*/
package Classes;
import Interface.IEmployeeBonus;
/**
* @author Siddhartha
*
*/
public class ConfirmEmployee extends OpenClosePrinciple implements IEmployeeBonus{
@Override
public void getBonusInterface(int salary) {
// TODO Auto-generated method stub
int bonus = salary*10/100;
System.out.println(" Confirm bonus:"+bonus);

}
@Override
public int getSalary(int salary) {
// TODO Auto-generated method stub
return salary;
}
}

/**
*
*/
package Classes;
import Interface.IEmployeeBonus;
/**
* @author Siddhartha
*
*/
public class ContractEmployee extends OpenClosePrinciple implements IEmployeeBonus{

@Override
public void getBonusInterface(int salary) {
// TODO Auto-generated method stub
int bonus = salary*7/100;
System.out.println(" Contract bonus:"+bonus);
}
@Override
public int getSalary(int salary) {
// TODO Auto-generated method stub
return salary;
}
}
/**
*
*/
package Classes;
import Interface.IEmployeeBonus;
/**
* @author Siddhartha
*
*/
public class ThirdPartyEmployee extends OpenClosePrinciple implements IEmployeeBonus{

@Override
public void getBonusInterface(int salary) {
// TODO Auto-generated method stub
System.out.println("No bonus for TirdParty Employee");

}
@Override
public int getSalary(int salary) {
// TODO Auto-generated method stub
return salary;
}
}

/**
*
*/
package Classes;
import Interface.IEmployeeBonus;
/**
* @author Siddhartha
*
*/
public class MainEmployeeClass {
/**
* @param args
*/
public static void main(String[] args) {

// To get salary we can have contract as given below

// TODO Auto-generated method stub
OpenClosePrinciple objConfirmEmployee = new ConfirmEmployee();
int ConfirmEmployeeSalary = objConfirmEmployee.getSalary(1000);
System.out.println("ConfirmEmployeeSalary:"+ConfirmEmployeeSalary);


OpenClosePrinciple objContractEmployee = new ContractEmployee();
int ContractEmployeeSalary = objContractEmployee.getSalary(1000);
System.out.println("ContractEmployeeSalary:"+ContractEmployeeSalary);


OpenClosePrinciple objThirdPartyEmployee = new ThirdPartyEmployee();
int ThridPartyEmployeeSalary = objThirdPartyEmployee.getSalary(1000);
System.out.println("ThridPartyEmployeeSalary:"+ThridPartyEmployeeSalary);

//here if we try to access the bonus we will get the exception i.e.
//objConfirmEmployee.getBonusInterface(ConfirmEmployeeSalary);


//To get the bonus use contract of interface
IEmployeeBonus objIEmployeeBonusConfirmEmployee = new ConfirmEmployee();
objIEmployeeBonusConfirmEmployee.getBonusInterface(ConfirmEmployeeSalary);


IEmployeeBonus objIEmployeeBonusContractEmployee = new ContractEmployee();
objIEmployeeBonusContractEmployee.getBonusInterface(ConfirmEmployeeSalary);

IEmployeeBonus objIEmployeeBonusThirdPartyEmployee = new ThirdPartyEmployee();
objIEmployeeBonusThirdPartyEmployee.getBonusInterface(ConfirmEmployeeSalary);
}
}

OutPut:-
ConfirmEmployeeSalary:1000
ContractEmployeeSalary:1000
ThridPartyEmployeeSalary:1000
Confirm bonus:100
Contract bonus:70
No bonus for TirdParty Employee

5- D :- Dependency Inversion Principle (DIP)
As per this priciple higher modules shoule not depends on low-level modules. Both should depends on abstraction. This means interaction of higher module with the lower module shoule be abstract. Best example is in server side we use to make call to DAOIMPL from BO class but this is not good design .
i.e. instead of this
BO--> DAOImpl -->SRVImpl
Use this :- Business object to Data Access Object interface and from Data Access Object interface to its Data Access Object Implementations.
BO--> DAO--> DAOImpl -->SRV --> SRVImpl

Tuesday, May 12, 2020

Minikube to deploy tomcat container from docker

To deploy the any container from the docker we need to first create the deployment.yaml file. Please refer to the below file
apiVersion: apps/v1
kind: Deployment
metadata:
name: siddhu-tomcat-deployment
spec:
selector:
matchLabels:
app: tomcat
replicas: 1
template:
metadata:
labels:
app: tomcat
spec:
containers:
- name: tomcat
image: tomcat:9.0
ports:
- containerPort: 8999
use the following command in sequence wise
1- kubectl apply -f C:\kubernetes-minikube\deployment.yaml
Image1
2- kubectl expose deployment siddhu-new-tomcat-deployment --type=NodePort
Image2
Please make sure to check the status of the container using
kubectl get pod
Image4Image5Image6Image7
Finally to check if the tomcat is running expose the above in url using below command

To install minikube use this site

https://minikube.sigs.k8s.io/docs/start/

and download the minikube installer from 

https://storage.googleapis.com/minikube/releases/latest/minikube-installer.exe

3- minikube service siddhu-new-tomcat-deployment --url

Image3
4- check if it is running using curl or browser
For deploying Apache httpd in docker using kubernetes use below deployment,yaml
'- deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpd-deployment
spec:
selector:
matchLabels:
app: httpd
replicas: 1
template:
metadata:
labels:
app: httpd
spec:
containers:
- name: httpd
image: httpd:2.4.43
ports:
- containerPort: 80

Before Deployment
Image1
After Deployment
Image2
Exposing to url and cheking if the httpd is running

Image3Image4

Note: Important command to get all
kubectl get all
'- And to delete the pod or deployment use
kubectl delete pod/nameofthepod

Minikube with windows for Kubernetes

As we know we have many online site that provide us to work directly on the ready made Kubernetes Cluster created for use i.e. 1 Master node and 1 Worker nodes
Kubernetes Playground:-https://www.katacoda.com/courses/kubernetes/playground
Play with Kubernetes Classroom:- https://training.play-with-kubernetes.com/
Play with Kubernetes :- https://labs.play-with-k8s.com/
Lets go in details and try to setup our own virtual box that contain Kubernetes cluster and that can be done using minikube.
So in short minikube is the tool that work on VM machine and used to create a single kubernetes note i.e. one master and one worker nodes with docer intalled in it. So when we deploy Minikube we get our own kubernetes cluster to work on it.
As we are using windows machine we are going to follow the below given step to setup minikube
Step 1:- Install Minikube Please refer to the below link it has all the step for Windows, Linux and MacOs for minikube installation.
https://kubernetes.io/docs/tasks/tools/install-minikube/
For windows first check you have your Hyper-V Requirement and it has to be set to YES i.e. Virtualization Enabled In Firmware: Yes. You can check this using below command.
systeminfo
If the value is NO go to the bios and set the same.
Step 2:- Install Kubectl
Please refer to the below url
https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-kubectl-on-windows
You can download the exe directly from https://storage.googleapis.com/kubernetes-release/release/v1.18.0/bin/windows/amd64/kubectl.exe
and add it to your path so that it can be access from any cmd prompt. Check using command
kubectl version --client
Kubectl is the tool that is used to execute command to interact with Master node of the Cluster through API server.
Other option is to use chocolatey which is similar to brewhome in MacOS.
https://chocolatey.org/
Use this command to install kubectl using chocolatey
choco install kubernetes-cli
Step 3:- Install a Hypervisor
This is important as we want to run our Minikube on virtual instance. We have two way to do it
• Hyper-V
• VirtualBox
I had used Virtual box concept as i used the same in docker exercise. Download window base virtual machine setup from https://www.virtualbox.org/wiki/Downloads
step 4:- Finally install minikube usind either by choco
choco install minikube

or direclty take the exe from below path
https://github.com/kubernetes/minikube/releases/latest/download/minikube-installer.exe
Step 5:- Start the minikube
To start the minikube we need to use the below command
minikube start
Generally it take the driver automatically but it is better to give the name explicitely so i use this command
minikube start --driver=virtualbox
Please refer to this sites
https://kubernetes.io/docs/setup/learning-environment/minikube/#specifying-the-vm-driver
https://minikube.sigs.k8s.io/docs/drivers/virtualbox/

Image1
check the status
Image2
Above image state that all the required things in the kubernest is running properly i.e. apiserver of master nodes, kubelets of worked notes etc.
Image3
Above image show it has only one master node and service as kubernetes running but no pod in worker notes.
here at this stage if you run command to check if this container has any service or pod in side it will show empty like below
Now once the minikube gives us the cluster for paying with Kubernetes lets deploy the ready made container/pods from docker in our kubernetes.
Here we are using image named echoserver. Let’s create a Kubernetes Deployment using an existing image named echoserver, which is a simple HTTP server and expose it on port 8080 using --port.
Image4
Now once the deployment is done we need to expose it so that outer system can access it on perticular port for that we need to use below command
Image5
Once we exposed the deployment we had made our pod launced check it using this command
Image6
Finally exposed it using the URL i.e. Get the URL of the exposed Service to view the Service details:
Image7
Finally open the url in browser

Image8
Or consume using curl
Image9

Please also try to execute command like

'- Delete the hello-minikube Service:
kubectl delete services hello-minikube
'- Delete the hello-minikube Deployment:
kubectl delete deployment hello-minikube
'- Stop the local Minikube cluster:
minikube stop
'- Delete the local Minikube cluster:
minikube delete
Now also try to use one the example or container form docker using deployment.yaml and perform the above operation that will give you more details. Take deployment/container of tomcat for better and easy understanding.