Tuesday, 24 September 2019

Enable HTTPS URL for Spring Boot wep application


Enable SSL certificate in spring boot application.
To enable https URL first we need to create an SSL certificate and configure the SSL certificate with spring boot application.


Create SSL certificate –
Navigate to the java installation directory, inside bin folder there is keytool executable file.
Run below command to generate jks file.
keytool -genkeypair -alias cert -keyalg RSA -keysize 2048 -keystore cert.jks -validity 3650
Run below command to get the content of keystore-
keytool -list -v -keystore cert.jks


Create a spring boot application–
Copy the certificate jks file in src/main/resources folder
Add below property in you application.yml file
server.port: 8443
server.ssl.key-alias: cert
server.ssl.key-store-password: ********
server.ssl.key-store: classpath:cert.jks
server.ssl.key-store-provider: SUN
server.ssl.key-store-type: JKS
Now you can access the url with https 
Refer below repository for project-
Enable SSL URL for web application

Friday, 20 September 2019

GraphiQL

GraphiQL is a query language, it’s expose a single endpoint API and we can fetch data from query as per the needs.
Graph QL can be used with any programming language and with any framework.
Grabh QL is more efficient and flexible in client-server communication.
A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type
Example:-
Create Graph QL using spring boot. Add below dependency.
dependencies {
    compile 'com.graphql-java-kickstart:graphql-spring-boot-starter:5.0.5'
     compile 'com.graphql-java-kickstart:graphiql-spring-boot-starter:5.0.5'
     compile 'com.graphql-java-kickstart:graphql-java-tools:5.3.4'
}
Add below mapping in application.yml
graphql:
  servlet:
    mapping: /api/graphql
    enabled: true

graphiql:
  enabled: true
  mapping: /graphiql
  endpoint:
    graphql: /api/graphql
  cdn:
    enabled: true
    version: 0.12.0
Create a graph QL query schema schema.graphqls
type Query {
  firstName: String!
  lastName: String!
}
Now create a query resolver class to handle above query, create one method for each query field
import org.springframework.stereotype.Component;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;

@Component
public class RootQueryResolver implements GraphQLQueryResolver {

     public String getFirstName() {
           return "Manoj";
     }

     public String getLastName() {
           return "Kumar";
     }
}
Now run spring boot application and run below URL
This will open the graph QL tool in browser now you can pass the query
{
  firstName,
  lastName
}
Output:-
{
  "data": {
    "firstName": "Manoj",
    "lastName": "Kumar"
  }
}
Refer below screenshot-
Defining Object Fields in schema-
type Query {
  employee: Employee!
}
type Employee {
     EmployeeNo: String!
     Name: String!
}
In above example we have defined a field employee of type Employee object and then further declaration Employee type object with its fields. Now create a method in query resolver class getEmployee() which will return employee object.
To declare a list use below scheme-
type Query {
  employee: [Employee!]
}
type Employee {
     EmployeeNo: String!
     Name: String!
}
Defining more complex schema:-
type Query {
  employee: Employee!
}

type Employee {
     empId: String!
     firstName: String
     lastName: String
     age: Int
     addressList: [String]
}
Query resolver class-
import java.util.Arrays;

import org.springframework.stereotype.Component;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import spring.boot.graphql.model.Employee;

@Component
public class RootQueryResolver implements GraphQLQueryResolver {

     public Employee getEmployee() {
           Employee employee = new Employee();
           employee.setEmpId("123");
           employee.setFirstName("Manoj");
           employee.setLastName("Kumar");
           employee.setAge(30);
           employee.setAddressList(Arrays.asList("Addrs1","addrs2"));
           return employee;
     }
}

Refer below screenshot for output



Sunday, 11 August 2019

Kubernetes

Kubernetes is a container management tool.
Docker creates container to deploy the application, while Kubernetes works on top of Docker. It’s manages the container, basically it works more on container auto scaling and load balancing.


Before proceeding with Docker first install Docker, refer below tutorial for Docker installation-


Saturday, 3 August 2019

Node JS

Node.js is a powerful framework developed on Chrome’s V8 JavaScript engine
Node JS is an open source server environment for java script, you can run you java script in server using Node JS, earlier


