Thursday, 31 August 2017

Wednesday, 30 August 2017

Revision Day 2: SPRING MVC

Completed the simple mvc application.
Changed it from spring jdbctemplate to hibernate for Dao implementation.


Web.xml:-

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

       <display-name>Archetype Created Web Application</display-name>

       <welcome-file-list>
             <welcome-file>home.jsp</welcome-file>
       </welcome-file-list>

       <servlet>
             <servlet-name>spring-mvc</servlet-name>
             <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
             <load-on-startup>1</load-on-startup>
       </servlet>
       <servlet-mapping>
             <servlet-name>spring-mvc</servlet-name>
             <url-pattern>/</url-pattern>
       </servlet-mapping>

<!-- <context-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
       </context-param>

       <listener>
             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
       </listener> -->
</web-app>

Wasted lot of time in understanding how this “spring-mvc-servlet.xml” getting loaded i.e. how spring is getting initiated when I am not specifying which file to fetch nor the file path??

After so much of investigation I came to know that
<servlet-name>spring-mvc</servlet-name>
             <url-pattern>/</url-pattern>

Here server will take servlet-name as the standard file name and appends -servlet at the end like this:-
Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-servlet.xml

When you want to put your Servlet file in your custom location or with custom name, rather than the default naming convention [servletname]-servlet.xml and path under Web-INF/ ,then you can use ContextLoaderListener.

I ran simple java main class to test the application functionality by placing the spring-mvc-servlet.xml in resources folder.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import jbr.springmvc.model.Login;
import jbr.springmvc.model.User;
import jbr.springmvc.service.UserService;

public class App {
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-mvc-servlet.xml");

    UserService obj = (UserService) context.getBean("userService");
    Login login = new Login();
    login.setUsername("admin");
    login.setPassword("admin123");
    User user = obj.validateUser(login);
    System.out.println(user.toString());
  }
}

<build>
             <finalName>SpringMvcUser</finalName>
             <plugins>
                    <plugin>
                           <groupId>org.mortbay.jetty</groupId>
                           <artifactId>jetty-maven-plugin</artifactId>
                           <version>8.1.16.v20140903</version>
                           <configuration>
                                 <scanIntervalSeconds>10</scanIntervalSeconds>
                           </configuration>
                    </plugin>
             </plugins>
       </build>

Use mvn jetty:run

SPRING:-

Spring framework provides flexibility to configure beans in multiple ways such as XML, Annotations, and JavaConfig.



What is dependency injection and its types?

A technique where the instance is not directly passed but its specified how to create the instance, this helps in loose coupling and testing.

Types:-
  1.              Setter injection
  2.              Constructor injection
We prefer setter injection over constructor injection because it helps in resolving cyclic dependency.

Scenario:- If A is dependent on B and vice-versa, then we can neither create instance of A nor B because A requires instance of B passed in the constructor and B requires instance of A be passed in the constructor, This can be resolved by setter injection where the instance A is created first then we can set the B’s instance.

Tuesday, 29 August 2017

Revision Day 1


  • Revised all the algorithms That i worked on in the past couple of months while working on Princeton's algorithms course.
  • Read about Hoare’s Partition Scheme and Lomuto partition scheme on quicksort,Dijkistra's algorithm etc.
  • I am not going to spend more time on this again.
  • updated my algorithms summary article.so that i can just go through it for quick reference.

Monday, 28 August 2017

Java Notes

Java Technology

HelloWorld.java -> Java Code
HelloWorld.class -> Java ByteCode

Bytecode

Object : -An  real-world object with state and behaviour

Class:- It’s a blueprint from which objects can be created

Class can be public or default.it cannot be declared as private or protected.

Class Name consists of:- alphabets, Numbers, $,_

Inheritance

Extends

Interface – A Contract between a class and the outside world.

Implements

Package

Variables
Instance Variables (Non-Static Fields)
Class Variables (Static Fields)
Local Variables
Parameters


Literals :- Java Literals are syntactic representations of variables.

Using Underscore Characters in Numeric Literals
long creditCardNumber = 1234_5678_9012_3456L; which is equal to 1234567890123456

Array
Java.util.Arrays
Arrays.binarySearch(array,key)
Arrays.fill(array,value)
Arrays.Equals(array1,array2) 1 dimension
Arrays.deepequals(array1,array2) 2 dimension

Operators


Type Comparison Operator instanceof

Bitwise and Bit Shift Operators

<<,<<<,&,|,^

If another class cannot call a Class constructor, it cannot directly create Class objects.

Variable Argument (Varargs)

            private static int add(int... i) {
                        int sum = 0;
                        for (int k = 0; k < i.length; k++) {
                                    sum += i[k];
                        }
                        return sum;
            }

Object Creation of  a class by name myClass:-

