Monday, April 2, 2018

adt



<?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>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

--------------------------------
@RestController
@RequestMapping("/api")
public class StudentController {
/**
* Injecting {@link StudentService} as a dependence
*/
@Autowired
private final StudentService studentService;
public StudentController (final StudentService studentService) {
this.studentService = studentService;
}
@PostMapping(path = "/student", produces = "application/json", consumes = "application/json")
@ResponseBody
public Student createStudent (@Valid @RequestBody final Student student) {
return this.createStudent(student);
}
@GetMapping("/student/{id}")
@ResponseBody
public Optional<Student> getStudentById (@PathVariable final Long id) {
this.validateStudent(id);
return this.studentService.findStudentById(id);
} 
@GetMapping(path = "/students")
@ResponseBody
public Iterable<Student> getAllStudents () {
return this.studentService.findAllStudents();
}
private void validateStudent (final Long id) {
this.studentService.findStudentById(id).orElseThrow(() -> new StudentNotFoundException(id));
}
}
---------------

@Service
public interface StudentService {

/**
* Create new student recode
* 
* @param student
*            {@link Student}
* @return {@link Student}
*/
public abstract Student createStudent(final Student student);
/**
* 
* @param id: Student id
* @return
*/
public abstract Optional<Student> findStudentById (final Long id); 
/**
* 
* @return
*/

public abstract Iterable<Student> findAllStudents ();

-----------------
/**
 * Persistence helper for student {@link Student}  
 * @author Isuru
 *
 */
public interface StudentRepository extends CrudRepository<Student, Long> {
/**
* 
* @param name {@link String} Student name 
* @return 
*/
public Optional<Student> findByName (final String name);
/**
* 
*/
public Optional<Student> findById (final Long id);
/**
* 
* @param name
* @return
*/
@Query("select count(e) > 0 from student e where e.name = :name")
public boolean exsitsByName (@Param("name") final String name);
}
---------------
@ResponseStatus(HttpStatus.NOT_FOUND)
public class StudentNotFoundException  extends RuntimeException {
public StudentNotFoundException (final Long id) {
super("Student " + id + "is not found.");
}
}


----------------
@ResponseStatus(HttpStatus.CONFLICT)
public class DuplicateStudentException extends RuntimeException {
public DuplicateStudentException(final String name) {
super("Student "+ name + " already exsit");
}
}
-------------------
#spring properties 
spring.application.name=api-test-service

#server properties 
server.port=8081

------------------
/**

 * Student data holder
 * 
 * @author Isuru
 *
 */
@Entity
@Table(name = "student")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createAt", "modifiedAt" }, allowGetters = true)
public class Student implements Serializable {

private static final long serialVersionUID = 1993218211842842078L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@NotBlank
private String name;

@NotBlank
private String address;

@Column(nullable = false, updatable = false)
@Temporal(TemporalType.DATE)
@CreatedDate
private Date createAt;

@Column(nullable = false, updatable = true)
@Temporal(TemporalType.DATE)
@LastModifiedDate
private Date modifiedAt;


----------------
@SpringBootApplication

@EnableJpaAuditing
public class ApiTestApplication {

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

-----------------



Wednesday, July 15, 2015

Java Collection Framework - Internal walk through -2

TreeMap
TreeMap is store key value pairs like HashMap. But it is sorted by key (ascending order) or by Comparator provided at the map creation time and it design to work as a red-black tree.
Red-black tree
   Red-black tree is a binary search tree with fallowing rules
·        Every node either red or black
·        Every null nodes consider as a black node
·        If node is red both child nodes are black
·        Every path from node to leaf contains the same number of black nodes                        

        