Download node JS from - https://nodejs.org/en/download/
To run you first Node JS programe create a folder under user directory
C:\Users\<SysUserName>\<Node Folder any Name>\<place here all js files>
Now open command prompt and navigate to above directory
Open notepad and write the below code –

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Welcome in MK Study Journal!');
}).listen(8080);

Save the file <filename>.js extension and run below command on CMD.
Node <fileName>.js
Node open your browser and run http://localhost:8080/
This will print “Welcome in MK Study Journal” in browser.

Let’s explain above code
var http = require('http');  it’s importing the http module, there are several module that can be import as per requirement.
You can also download other module using npm(node package manager), use below command –
npm install <package-name>
createServer is callback function in http module, it have 2 argument req and res, in res field we specify the header with status code and content-type, ending with string “Welcome in MK Study Journal


In above example we are using built in module http.
To use a module use require(“<module-name>”)


List of built in module-
1.      http- This is used for http server, http request and http response object
2.      url- Is used for url parsing, fetching details like hostname, port etc
3.      querystring- method to handle querystring
4.      path- File path methods
5.      fs- Used for file i/o operation
6.      util- Used for utils functions
Refer below example for few of built in modules.
var url = require('url');
var urladdress = 'http://localhost:8080/default.htm?query1=test1&query2=test2';
var parsedurl = url.parse(urladdress, true);

console.log(parsedurl.host);
console.log(parsedurl.pathname);
console.log(parsedurl.search);
var querydata = parsedurl.query;
console.log(querydata.query1);

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.writeFile('mkstudyjournal.txt', 'hello ! welcome!', function(err) {
    res.writeHead(200, {'Content-Type': 'text/html'});
  });
 
  fs.readFile('mkstudyjournal.txt', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
 
}).listen(8080);
See below output-


Custom module can also be created and used same as above.
To create custom module use exports keyword, refer below snippet-
exports.dateTime = function () {
  return Date();
};
Save above code in date-time.js file and run it will create module with name date-time
Now we can use as follows-
var http = require('http');
var dt = require('date-time’);

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("Current date: " + dt.dateTime());
  res.end();
}).listen(8080);


Sunday, 28 July 2019

Python Basics and Fundamentals


Basics and Fundamentals of Python


Python is more powerful language in modern days. Python is widely used in AI and machine learning.

Let’s download the python library https://www.python.org/downloads/  and IDE for python -https://www.jetbrains.com/pycharm/ download community edition of pycharm.


Now open pycharm and create a app.py file start with first code-
print("MK Study Journal")  # will print MK Study Journal in console


Beauty of python is we need no to create any explicit data variable, it automatically create the variable as assigned value. Refer below
print("MK Study Journal")  # will print MK Study Journal in console

variable1 = "MK Study Journal"
print(variable1) # will print 'MK Study Journal' in console

variable2 = True
print(variable2) # will print 'True' in console

variable3 = 123
print(variable3) # will print '123' in console


Take user input-
variable = input("Please enter True\False: ")
print(variable) # will print user input True\False


Conditional statement-
variable = input("Please enter number between 1 to 10: ")
if variable < 5:
   
print("Won")
elif variable < 10:
   
print("loss")
else:
   
print("Invalid input")


Multiple assignment-
a = b = c = 1
a,b,c = 1,2,"MK Study Journal"
print(a) # will print 1
print(b) # will print 2
print(c) # will print MK Study Journal


Python String:-
variable = "MK Study Journal"
print(variable[0]) # will print character at index 0 = M
print(variable[0:5]) # will print character form index 0 to 5 = MK St
print(variable[-1]) # will print last character = l
print(variable[:]) # will print compete string = MK Study Journal


Data Type conversion:-
variable = input("Please enter you birth year ") #variable is treated as String
age = 2019 - int(variable) # string to int conversion
print(age) # will print age if user input 1988 the age will be 31


Types of operator-
var1 = 10
var2 = 2
print(var1+var2) # addition 12
print(var1-var2) # substraction 8
print(var1*var2) # * Multiplication 20
print(var1/var2) # / Division 50
print(var1%var2) # % Modulus 0
print(var1**var2) # ** Exponent 100
print(var1//var2) # // floor division 5


Loop Control:-
# while loop
count = 0
while (count < 10):
  
print('The count is:', count)
   count = count +
1
  
# for loop
for char in 'MKStudyJournal':
  
print('Current Letter :', char)

# nested loop
var1 = 2
while(var1 < 100):
   var2 =
2
  
while(var2 <= (var1 / var2)):
      
if not(var1 % var2): break
     
var2 = var2 + 1
  
if (var2 > var1/var2) : print (var1, " is prime number")
   var1 = var1 +
1


Triple quotes-print multiline string-
# triple quote to print multi line string
variable = """ Hello Friends
Welcome in MK Study Journal"""
print(variable)


List operations-
list1 = ['M','T', 'W','T', 'F','S','S']
list2 = [
1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])      # list1[0]:  M
print ("list2[1:5]: ", list2[1:5])  # list2[1:5]:  [2, 3, 4, 5]

