18 January 2020

K8S

Kubernetes cluster manages the containers for
1.Deployment
2.Maintenance
3.Scaling.


Steps to create a deploy a spring boot application to google cloud with kubernetes cluster
1.Create a spring boot app and push it to git.
2.Login to google cloud console and create a docker image by pulling application
3.Deploy container image to kubernetes cluster.
4.Allow traffic
5.Test it by  adding additional containers and changing versions.

HTML5

25%  <meter><progress>

This
is
 formatted  <pre>
text

 <input range>

iam small  <small>

marked text  <mark>

JavaPro9NoYesquoted
<sup><sub><del><q>

<FieldSet>
Java9pro Java
HTML
DS


<bdo> Writing left to right Is it right 

<Audio>

<Video> 

14 October 2018

Caching with Spring Boot

What-Why Cache?
Cache is a memory between an application and database to reduce the number of
Database hits.It improves performance of applications by reducing expensive
operations(Ex:DB hits), if it is stored with frequently accessed data.
Data which changes less frequently(static master data) and frequently accessed
data can be stored in cache.


Spring boot Cache:
Spring framework provides cache
api to integrate with different cache providers.
Spring boot provides @EnableCaching annotation to enable cache management.
When @Cacheable annotation is used at method level, Spring manages the request and response in cache.@Cacheable annotation has "key" attribute to decide a request to be cached.

Example:
Check code at https://github.com/java9pro/java9pro-cache
Project structure look like


pom.xml
Add dependency spring-boot-starter-cache for enabling cache management.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"         
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>java9pro</groupId>
    <artifactId>java9pro.springboot.cache</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-archiver</artifactId>
            <version>3.4</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.9</source>
                    <target>1.9</target>
                    <jdkToolchain>
                        <version>9</version>
                    </jdkToolchain>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
        </plugins>
    </build>

</project>
ProductController
It has request mapping with url path parameter as "id" and calls service method.
package com.cache.java9pro;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestControllerpublic class ProductController {
    @Autowired    MobileService mobileService;

    @GetMapping("/mobile/{id}")
    public   Mobile findMobileDetailById(@PathVariable String id)
    {
       return mobileService.getMobileDetailByID(id);
    }
}
Mobile
It is a simple POJO with required attribute id
package com.cache.java9pro;

public class Mobile {
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getRam() {
        return ram;
    }

    public void setRam(String ram) {
        this.ram = ram;
    }