  Eg-:  (12,4,5,8,12,45,0,25,7,89,100,-7,2,20, 25.5)
Check with your own data set


In the TreeMap key objects should implement java.lang.comparable interface then override compareTo method for implied the “Natural Ordering”. TreeMap decides wether the key is smaller than or greater than to others. If comparable is not implemented, need to supply an implementation of java.util.comparator that would do comparing outside the key class itself .TreeMap internally maintains Lists of Entry class nodes which actually implemented the java.util.map.entry interface.


Set
Is unique collection of objects .There have three implementation of the Set, called HashSet, TreeSet and LinkedHashSet

HashSet
Its unordered set. Internally it use HashMap.Inside of HashSet class have class variable call ‘map’ which is an instance of the HashMap .when we adding values to the HashSet using add(element) internally it add values to ‘map’ by calling put(key,value) .use that element passing through the add method as a key and use dummy object as value for all elements

Object value=new Object();

HashMap internally check the uniqueness of the Key objects using equal method

TreeSet
TreeSet is sorted and internally using TreeMap.(functioning same like HashSet )   

LinkedHashSet
LinkedHashSet is ordered set which extends the HashSet.It uses Doubly Linked List for hold the order.



Monday, July 13, 2015

Java Collection Framework - Internal walk through -1


                                                      In this tutorial I’m going to discuss about Java Collection Framework in a different way.Which means I’m going to discuss how the component works in this framework.Main forces of this tutorial is knowing which collection class suitable for which situation.
So.., let’s begin

Basic interfaces in Collection framework
Set: - collection of unique element
List: - collection of elements (might have duplicates)
Map: - collection of key, value pairs
Queue:-ordered collection of elements 

Concrete classes in collection framework
Maps : HashMap,HashTable,TreeMap
Sets   : HashSet,LinkHashSet,TreeSet
Lists  : ArrayList,Vector,LinkedList
Queues : PriorityQueue
Utilities : Collections,Arrays

List
List maintain the order which they are added.

ArrayList

                                                           ArrayList based on the principle of creating array and add data in to that.In ArrayList class has member variable call Object[] elementData.When we crerating new arraylist like this ,

List l=new ArrayList();

                                                           elementData array should initialize with size 10 . Using add(Element e) we can add one by one element to the ArrayList , After all the 10 locations are filled with elements ArrayList creating new different size(size>10) of array and coping old array to new one using Array.copyOf . That “different size” depend on the algorithm below.

    newSize=((oldSize*3)/2)+1;

                                                         On adding a element at a particular index in ArrayList using add(index i,Element e), ArrayList checks if a element is already present at that index. If no than the element passed in add() is added at that index, otherwise a new array is created with the index kept vacant and the remaining element shifted to right.
So, ArrayList is most suitable for frequently fetching and one time adding scenarios 

LinkList
                                                       Actulally the LinkList not using any primitives like arrays, etc. . . . It’s a collection object linked together using reference (Doubly Link List).
 LinkList has Entry class member variable called header. It’s the start element of LinkList.
                                                       Every time we calling add(element) new instance of Entry class created and attached it end of the list.
                                                      Calling add(element,position) means add a new element to specific position of the list.to do that operation shift the current element of that position and subsequent elements to the right add the new element to current position.
                                                      Invoking get(position) is more time consuming than ArryList  , because need to travers from the start node every time.
So, LinkLst is suitable for frequently adding and removing, not suitable for frequently fetching

Map
                                                     Map is special collection in collection framework which can frequently add and fetch easily. It’s not just adding elements to the list, Map allow you to add element as a key and other as a value.
 HashMap

                                                       HashMap is an implementation of the Map interface. It’s completely based on hashing principle. It store the values in form of key,vaule  pair. Use key to access to value.to get the efficient use of HashMap need to override the equal() and hashcode() methods in key element. equal()  method helps to compare the content of two object(not the memory location) and hashcode() return unique identifier to each object it helps to arranged the HashMap elements to separate buckets.So the elements in same hashcode put together in to a same bucket. Beacuse it’s support to when fetching elements using get(key) . First it identify the hash bucket then after uses equal() method to identify the actual object present in the bucket.
For the frequent access to the value HashMap using “Singly Linked List” .Number of buckets are depends on number of different hashcodes .To hold the set of buckets together use a array with initial size 12.Size will be change when different hashcode added.

newSize=oldSize*(3/2)

Wednesday, July 1, 2015

Java 8 | Lambda Expressions


What is lambda expression for?


It is another way of writing instances of anonymous classes

If we have more than one line of code, use lambda expression in this way

If we have more than one argument, use lambda expression in this way


