Tuesday, March 27, 2018

pring Boot Basic Course 04-2- Lazy and Eager

Lazy -Run Few queries
Eager -Run Many queries

Spring Boot Basic Course 04- One to many RelationShip

Consider scenario user has many address. 

Address class

ackage com.sb.basic.model;


import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
public class Address extends AbstractPersistable<Long>{
 
 private String city;
 private String state;
 private String country;
 //We will create one transition for userId
 private transient Long userId;
 
 @ManyToOne(targetEntity = User.class)
 @JoinColumn(name="user_id") //user_id is table column name
 private User user;
 
 //Getter Setter

Update User class

private String userId;
private String userName;
private String password;
 
 
@OneToMany(targetEntity = Address.class, mappedBy = "user",fetch= FetchType.LAZY ,cascade =CascadeType.ALL)
private Set<Address> address; //Instead of Set(Unordered collection and not allow duplicates) we can use list(ordered and allow duplicate values) as well

Getter and setter;


Create AddressController class

This like normal UserController class
@RequestMapping("/addressList")
 public List<Address> addressList(){
  return addressService.addressList();
 }


Create AddressServiceImpl class

This also like UserSImpl class
@Override
 public List<Address> addressList() {
  return addressRepository.findAll();
 }


Add data to the generated address table.

Then run project

      Method - Get
      Link      - http://localhost:9080/springbootbasic/address/addressList



Priyantha.samaraweera

Monday, March 26, 2018

Spring Boot Basic Course 03- Implement crud operation

Only change UserService interface,  UserServiceImpl class, and UserController class

UserService interface


package com.sb.basic.service;

import java.util.List;
import java.util.Optional;

import com.sb.basic.model.User;

public interface UserService {
	
	List<User> userList();
	
	Optional<User> findOne(Long id);
	
	User addUser(User user);
	
	String deleteUser(Long id);
}


UserServiceImpl class


package com.sb.basic.service.impl;

import java.util.List;
import java.util.Optional;

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

import com.sb.basic.model.User;
import com.sb.basic.repository.UserRepository;
import com.sb.basic.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	private UserRepository userRepository;
	
	//Better go with constructor injection so no need to put @Autwired again and again
	
	@Autowired
	public UserServiceImpl(UserRepository userRepository) {
		this.userRepository = userRepository;
	}
	
	@Override
	public List<User> userList() {
		return userRepository.findAll();
	}
	
	@Override
	public Optional<User> findOne(Long id) {
		return userRepository.findById(id);
	}

	@Override
	public User addUser(User user) {
		return userRepository.save(user);
	}

	@Override
	public String deleteUser(Long id) {
		userRepository.deleteById(id);;
		return "{'message':'User Deleted'}";
	}

	
}



Create UserController class


package com.sb.basic.coontroller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sb.basic.model.User;
import com.sb.basic.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
	
	private UserService userService;
	
	@Autowired
	public UserController(UserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping("/list")
	public List<User> userList(){
		return userService.userList();
	}
	
	@RequestMapping("/id/{id}")	
	public Optional<User> findOne(@PathVariable Long id){
		return userService.findOne(id);
	}
	
	@RequestMapping("/add")
	public User addUser(@RequestBody User user){
		return userService.addUser(user);
	}
	
	@RequestMapping("/delete/{id}")
	public String deleteUser(@PathVariable Long id){
		return userService.deleteUser(id);
	}

}





Check URL



01. User List - 
      Method - Get
      Link      - http://localhost:9080/springbootbasic/user/list


02. Delete User - 
      Method - Get

      Linkhttp://localhost:9080/springbootbasic/user/delete/3             

03. Find User By Id - 
      Method - Get

      Link  - http://localhost:9080/springbootbasic/user/id/1


04. Add User - 
      Method - Post

      Link      - http://localhost:9080/springbootbasic/user/add
         {
   "userId":"167",
           "userName":"Perera",
           "password":"dser"
         }