# updating value in list
list1[0] = 'Mon'
list2[1] = 'two'
print ("list1[0]: ", list1[0])      # list1[0]:  Mon
print ("list2[1]: ", list2[1])      # list2[1]:  two

print (len(list1[1]))  # length of list1 is 7
print (len(list2[1]))  # length of list2 is 7

# deleting value in list
del list1[0]
del list2[1]
print ("list1[0]: ", list1[0])      # list1[0]:  T
print ("list2[1]: ", list2[1])      # list2[1]:  3

# length of list after one element deletion
print (len(list1[1]))  # length of list1 is 6
print (len(list2[1]))  # length of list2 is 6

print (max(list1[1]))  # max element in list1 is T
print (min(list2[1]))  # min element in list1 is 1


Tuples – tuples is a sequence of immutable python objects.
tuple1 = (1, 2, 3, 4, 5 );
tuple2 =
"a", "b", "c", "d";
emptyTuple = ()
singleValueTuple = (
1,)
print(tuple1)           # print (1, 2, 3, 4, 5)
print(tuple2)           # print ('a', 'b', 'c', 'd')
print(emptyTuple)       # print ()
print(singleValueTuple) # print (1,)
print(tuple1[0])        # print 1
print(tuple1[-1])       # print 5
print(tuple1[1:4])      # print (2, 3, 4)
tuple3 = tuple1+tuple2  # updating tuple
print(tuple3)           # print (1, 2, 3, 4, 5, 'a', 'b', 'c', 'd')
del tuple3              # delete entire tuple
print(tuple3)           # NameError: name 'tuple3' is not defined
tuple3 = ('Hi!',) * 4
print(tuple3)           # print ('Hi!', 'Hi!', 'Hi!', 'Hi!')
print('Hi!' in tuple3)  # print true


Dictionary: - Dictionary is a key value pair separated by: and represent in curly braces.
Like –{key1:value1, key2:value2}
dictionary1 = {}    # empty dictionary
dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print ("dict['key1'] value: ", dict['key1'])    # dict['key1'] value:  value1
print ("dict['key2'] value: ", dict['key2'])    # dict['key2'] value:  value2

dict['key1'] = 1;                                # update existing entry
print ("dict['key1'] value: ", dict['key1'])     # dict['key1'] value:  1

del dict['key1'];                                # remove entry with key 'key1'
print ("dict['key1'] value: ", dict['key1'])    # KeyError: 'key1'
dict.clear();                                    # remove all entries in dict
print (dict)                                     # {}
del dict ;                                       # delete entire dictionary


Function block:-
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
A return statement with no arguments is the same as return None.
def checkPrime( num):
  
if num%2 != 0:
      
print("Prime number")
  
else:
      
print("Not a Prime number")

def factorial(num):
    fatorial =
1;
   
while num >= 1:
        fatorial = fatorial*num
        num = num-
1
   
print("factorial value is ",fatorial)

number =
int(input("Enter number : "))  # user input number

factorial(number)
checkPrime(number)


Handling with files
import os

fileObject =
open("mkstudyjournal.txt", "w+")   # open file in wb-Opens a file in writing and reading
print("Name of the file: ", fileObject.name)    # Name of the file:  mkstudyjournal.txt
fileObject.write( "second-MK Study Journal")    # write into file
fileObject.write( "third-MK Study Journal")     # write into file
print(fileObject.seek(0,0))                     # reset reader pointer position 0
print("", fileObject.read(45))                  # read file
print(fileObject.tell())                        # Current file position 45
fileObject.close()

os.rename(
"mkstudyjournal.txt", "ren-mkstudyjournal.txt")
os.makedirs(
"/temp/text")                        # make directory
os.removedirs("/temp/text")                      # remove directory