new()
myClass.class.newInstance()
Class obj = Class.forName("myClass”);
myClass myclass = obj.getInstance();
Serialization
Clone()


compile-time constant
A constant variable of primitive type or type String that is declared final and initialized with a compile-time constant expression.

Important Nested Classes

Nested classes that are declared static are called static nested classes.
Non-static nested classes are called inner classes.
There are two special kinds of inner classes: local classes and anonymous classes.
a local class can access local variables and parameters of the enclosing block that are final or
effectively final
Shadowing
Local classes are similar to inner classes because they cannot define or declare any static members
Final and Effectively Final:-
A variable or parameter whose value is never changed after it is initialized is effectively final.

Serializable

serialize an object means to convert its state to a byte stream so that the byte stream can be
 reverted back into a copy of the object.
A Java object is serializable if its class or any of its superclasses implements either the
 java.io.Serializable interface or its subinterface, java.io.Externalizable.

Enum

All enums implicitly extend java.lang.Enum.hence they cannot be extended further.
Note: The constructor for an enum type must be package-private or private access. It automatically
creates the constants that are defined at the beginning of the enum body. You cannot invoke an
enum constructor yourself


All interfaces are inherently static
Annotation

Interfaces
abstract methods, default methods, and static methods.
All constant values defined in an interface are implicitly public, static, and final, you can omit
these modifiers.

The Java programming language supports multiple inheritance of type

Using an Interface as a Type

Overriding and Hiding Methods

covariant return type

Instance methods are preferred over interface default methods.

Static methods in interfaces are never inherited.

virtual method invocation

hiding fields
hiding methods

Methods called from constructors should generally be declared final.

Abstract Class Implements an Interface

Abstract calss can have final methods.

static import

Generics

type inference

bounded type parameters

Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no
 relationship to MyClass<B>, regardless of whether or not A and B are related. The common
parent of MyClass<A> and MyClass<B> is Object.

static import

exception

exception handling

call stack

Checked Exceptions
Errors and runtime exceptions are collectively known as unchecked exceptions

All exceptions inherit from Throwable class

If a catch block handles more than one exception type, then the catch parameter is implicitly final.

try-with-resources statement is a try statement that declares one or more resources.
Any object that implements java.lang.AutoCloseable, which includes all objects which implement
 java.io.Closeable, can be used as a resource.

suppressed exceptions

runtime exception  occurs when a method tries to access a member of an object through a null
reference

StackTraceElement

File IO

java.io vs java.nio

Io Streams

Array based memory

byte streams

InputStream and OutputStream are superclasses

FileInputStream and FileOutputStream are descendends of above two classes.Used for byte reading

FileReader and FileWriter same as above used for character’s reading.

BufferedReader and PrintWriter used in Line-Oriented I/O


Buffered Streams


There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and
BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter
create buffered character streams.


flushing the buffer.

Datastreams

objectStreams


FileVisitor to walkthrough file tree

Type Erasure and Bridge Methods
       
Restrictions on generics

 ACID (Atomicity, Consistency, Isolation, Durability)

Tuesday, 22 August 2017

DFS and BFS

package vikram.HR;
// Java program to print DFS traversal from a given given graph

import java.util.*;
import java.util.LinkedList;

// This class represents a directed graph using adjacency list
// representation
public class DFSBFS {
    private int V;   // No. of vertices

    // Array  of lists for Adjacency List Representation
    private java.util.LinkedList<Integer> adj[];

    // Constructor
    public DFSBFS(int v) {
        V = v;
        adj = new java.util.LinkedList[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new java.util.LinkedList();
    }

    //Function to add an edge into the graph
    void addEdge(int v, int w) {

        adj[v].add(w);  // Add w to v's list.
    }

    // A function used by DFS
    void DFSUtil(int v, boolean visited[]) {
        // Mark the current node as visited and print it
        visited[v] = true;
        System.out.print(v + " ");

        // Recur for all the vertices adjacent to this vertex
        Iterator<Integer> i = adj[v].listIterator();
        while (i.hasNext()) {
            int n = i.next();
            if (!visited[n])
                DFSUtil(n, visited);
        }
    }

    // The function to do DFS traversal. It uses recursive DFSUtil()
    void DFS(int v) {
        // Mark all the vertices as not visited(set as
        // false by default in java)
        boolean visited[] = new boolean[V];

        // Call the recursive helper function to print DFS traversal
        DFSUtil(v, visited);
    }

    // prints BFS traversal from a given source s
    void BFS(int s) {
        // Mark all the vertices as not visited(By default
        // set as false)
        boolean visited[] = new boolean[V];

        // Create a queue for BFS
       java.util.LinkedList<Integer> queue = new LinkedList<Integer>();

        // Mark the current node as visited and enqueue it
        visited[s] = true;
        queue.add(s);

        while (queue.size() != 0) {
            // Dequeue a vertex from queue and print it
            s = queue.poll();
            System.out.print(s + " ");
            // Get all adjacent vertices of the dequeued vertex s
            // If a adjacent has not been visited, then mark it
            // visited and enqueue it
            Iterator<Integer> i = adj[s].listIterator();
            while (i.hasNext()) {
                int n = i.next();
                if (!visited[n]) {
                    visited[n] = true;
                    queue.add(n);
                }
            }
        }
    }

    public static void main(String args[]) {
        DFSBFS g = new DFSBFS(4);

        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 2);
        g.addEdge(2, 0);
        g.addEdge(2, 3);
        g.addEdge(3, 3);

        System.out.println("Following is Depth First Traversal " +
                "(starting from vertex 2)");
        System.out.println("BFS:-");
        g.BFS(2);
        System.out.println("\nDFS:-");
        g.DFS(2);
    }
}
// This code is contributed by Aakash Hasija

Saturday, 12 August 2017

Completed - CTCI 20 Days Challange

Completed the Challenge in 18 days(25th July-12th Aug).

Digest:-

  • Most of the problems were easier than I thought.
  • Learnt implementation of algorithms like tries,heaps,BFS and DFS.
  • Gained lot of confidence on my algorithmic knowledge.
  • Learnt discipline and working in time bound environment.
  • On paper working helped me a lot,need to practice further on that.
  • Few backlogs are left out,need to cover them ASAP.  note:- Completed all problems on 22/8/17
  • Uploaded all the solutions on Github at link:-  Github link


CTCI Challange, DAY 20

Day 20

Problem Statement:-Bit Manipulation: Lonely Integer

Studied the Bit manipulation.
Solution:-

   public static int lonelyInteger(int[] a) {
        int value = 0;
        for (int i : a)
            value ^= i;
        return value;
    }

Installing Docker and Minikube

  install docker-   sudo apt install docker.io   set user to docker group:- sudo gpasswd -a   {user} docker   imp commands:- ...