04.1 User Update

      Now we don't need to update method. We can use add          method. Request body must identified with id.

      Method -Post
      Link-http://localhost:9080/springbootbasic/user/add
      {
           "id","3"
   "userId":"167",
           "userName":"Perera",
           "password":"dser"

         }

Priyantha.samaraweera

Sunday, March 25, 2018

Spring Boot Basic Course 02- Integrated with spring data

Add JPA and MySQL configuration 

No, hibernate related XML. Add some properties in application.properties  file


#Hibernate
spring.datasource.url= jdbc:mysql://localhost:3306/springboot
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username= root
spring.datasource.password= root

#JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect


Also add bellow dependencies 


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.6</version>
</dependency>

Create User Class

We extends AbstractPersistable class. Then we don't need 
Primary key (It's automatically genarated)
Field-based  annotation(@Column)

package com.sb.test.model;

import javax.persistence.Entity;

import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
public class User extends AbstractPersistable<Long>{
 //Don't need to primary key and column annotation.
 
 private String userId;
 private String userName;
 private String password;
 
 
 public String getUserId() {
  return userId;
 }
 public void setUserId(String userId) {
  this.userId = userId;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 
}

Create database springboot. Then run code
Automatically generate the table for the users. Column name separated by an underscore.


Create sql file to insert the data.
Under resource folder.
     Not Yet




Create UserController class


package com.sb.test.model;

package com.sb.basic.coontroller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sb.basic.model.User;
import com.sb.basic.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
 
 private UserService userService;
 
 @Autowired
 public UserController(UserService userService) {
  this.userService = userService;
 }
 
 @RequestMapping("/list")
 public List<User> userList(){
  return userService.userList();
 }

}


Create UserService Interface


package com.sb.basic.service;

import java.util.List;

import com.sb.basic.model.User;

public interface UserService {
 
 List<User> userList();

}


Create UserServiceImple class



package com.sb.basic.service.impl;

import java.util.List;

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

import com.sb.basic.model.User;
import com.sb.basic.repository.UserRepository;
import com.sb.basic.service.UserService;

@Service
public class UserServiceImpl implements UserService {
 
 private UserRepository userRepository;
 
 //Better go with constructor injection so no need to put @Autwired again and again
 
 @Autowired
 public UserServiceImpl(UserRepository userRepository) {
  this.userRepository = userRepository;
 }
 
 @Override
 public List<User> userList() {
  return userRepository.findAll();
 }

}




Create UserRepository Interface


package com.sb.basic.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.sb.basic.model.User;

public interface UserRepository extends JpaRepository<User, Long>{

}






Create UserController class


package com.sb.basic.service.impl;

import java.util.List;

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

import com.sb.basic.model.User;
import com.sb.basic.repository.UserRepository;
import com.sb.basic.service.UserService;

@Service
public class UserServiceImpl implements UserService {
 
 private UserRepository userRepository;
 
 //Better go with constructor injection so no need to put @Autwired again and again
 
 @Autowired
 public UserServiceImpl(UserRepository userRepository) {
  this.userRepository = userRepository;
 }
 
 @Override
 public List<User> userList() {
  return userRepository.findAll();
 }

}





Create UserController class

package com.sb.basic.service.impl;

import java.util.List;

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

import com.sb.basic.model.User;
import com.sb.basic.repository.UserRepository;
import com.sb.basic.service.UserService;

@Service
public class UserServiceImpl implements UserService {
 
 private UserRepository userRepository;
 
 //Better go with constructor injection so no need to put @Autwired again and again
 
 @Autowired
 public UserServiceImpl(UserRepository userRepository) {
  this.userRepository = userRepository;
 }
 
 @Override
 public List<User> userList() {
  return userRepository.findAll();
 }

}





File Structure


















Now Run Application.


Open ARC or Postman

URL - http://localhost:9080/springbootbasic/user/list
method -get

If you have data in the database then you can retrieve the data



Thursday, March 22, 2018

Json Interview Question



01. Cannot be dublicate keys

        {"foo":"bar","foo":"baz"}

https://career.guru99.com/top-19-json-interview-questions/

Spring Boot Basic Course 01 - Web Introduction

01.Basic Structure
Ctrl+Shift+T
package - com..sbbasiccourse

02.How to Change Port and contextPath

application.properties

server.port = 9090
server.context-path = /springboot
Now URL : localhost:9090/springboot

03.Devtools Dependencies for auto restart server
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
</dependency>


04.Add to Controller
package com.sbbasiccourse.controller;



@RestController
public class WelcomeController {
@RequestMapping(name="/")
public String index(){
return "Spring Boot Basic Course";
}
}
Now run and call URL - localhost:9090/springboot


05.Default API calling


<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

And you have to add application.properties 
management.security.enabled=false

06.Default API calling

How to convert json object to java classes - 02 (Advanced Option)


I'm Tring to using bellow json String 
(Ref - json.org )


{
 "glossary": {
  "title": "example glossary",

  "GlossDiv": {

   "title": "S",
   "topic": "SsS",

   "GlossList": {

    "GlossEntry": {

     "ID": "SGML",
     "SortAs": "SGML",
     "GlossTerm": "Standard Generalized Markup Language",
     "Acronym": "SGML",
     "Abbrev": "ISO 8879:1986",

     "GlossDef": {
      "para": "A meta-markup language, used to create markup languages such as DocBook.",
      "GlossSeeAlso": ["GML", "XML"]
     },

     "GlossSee": "markup"
    }
   }
  }
 }
}

You can validate this json String using JsontLint


Now I'm going to create relevent java classes. This is very easy when use jsonschema2pojo .

Paste above JSON String space of jsonschema2pojo space.
(Follow bellow image)




You can preview All java classes using click priview button.You can downlord it clicking zip button and classname-source.zip link.

I created Spring Boot test Project

Package Name - com.example.demo
(Because aboue jsonschema2pojo I used com.example.demo.pojo)

Now I can copy downloaded json classes to the com.example.demo package.

Follow package structure 
























Add jackson dependencies to the pom.xml file


<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
</dependency>
Create WelcomController class


package com.example.demo.pojo;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeController {
 
 @RequestMapping(value = "/jsontopojo", method = RequestMethod.POST )
 public @ResponseBody Example value(@RequestBody Example example){
  return example;
  
 }

}

Now run the project and use ARC or Postman client to request.

url - http://localhost:8080/jsontopojo
method -POST
body - Add to above json string

If You need to return some string of request json body,

package com.example.demo.pojo;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeController {
 
 @RequestMapping(value = "/jsontopojo", method = RequestMethod.POST )
 public @ResponseBody String value(@RequestBody Example example){
  return example.getGlossary().getTitle();
  
 }

}

You can see return  "example glossary".

Again Simple Example without using jsonschema2pojo site.

Follow bellow json string

{
 "car": {
  "title": "example glossary",

  "bmw": {

   "title": "S",
   "topic": "SsS"

  }
 }
}

Create  Main class


package com.example.demo.pojo;

import com.fasterxml.jackson.annotation.JsonProperty;

public class JsontoPojo {
 
 @JsonProperty("car")
 private Car car;

 public Car getCar() {
  return car;
 }

 public void setCar(Car car) {
  this.car = car;
 }
}

Create Car class


package com.example.demo.pojo;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Car {
 
 @JsonProperty("title")
 private String title;
 
 @JsonProperty("bmw")
 private BMW bmw ;
 
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public BMW getBmw() {
  return bmw;
 }
 public void setBmw(BMW bmw) {
  this.bmw = bmw;
 }
 
 

}



Create BMW class


package com.example.demo.pojo;

import com.fasterxml.jackson.annotation.JsonProperty;

public class BMW {
 
 @JsonProperty("title")
 private String title;
 
 @JsonProperty("topic")
 private String topic;
 
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getTopic() {
  return topic;
 }
 public void setTopic(String topic) {
  this.topic = topic;
 }
 
 
 

}

Create  Main class



package com.example.demo.pojo;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeController {
 
 
 @RequestMapping(value="/car" , method = RequestMethod.POST)
 public @ResponseBody JsontoPojo type(@RequestBody JsontoPojo jsontoPojo){
  return jsontoPojo;
 }

}

URL - http://localhost:8080/car


Thank You


Others

@JsonIgnoreProperties

https://dzone.com/articles/jackson-annotations-for-json-part-1-serialization

@JsonProperty



Tuesday, March 13, 2018

Recursion

public class MainClass {
  // recursive declaration of method fibonacci
  public static long fibonacci(long number) {
   
if ((number == 0) || (number == 1)) // base cases
      return number;
    else
      // recursion step
      return fibonacci(number - 1) + fibonacci(number - 2);
  }

  public static void main(String[] args) {
    for (int counter = 0; counter <= 10; counter++)
      System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
  }
}

Java ArrayList isEmpty() Method example


ArrayList<String> name = new ArrayList<String>();

if(name.isEmpty()){
   sysout("Array is Empty");
}

References -  https://beginnersbook.com/2013/12/java-arraylist-isempty-method-example/

Tuesday, March 6, 2018

What is browser cache memory


In order to speed up web browsing, web browsers are designed to download web pages and store them locally on your computer's hard drive in an area called "cache". Browser cache (also know as Internet cache) contains records of every item you have viewed or downloaded while Internet surfing. So when you visit the same page for a second time, the browser speeds up display time by loading the page locally from cache instead of downloading everything again.

How to find cache folder

1. Click the “Start” button and click on “Control Panel.”
2. Choose “Appearance and Personalization,” then click on “Folder Options.”
3. Click the “View” tab and look under “Advanced Settings.”
4. Click the “Show Hidden Files and Folders” radio button and click “OK.”
5. Click the "Start" menu button, then click "Computer." Double-click your main hard drive, then click on “Users” and open the folder with your user name.
6. Navigate to the file path “\AppData\Local\Google\Chrome\User Data\Default\Cache.” The contents of Chrome's cache appear in this folder.

Monday, March 5, 2018

Marker Interface

http://mrbool.com/what-is-marker-interface-in-java/28557

Serialization

Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.(https://www.geeksforgeeks.org/serialization-in-java/)

TALK-01

Short story about serialization
After many years of hard work, Earth's scientists developed a robot who can help them in daily work. But this robot had fewer features than the robots developed by the scientists from planet Mars.
After a meeting between both planets' scientists, it is decided that Mars will send their robots to Earth. But a problem occurred. The cost of sending 100 robots to Earth was $100 million. And it takes around 60 days of traveling.
Finally, Mar's scientists decided to share their secret with Earth's scientists. This secret was about the structure of class/robot. Earth's scientists developed the same structure on Earth itself. Mar's scientists serialized the data of each robot and sent it to earth. Earth's scientists deserialized the data and fed it into each robot accordingly.
This process saved them time in communicating a massive amount of data.
Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transient before sending their data to Earth. Note that the transient property is set to null (in case of reference) or to the default value (in case of the primitive type) when the object gets deserialized.
One more point noticed by Earth's scientists is that Mars's scientists asked them to create some static variables to keep details about the environment. These details are used by some robots. But Mars's scientists don't share these details. Because Earth's environment was different from Mars' environment.
Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.
Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything started working.
TALK-02

Serialization is usually used When the need arises to send your data over network or stored in files. By data I mean objects and not text.
Now the problem is your Network infrastructure and your Hard disk are hardware components that understand bits and bytes but not JAVA objects.
Serialization is the translation of your Java object's values/states to bytes to send it over network or save it.

This is analogous to how your voice is transmitted over PSTN telephone lines.