    String id;
    String model;
    String ram;
    public Mobile(String id, String model, String ram) {
        this.id=id;
        this.model=model;
        this.ram=ram;
    }
}
MobileService
It has @Cacheable annotation enabled method  getMobileDetailByID 
which call DAO method if and only if the request/response are not available in cache. 
package com.cache.java9pro;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Servicepublic class MobileService {

    @Autowired    MobileDAO  mobileDAO;

    @Cacheable(value="mobile", key="#id")
    public Mobile getMobileDetailByID(String id)
    {
        Mobile mobile=null;
        try {
            System.out.println("Getting from database");
            Thread.sleep(5000);
            mobile = mobileDAO.getMobileInfo(id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return mobile;
    }
}

MobileDAO
To simulate database access, provided switch-case implementation for different ids
package com.cache.java9pro;

import org.springframework.stereotype.Component;

@Componentpublic class MobileDAO {

    public Mobile getMobileInfo(String id) {
        switch (id){
            case "1" : return new Mobile(id,"Samsung","4GB");
            case "2" : return new Mobile(id,"Apple","6GB");
            case "3" : return new Mobile(id,"Motorola","2GB");
            case "4" : return new Mobile(id,"Lenovo","3GB");

        }
        return null;
    }
}
CacheApplication

It is Spring boot application method with annotation @EnableCaching

package com.cache.java9pro;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication@EnableCachingpublic class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

application.properties
application.port=8080
Upon running main method application starts on port 8080.
To test the application execute the following URLs
  1. http://localhost:8080/mobile/1
  2. http://localhost:8080/mobile/2
  3. http://localhost:8080/mobile/3
  4. http://localhost:8080/mobile/4
  5. http://localhost:8080/mobile/1
  6. http://localhost:8080/mobile/2
  7. http://localhost:8080/mobile/3
  8. http://localhost:8080/mobile/4
First 4 URLs will access DAO method.
Last 4 URLs (5,6,7,8) will not access DAO method and
will provide response from cache.
Sample output looks like







28 April 2018

LinkedList with Side nodes


LinkedList with side nodes



class SidelyLinkedList  {
    static Node head;
    static class Node {
        int item;
        Node next;
        Node side;
        Node(int item) {
            this.item =item;
            next = null;
            side = null;
        }
    }
    public static void main(String[] args) {
        SidelyLinkedList list = new SidelyLinkedList();
        list.head = new Node(51);
        list.head.next = new Node(10);
        list.head.next.next = new Node(15);
        list.head.next.next.next = new Node(18);
        list.head.next.next.next.next= new Node(21);
        list.head.side = new Node(34);
        list.head.side.side = new Node(48);
        list.head.next.side = new Node(23);
        list.head.next.side.side = new Node(67);
        list.head.next.next.side = new Node(12);
        list.head.next.next.side.side = new Node(89);
        list.head.next.next.next.side = new Node(67);
        list.head.next.next.next.side.side = new Node(92);
        list.head.next.next.next.next.side = new Node(56);
        list.head.next.next.next.next.side.side = new Node(97);
        Node res1 = list.singleList(head);
        list.printSidelyLinkedList(res1);
       }

    private Node singleList(Node node) {
        if(node.next==null){
            return node;
        }
        else{
            Node temp = node;
            Node temp1= node.next;
            while(temp.side!= null){
                temp= temp.side;
            }
            temp.side= temp1;
            node.next=temp1.next;
            return singleList(node);
        }
    }

    private void printSidelyLinkedList(Node head) {
        if(head==null){
            return;
        }
        else            {
            System.out.println(head.item +"->");
                printSidelyLinkedList(head.side);
        }
    }


}

Output:
51->
34->
48->
10->
23->
67->
15->
12->
89->
18->
67->
92->
21->
56->
97->




03 March 2018

Spring Boot Application

Spring boot framework:

1.Helps to build applications rapidly by removing the need to configure boiler plate configuration code.

2.Though it has no additional features to add to spring framework, It helps to build production
 ready applications quickly.

3.It provides necessary endpoints out of the box to check metrics, health check with spring boot actuator module.

4.Embedded servers(tomcat,jetty) and embedded databases can be added to build the application
without looking into the database configuration details.

We can build a simple HelloWorld Spring MVC application with Spring Boot in 2 minutes.

Project structure:  It does not need web.xml. Spring boot will take care of these configurations.

spring boot
Add caption


pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0"         
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>java9pro</groupId>
    <artifactId>java9pro.springboot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>


</project>

LoginController:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class LoginController {


        @RequestMapping("/")
        @ResponseBody        String home() {
            return "Hello World!";
        }

        public static void main(String[] args) throws Exception {
            SpringApplication.run(LoginController.class, args);
        }
    }

It has annotation @EnableAutoConfiguration, which will load the required jar dependencies.It will
initialize the application context, registers the dispatcher servlet, registers the beans for JMX.

After running the main method of LoginController, Application will start on the embedded tomcat on default port 8080.

Output can be viewed on this URL.

http://localhost:8080

server port can be changed by adding configuration to application.properties file in resources.

server.port = 8090.

Then server starts on port 8090 and URL http://localhost:8090 will give the result.







25 February 2018

HTTP Vs HTTPS

HTTP is short form for Hyper Text Transfer  Protocol. It is used for communication between website and user(browser). Information going to and from the server is plain text.

HTTPS is nothing but the (S)Secured HTTP protocol. Information going to and from the server is encrypted.

How this security is assured:
How to convert a website to use https:

SSL certificate does this job.SSL is short form for Secure Socket  Layer.
One need to buy a SSL certificate from certified authorities(CA) and it need to be installed in host.
All popular browsers recognize the certificates from CAs.

How HTTPS works with SSL certificate:

SSL is the protocol used to make the communication secure by encrypting the messages between website and user.
It uses asymmetric keys to secure the transport between browser and server.
It uses asymmetric and symmetric encryption techniques to encrypt the messages between sender and receiver.
Server uses private key to decrypt the message.Public key is shared across all the clients.
Server sends SSL certificate certified by trusted authorities.It includes public key information.
Client(browser) generates a key(client key) and encrypts the message with it and encrypt the message again with it public key.
Server receive the message and decrypt it with its private key.
Now the communication happens with the symmetric key generated by client and it is valid for that session. For every new session,client generates new symmetric key.

How asymmetric key works:

Message will by multiplied by certain number(public key) and the inverse of the same can be used as  private key.
Example:
If a message has been multiplied by it self 3 times, 0.33(1/3) will be private key and 3 is the public key.
Sender -M--->M*M*M--->M*M*M--->M3(1/3)-->M- Receiver.
Popular asymmetric encryption algorithms use different number with log functions to generate symmetric and asymmetric keys.
Examples:
RSA


11 November 2017

Java 9 Modules

What is a Java Module:

Java 9 has introduced modules.Module is nothing but a set of packages.
A new java file module-info.java in every module tells the following
1.Required packages for a modules
2.Exported packages from module.
Tools can generate this file, when we create a java modular application.

So the current access specifier of class "public" can have 3 definitions based on module-info.java.

Public class in a package
1.Can't be accessed outside the module if it is not exported.
Thus JDK encapsulates internal APIs.
2.Can be accessed outside the module if it is exported.
3.Can be accessed to some modules outside the module and can't be accessed by some modules outside the module.

Why we need --What are the advantages:

1.All the public classes can't be accessed outside the module,if module-info.java defined to
not to be accessed.Public classes of JDK internal APIs can't be accessed outside.So provides security improvement.

2.Java9 JDK has removed rt.jar and introduced 95 smaller modules.User can import the required module.Since there is no need to add big jars like rt.jar,which was essential to add java runtime libraries,the application size will be small

3.It will restrict to not to write packages with same name in two modules.
It will throw runtimeexception.So no split packages

Example:

“java.base” module is the base module.
module-info.java for java.base
module java.base {
    exports java.io;
    exports java.lang;
    exports java.math;
    exports java.net;
}
Every module requires java.base module.New folder in JDK jmods folder has all the modules and it looks like





04 November 2017

Spring security application with password hashing

Spring security framework provides solutions for developing applications with authorization and authentication.We use password encoder in with this example.

To build Spring MVC based web application,which uses Spring Security framework for login,
We need
1.JDK
2.Apache Maven
3.Intellij/Eclipse(Editor tool)
4.Apache Tomcat

We have developed a sample Spring MVC application in this link.
Project structure look like



DelegatingFilterProxy is an impelmentation of the javax.servlet.Servlet filters can intercept requests before reaching servlet.
We have to configure this DelegatingFilterProxy in web.xml,it acts as filter.
We have to define a spring spring-security.xml  in context param.
web.xml :

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee"                  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                   
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/java9pro-springmvc-servlet.xml
        /WEB-INF/java9pro-security.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
    </listener>
    <servlet>
        <servlet-name>java9pro-springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>java9pro-springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


</web-app>

We have to define a  spring-security.xml .Spring security framework provides BCryptPasswordEncoder to hash the passwords.
So the hashed password for java9pro is  $2a$10$p.r1COYmT0kl8iU3Eq56EeCm1.QdcwIRozzkJ5GVOLxAGICAxCLIy.
Same has been provided as password for user java9pro.
Following util class can be used to generate the hashed password.

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class Utils {
    public static void main(String[] args) {
            String password = "java9pro";
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
         System.out.println(passwordEncoder.encode(password));

        }
}

http configuration is used to intercept the url access along with the role.
authentication manager configuration consists of  user service configuration to fetch the user credentials to authenticate the application.
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"       xmlns="http://www.springframework.org/schema/security"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd       http://www.springframework.org/schema/security       http://www.springframework.org/schema/security/spring-security-3.2.xsd ">

    <http auto-config="true">
        <intercept-url pattern="/login" access="ROLE_USER" />
    </http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder ref="passwordEncoder"/>
            <user-service>
                <user name="java9pro" 
password="$2a$10$p.r1COYmT0kl8iU3Eq56EeCm1.QdcwIRozzkJ5GVOLxAGICAxCLIy"
 authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
    <beans:bean id="passwordEncoder" 
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

</beans:beans>

 pom.xml:

Add  below jars
spring-security-core
spring-security-config
spring-security-web

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"        
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>java9pro.springmvc</groupId>
    <artifactId>java9pro.springmvc.arti</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <finalName>springJava9ProMVC</finalName>
    </build>

    <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>

    </dependencies>


</project>

Controller Class Java9ProController looks like
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controllerpublic class Java9ProController {
    @RequestMapping("/login")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/")
    public String logoutPage(){

        return "logout";
    }

}

Spring MVC bean confiuration file java9pro-springmvc-servlet.xml



<beans xmlns="http://www.springframework.org/schema/beans"       
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       
xmlns:context="http://www.springframework.org/schema/context"      
 xmlns:mvc="http://www.springframework.org/schema/mvc"       
xsi:schemaLocation="http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc.xsd      
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd      
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd ">

    <context:component-scan base-package="com.becomeJavaPro.springmvc"/>
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>


Spring Security will automatically create a login URL at /spring_security_login


When Username as java9pro and Password as java9pro


When bad credentials