 What is the type of Lambda expression?

It’s a functional interface (the interface contain only one abstract method)
A Lambda can be taken as a method parameter, and can be returned by a method 
Lambda expression is “not an obect” because we can’t call any method in object class like hashCode(),toString() , but the exact answer is an object without identity 



Java 8 | Default methods for interface


Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the default keyword. This feature is also known as Extension Methods.

interface Formula {
    double calculate(int a);

    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}
Formula formula = new Formula() {
    @Override
    public double calculate(int a) {
        return sqrt(a * 100);
    }
};

formula.calculate(100);     // 100.0
formula.sqrt(16);           // 4.0

}

Session Tracking / Cookies



                    HTTP is “stateless” protocol, because of that it’s doesn’t keep any track record of previous client request there for every request client opens a new connection to the web server. But for identify the clients we have to use HTTP sessions.

Create HTTP Session

protected void doPost(HttpServletRequest request,
           HttpServletResponse response)
               throws ServletException, IOException {

           HttpSession session = request.getSession ();

       }

Store the values in Session Object

session.setAttribute("useridKey", "userIdvalue");

Read the session value

String userName = (String) session.getAttribute("useridKey");

***Values of session objects are stored in a servlet container memory

Sessions in Cluster

If web application runs on cluster (2 or more nodes), keep it mind the session will be create in only one server memory. For this problem have few solutions and also they have their own draw backs as well.

  1.   Save the session data in a DB. (Cause huge performance decrease)
  2.   Instructed to load balancer to use sticky sessions, for the particular session all the interaction will happen with the same physical server, even though other servers are present. (if that server goes down?, session will be lost L L)
  3. Sync up the session, session get replicated in all other nodes in the cluster.(additional overhead for sync up) 

HTTP Cookies

                      HTTP cookies are small files (size<4KB; according to http protocol) that create by web browser. Web server can only access cookies which are set to their own domain. There is limited numbers of cookies for one domain. This number may differ per browser. You can refer additional from here http://browsercookielimits.squawky.net but general limit is 20 per domain and total 300 maximum cookies can have for one client’s hard drive. Again it’s differ based on the browser. When exceed the limit of cookies older cookies delete before create the new one.

                    Cookies have an expiration date. This date is set so the browser can delete old cookies when they are no longer in use. If the date is not set cookies will be delete when the browser is closed.

Snippet part of the http response
Set-Cookie: Name=content data; expires=Sun, 31-June-2015 23:59:59 GMT; path=/; domain=.example.net     

Set-Cookie: let browser know server like to create cookie in the client hard drive
Name: name of of the cookie (eg-: userId=content data)
content data: the data which can be store in the cookie(eg:-userId=003)
expires: expire date of cookie
path: the path of the domain to which the cookie is sent. This means that, if the     path is set to '/login/,' and the domain is set to 'mysite.com,' the cookie will only be sent to the server if the browser requests a file from 'mysite.com/login/'. If the path is set to '/', the cookie will be sent to the server regardless of the location of the requested file on the server.


Write Cookie and add it to an HttpServletResponse

Cookie cookie = new Cookie("myCookie", "myCookieValue");
response.addCookie(cookie);
Read the cookies
Cookie[] cookies = request.getCookies();
** getCookies() may return null


Set cookie expire

Cookie cookie = new Cookie("myCookie", "myCookieValue");
cookie.setMaxAge(24 * 60 * 60); // 24 hr
response.addCookie(cookie);

Remove cookies

Cookie cookie = new Cookie("myCookie", "myCookieValue");
cookie.setMaxAge(0);
response.addCookie(cookie);