Exception Handling-
try:
    fileObject =
open("test1", "w")
    fileObject.write(
"Exception handling!!")
except IOError:
   
print("Error: can\'t find file or read data")
else:
   
print("success")
    fileObject.close()

try:
    var1 =
int(input("Enter number: "))
    var =
10/var1
except ValueError:          # if input value is not numeric
   
print("Error: can not convert to int, Invalid number")
except ZeroDivisionError:   # if input value is 0
   
print("Error: can\'t divide by zero")
else:
   
print("success")

User defined error-
class CustomkError(RuntimeError):
   def __init__(self, arg):
      self.args = arg

try:
   raise CustomkError("user defined error")
except CustomkError:
    print("Error: custom error")


Object oriented
class Student:

    fullName = "test"

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        Student.fullName = firstName+" "+lastName

    def fullName(self):
        print("Student name: ", Student.fullName)

    def displayStudent(self):
        print("FirstName : ", self.firstName, ", LastName: ", self.lastName)

student = Student("Manoj", "Kumar")
student.displayStudent()
 
# inheritance property implementation
class Person:

    fullName = "test"

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        Student.fullName = firstName + " " + lastName

    def displayPerson(self):
        print("Hello parent", Student.fullName)

    def displayWelcome(self):
        print("Welcome")

class Student(Person):

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        Student.fullName = firstName+" "+lastName

    def displayPerson(self):
        print("Hello child", Student.fullName)


student = Student("ChildFN", "ChildLN")
student.displayWelcome()    # call parent method print Welcome

# method overriding
student.displayPerson()     # call child method print Hello child ChildFN ChildLN

person = Person("ParentFN", "ParentLN")
person.displayPerson()      # parent method print -Hello parent ParentFN ParentLN


CGI Programming in Python-
Create httpd.cfg with below content –
<Directory "/cgi-bin">  
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>

<Directory "/cgi-bin">
Options All
</Directory>
Create python file in directory /cgi-bin CGI.py
import cgitb

cgitb.enable()

print("Content-Type: text/html\n")
print("<!doctype html>")
print("<h2>Welcome in MK Study Journal</h2>")
print("<h2>Thank you !!</h2>")
Run below command in terminal-
python -m http.server --bind localhost --cgi 8080
Open browser-
terminal command will be as follows-


Navigation between CGI-
Create below textareasubmit.py file-
import cgitb

cgitb.enable()

print("Content-Type: text/html\n")
print("<!doctype html>")
print("<body>")
print('<form action = "/cgi-bin/textarea.py" method = "post"')
print('<textarea name = "textArea" cols = "40" rows = "4">')
print("</textarea>")
print('<input type = "submit" value = "Submit" />')
print("</form>")
print("</body>")
Create below textareareader.py file
import cgi, cgitb

form = cgi.FieldStorage()

if form.getvalue('textArea'):
   text_area = form.getvalue('textArea')

else:
   text_area = "Not entered"

print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<body>")
print("<h2> Entered Text is %s</h2>" % text_area)
print("</body>")
Now open below url –
http://localhost:8080/cgi-bin/textareareader.py and enter the text in text area and submit, this will navigate to http://localhost:8080/cgi-bin/textarea.py


Multithreading in Python-
import threading
import time

class PrintNumbers(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):

        for i in range(10):
            time.sleep(1)       #sleep for 1 seconds
            print(i)            # will print 0 to 9
            print(threading.current_thread()) # threadName <PrintNumbers(Thread-1, started 19464)>

thread1 = threading.Event()

t1 = PrintNumbers()
t1.start()

import threading

class PrintNumbers(threading.Thread):

    def __init__(self, startIndex, lastIndex, step, set_event, clear_event):
        threading.Thread.__init__(self)
        self.startIndex = startIndex
        self.lastIndex = lastIndex
        self.step = step
        self.set_event = set_event
        self.clear_event = clear_event


    def run(self):
        for i in range(self.startIndex, self.lastIndex, self.step):
            print(i)
            self.set_event.set()
            self.clear_event.clear()
            self.clear_event.wait()
        self.set_event.set()


thread1 = threading.Event()
thread2 = threading.Event()

t1 = PrintNumbers(0, 10, 2, thread1, thread2)
t2 = PrintNumbers(1, 10, 2, thread2, thread1)

t1.start()
t2.start()

t1.join()
t2.join()