Saturday, February 25, 2017

Spring Boot @ConfigurationProperties


application.yml
prefix:
    stringProp1: propValue1
    stringProp2: propValue2
    intProp1: 10
    listProp:
        - listValue1
        - listValue2
    mapProp:
        key1: mapValue1
        key2: mapValue2


application.properties
prefix.stringProp1=propValue1
prefix.stringProp2=propValue2
prefix.intProp1=10
prefix.listProp[0]=listValue1
prefix.listProp[1]=listValue2
prefix.mapProp.key1=mapValue1
prefix.mapProp.key2=mapValue2

public class SamplePropertyLoadingTest {
    @Value("${prefix.stringProp1}")
    private String stringProp1;

@ConfigurationProperties(prefix = "prefix")
@Component
public class SampleProperty {
    private String stringProp1;
    private String stringProp2;
    @Max(99)
    @Min(0)
    private Integer intProp1;
    private List listProp;
    private Map mapProp;
    ...
}


Spring Advice Annotation Examples

package beans.annotation;

import org.springframework.stereotype.Component;

@Component
public class Arithmatic {

public int add(int a, int b){
return a+b;
}

public int sub(int a, int b){
return a-b;
}

public int mul(int a, int b){
return a*b;
}

public int div(int a, int b){
return a/b;
}
}

package beans.annotation;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component("cours")
public class Course {

@Value(value = "100")
private int courseId;

private String courseName;

public int getCourseId() {
return courseId;
}

public void setCourseId(int courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return courseName;
}
   
@Value(value = "JAVA")
@Required
public void setCourseName(String courseName) {
this.courseName = courseName;
}

@Override
public String toString() {
return "Course [courseId=" + courseId + ", courseName=" + courseName + "]";
}
}

package beans.annotation;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyAdvice {
@Before("execution(public * *(..))")
//@AfterReturning("execution(public * *(..))")
//@AfterThrowing("execution(public * *(..))")
public void sayHello(){
System.out.println("MyAdvice sayHello method is invoked");
}
}


package beans.annotation;

import javax.inject.Qualifier;

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

@Service
public class Student {

private int studentNo;
private String studentName;
   
@Autowired
private Course course;
public Student() {
super();
System.out.println("Default constructor called");
}

@Autowired
public Student(@Value(value = "001") int studentNo, @Value(value = "Bala") String studentName) {
super();
this.studentNo = studentNo;
this.studentName = studentName;
System.out.println("2-arg constructor called");
}
public int getStudentNo() {
return studentNo;
}
//@Value(value = "002")
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public String getStudentName() {
return studentName;
}
//@Value(value="Balaji")
public void setStudentName(String studentName) {
this.studentName = studentName;
}

public Course getCourse() {
return course;
}

public void setCourse(Course course) {
this.course = course;
}

@Override
public String toString() {
return "Student [studentNo=" + studentNo + ", studentName=" + studentName + ", course=" + course + "]";
}
}



Spring Core Examples

package main;

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

import beans.annotation.Student;

public class MainApplication {

public static void main(String[] args) {
AbstractApplicationContext  ac = new ClassPathXmlApplicationContext("config/hello.xml");
 
//setEmployeeName example

/* Employee emp = (Employee)ac.getBean("employeeProp");
System.out.println(emp);
emp.setEmpId(emp.getEmpId()+50);

Employee employeeProp1 = (Employee)ac.getBean("employeeProp");
System.out.println(employeeProp1);

Employee empCons = (Employee)ac.getBean("employeeCons");
System.out.println(empCons);

Employee empCons1 = (Employee)ac.getBean("employeeCons1");
System.out.println(empCons1);

//Constructor injection use index attribute to avoid constructor args ambiguity
Employee empCons2 = (Employee)ac.getBean("employeeCons2");
System.out.println(empCons2);


//Constructor injection use type attribute to avoid constructor args ambiguity
Employee empCons3 = (Employee)ac.getBean("employeeCons3");
System.out.println(empCons3);
Employee empCons4 = (Employee)ac.getBean("employeeCons4");
System.out.println(empCons4);
*/

/* //Singleton Scope Singleton design pattern .. return the same singleton object on every getBean call
Employee empCons5 = (Employee)ac.getBean("employeeCons5");
System.out.println(empCons5);
Employee empCons5_1 = (Employee)ac.getBean("employeeCons5");
System.out.println(empCons5_1);*/

/* //lazy init to avoid eager loading .. spring container creating beans
Employee empCons6 = (Employee)ac.getBean("employeeCons6");
System.out.println(empCons6);*/


/* //Prototype Scope Singleton design pattern // create new object and return on every getBean call
Employee empCons7 = (Employee)ac.getBean("employeeCons7");
System.out.println(empCons7);
Employee empCons7_1 = (Employee)ac.getBean("employeeCons7");
System.out.println(empCons7_1);*/

/* //Bean life cycle methods
Employee empCons8 = (Employee)ac.getBean("employeeCons8");
System.out.println(empCons8);
//empCons8=null;
//System.gc();
//Runtime.getRuntime().gc();
ac.registerShutdownHook();*/

/* //Bean life cycle methods
Employee empCons8_ = (Employee)ac.getBean("employeeCons8_");
System.out.println(empCons8_);
ac.registerShutdownHook();*/

//Setter based Injection demo..  without property declaration settor methods will be called (Set Prefix)
/* Employee employeeProp9 = (Employee)ac.getBean("employeeProp9");
System.out.println(employeeProp9);*/

/* // setter injecton not working if the method prefix not have "Set"
Employee employeeProp10 = (Employee)ac.getBean("employeeProp10");
System.out.println(employeeProp10);
*/

/* // bean ref
Employee employeeProp11 = (Employee)ac.getBean("employeeProp11");
System.out.println(employeeProp11);*/

/* //Inner beans
Employee employeeProp12 = (Employee)ac.getBean("employeeProp12");
System.out.println(employeeProp12);*/

/* //Association or collection or group of bean references - List
Employee employeeProp13 = (Employee)ac.getBean("employeeProp13");
System.out.println(employeeProp13);*/


/* //Association or collection or group of bean references - Set
Employee employeeProp14 = (Employee)ac.getBean("employeeProp14");
System.out.println(employeeProp14);*/

/*//using multiple configuration files
Employee employeeProp15 = (Employee)ac.getBean("employeeProp15");
System.out.println(employeeProp15);*/

/* //error
//using multiple configuration files
 ac = new ClassPathXmlApplicationContext(new String[]{"config/department.xml","config/hello.xml"});
 Employee employeeProp16 = (Employee)ac.getBean("employeeProp16");
 System.out.println(employeeProp16);*/

/*//using FileSystemXmlApplicationContext use relative file path
ApplicationContext fsac = new FileSystemXmlApplicationContext("D:/Balaji/Demo1/src/config/hello.xml");
Employee employeeProp17 = (Employee)fsac.getBean("employeeProp17");
System.out.println(employeeProp17);
*/

/*//using autowire byName
Employee employeeProp18 = (Employee)ac.getBean("employeeProp18");
System.out.println(employeeProp18);
*/

/*//using autowire byType
Employee employeeProp19 = (Employee)ac.getBean("employeeProp19");
System.out.println(employeeProp19);*/

   
/* Address address = (Address)ac.getBean("address");
System.out.println(address);*/

/********** Notes **********/
//light weight component - many way of implementations

/* beans Tag default methods declaration

1. default-init-method
2.default-destroy-method
3. default-lazy-init

Life Cycle Method Invocation order:
1.Constructor invoke
        2.Application Context Aware -  setApplicationContext invoke
        3. InitializingBean - afterPropertiesSet  invoke
        4.Custom Init Method invoke (preference order1) or Default Init Method Invoke (preference order2)
        5.DisposableBean - Destroy life cycle  method of the bean called
        6.Custom Destroy Method invoke (preference order1) or Default Destroy Method Invoke (preference order2)

where we have to use ID attribute and Name attribute in Bean Tag
without ID attribute and Name attribute in Bean Tag - not error but how to retrive .. spring xml based
*/

}
}


package main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.annotation.Arithmatic;
import beans.annotation.Course;

public class MainApplicationAnnotation {
public static void main(String args[]){
ApplicationContext  ac = new ClassPathXmlApplicationContext("config/annotationbased.xml");
// ApplicationContext  ac = new AnnotationConfigApplicationContext("config/annotationbased.xml");
//using Annotations
//Student student = (Student)ac.getBean("student");
//System.out.println(student);
/* //using Annotations
Course course = (Course)ac.getBean("cours");
System.out.println(course);*/
//using AOP
Arithmatic arithmatic = (Arithmatic)ac.getBean("arithmatic");
System.out.println(arithmatic.add(5, 2));
 
/*********** Notes *********/
/*
1.Setter based injection via @Value(value = "002")
2.Constructor based injection via @autowired + @Value
@Autowired
public Student(@Value(value = "001") int studentNo, @Value(value = "Bala") String studentName) {
3. class annotations
@Component
@Service
@Repository
@Controller
@RestController
@Configuration
 
4.@Required Mandatory propery fields.. we need to inject via setter methods.. oly applicable for setter methods
 
// AnnotationConfigApplicationContext getting error
*
*/
}
}


(beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd" default-init-method="defaultInitMethod"  default-destroy-method="defaultDestoryMethod" )
(!--
(bean id="employeeProp" class="beans.Employee" )
(property name="empName" value="balaji" /)
(/bean)
(bean id="employeeCons" class="beans.Employee")
(constructor-arg value="001" )(/constructor-arg)
   (constructor-arg  value="balaji" ) (/constructor-arg)
(/bean)
(bean id="employeeCons2" class="beans.Employee")
   (constructor-arg  value="balaji" index="1") (/constructor-arg)
(constructor-arg value="001" index="0")(/constructor-arg)
(/bean)

(bean id="employeeCons3" class="beans.Employee" )
   (constructor-arg  value="balaji3" type="String" ) (/constructor-arg)
(constructor-arg value="003" type="int" )(/constructor-arg)
(/bean)
(bean id="employeeCons4" class="beans.Employee" )
   (constructor-arg  value="balaji4" type="java.lang.String" ) (/constructor-arg)
(constructor-arg value="004" type="int" )(/constructor-arg)
(/bean)

(bean id="employeeCons5" class="beans.Employee")
(constructor-arg value="005"  )(/constructor-arg)
   (constructor-arg  value="balaji5") (/constructor-arg)
(/bean)
(bean id="employeeCons5_" class="beans.Employee" scope="singleton")
(constructor-arg value="005_"  )(/constructor-arg)
   (constructor-arg  value="balaji5_") (/constructor-arg)
(/bean)
(bean id="employeeCons6" class="beans.Employee" lazy-init="true")
(constructor-arg value="006" )(/constructor-arg)
(constructor-arg  value="balaji6" ) (/constructor-arg)
(/bean) --)

(!-- (bean id="employeeCons7" class="beans.Employee" scope="prototype")
(constructor-arg value="007" )(/constructor-arg)
   (constructor-arg  value="balaji7") (/constructor-arg) 
(/bean)  --)

(!--    (bean id="employeeCons8" class="beans.Employee" init-method="customInitMethod" destroy-method="customDestoryMethod" )
(constructor-arg value="008" )(/constructor-arg)
   (constructor-arg  value="balaji8") (/constructor-arg)
(/bean)  --)
(!--    (bean id="employeeCons8_" class="beans.Employee"  )
(constructor-arg value="008" )(/constructor-arg)
   (constructor-arg  value="balaji8_") (/constructor-arg)
(/bean)  --)
(!-- (bean id="employeeProp9" class="beans.Employee" )
(property name="empName" value="balaji9" /)
(property name="sayHello" value="Hello!!" /)
(/bean) --)
(!-- (bean id="employeeProp10" class="beans.Employee" )
(property name="empName" value="balaji10" /)
(property name="sayHello1" value="Hello1!!" /)
(/bean) --)

(!--  (bean id="employeeProp11" class="beans.Employee" )
  (property name="empId" value="11" /)
(property name="empName" value="balaji11" /)
(property name="empAddress" ref="address11" /)
(/bean)
(bean id="address11" class="beans.Address")
(property name ="doorNo" value="41" /)
(property  name="street" value="Periyar Street" /) 
 (property  name="state" value="Tamil Nadu" /) 
(/bean)
 --)
(!-- 
    (bean id="employeeProp12" class="beans.Employee" )
  (property name="empId" value="12" /)
(property name="empName" value="balaji12" /)
(property name="empAddress")
(bean id="address12" class="beans.Address")
    (property name ="doorNo" value="42" /)
    (property  name="street" value="Periyar Street" /) 
     (property  name="state" value="Tamil Nadu" /) 
     (/bean)
(/property) 
(/bean)


    (bean id="employeeProp13" class="beans.Employee" )
  (property name="empId" value="13" /)
(property name="empName" value="balaji13" /)
(property name="empSkills")
(list)
    (ref bean="skillProp13" /)
        (ref bean="skillProp13" /)
(ref bean="skillProp13_" /)
(bean id="skillProp13__" class="beans.Skill" )
  (property name="skillId" value="003" /)
(property name="skillName" value="j2ee" /)
(/bean)
(value)skill1,skill2,skill3(/value)
(/list)
(/property)
(/bean)
(bean id="skillProp13" class="beans.Skill" )
  (property name="skillId" value="001" /)
(property name="skillName" value="Spring" /)
(/bean)
    (bean id="skillProp13_" class="beans.Skill" )
  (property name="skillId" value="002" /)
(property name="skillName" value="webservice" /)
(/bean)


    (bean id="employeeProp14" class="beans.Employee" )
  (property name="empId" value="14" /)
(property name="empName" value="balaji14" /)
(property name="empSkills")
(set)
    (ref bean="skillProp14" /)
    (ref bean="skillProp14" /)
(ref bean="skillProp14_" /)
(bean id="skillProp14__" class="beans.Skill" )
  (property name="skillId" value="003" /)
(property name="skillName" value="j2ee" /)
(/bean)
(value)skill1,skill2,skill3(/value)
(/set)
(/property)
(/bean)
(bean id="skillProp14" class="beans.Skill" )
  (property name="skillId" value="001" /)
(property name="skillName" value="Spring" /)
(/bean)
    (bean id="skillProp14_" class="beans.Skill" )
  (property name="skillId" value="002" /)
(property name="skillName" value="webservice" /)
(/bean) --)

(!--     (import resource="department.xml"/)
    (bean id="employeeProp15" class="beans.Employee" )
  (property name="empId" value="15" /)
(property name="empName" value="balaji15" /)
(property name="department" ref="dept" /)
(/bean) --)

(!--  (bean id="employeeProp16" class="beans.Employee" )
  (property name="empId" value="16" /)
(property name="empName" value="balaji16" /)
(property name="department" ref="dept" /)
(/bean) --)
(!-- (bean id="employeeProp17" class="beans.Employee" )
  (property name="empId" value="17" /)
(property name="empName" value="balaji17" /)
(/bean) --)
(!-- (bean id="employeeProp18" class="beans.Employee" autowire="byName" )
(property name="empId" value="18" /)
(property name="empName" value="balaji18" /)
  (/bean)
(bean id="department" class="beans.Department" )
  (property name="deptId" value="002" /)
(property name="deptName" value="Computer" /)
(/bean)
(bean id="empAddress" class="beans.Address")
    (property name ="doorNo" value="41" /)
    (property  name="street" value="Periyar Street" /) 
     (property  name="state" value="Tamil Nadu" /) 
     (/bean) --)

(!-- (bean id="employeeProp19" class="beans.Employee" autowire="byType"  )
(property name="empId" value="19" /)
(property name="empName" value="balaji19" /)
  (/bean)
(bean id="department" class="beans.Department" )
  (property name="deptId" value="001" /)
(property name="deptName" value="Computer" /)
(/bean)
(bean id="empAddress" class="beans.Address")
    (property name ="doorNo" value="41" /)
    (property  name="street" value="Periyar Street" /) 
     (property  name="state" value="Tamil Nadu" /) 
     (/bean)
 --)

(bean  class="beans.Address")
    (property name ="doorNo" value="41" /)
    (property  name="street" value="Periyar Street" /) 
     (property  name="state" value="Tamil Nadu" /) 
     (/bean)
(/beans)

(?xml version="1.0" encoding="UTF-8"?)
(beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd" default-init-method="defaultInitMethod"  default-destroy-method="defaultDestoryMethod" )
    (bean id="dept" class="beans.Department" )
  (property name="deptId" value="001" /)
(property name="deptName" value="Computer" /)
(/bean)
(/beans)


(?xml version="1.0" encoding="UTF-8"?)
(beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd")
 
(context:component-scan base-package="beans.annotation,beans" /)
 (aop:aspectj-autoproxy /)
 (!-- (bean id="arithmatic" class="beans.annotation.Arithmatic"/)
(bean id="myAdvice" class="beans.annotation.MyAdvice"/)   --)
(/beans)


package beans;

public class Address {

private int doorNo;
private String street;
private String state;
public int getDoorNo() {
return doorNo;
}
public void setDoorNo(int doorNo) {
this.doorNo = doorNo;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "Address [doorNo=" + doorNo + ", street=" + street + ", state=" + state + "]";
}
}


package beans;

public class Department {

private String deptId;
private String deptName;
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return "Department [deptId=" + deptId + ", deptName=" + deptName + "]";
}
}


package beans;

import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Employee implements InitializingBean,DisposableBean,ApplicationContextAware {

private int empId;
private String empName;
private Address empAddress;
private List(Skill) empSkills; 
    private Department department;

public Employee() {
super();
System.out.println("default constructor called");
}

public Employee(int empId, String empName) {
super();
this.empId = empId;
this.empName = empName;
System.out.println("2-arg constructor called ");
}

public Employee(int empId, String empName, Address empAddress) {
super();
this.empId = empId;
this.empName = empName;
this.empAddress = empAddress;
System.out.println("3-arg constructor called ");
}

public void setSayHello(String str){
System.out.println("setSayHello - "+str);
}
public void sayHello1(String str){
System.out.println("sayHello1 - "+str);
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}

public Address getEmpAddress() {
return empAddress;
}

public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}

public List(Skill) getEmpSkills() {
return empSkills;
}

public void setEmpSkills(List(Skill) empSkills) {
this.empSkills = empSkills;
}

public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}

@Override
public void destroy() throws Exception {
System.out.println("DisposableBean - Destroy life cycle  method of the bean called");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean - afterPropertiesSet  method of the bean called");
}
public void customInitMethod(){
System.out.println("Custom Init Method Called");
}
   public void customDestoryMethod(){
System.out.println("Custom Destroy Method Called");
}

public void defaultInitMethod(){
System.out.println("Default Init Method Called");
}
    public void defaultDestoryMethod(){
System.out.println("Default Destroy Method Called");
}
   
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
System.out.println("setApplicationContext method called"+ac);
}

@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", empAddress=" + empAddress + ", empSkills="
+ empSkills + ", department=" + department + "]";
}
}

package beans;

public class Skill {

private String skillId;
private String skillName;
public String getSkillId() {
return skillId;
}
public void setSkillId(String skillId) {
this.skillId = skillId;
}
public String getSkillName() {
return skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
@Override
public String toString() {
return "Skill [skillId=" + skillId + ", skillName=" + skillName + "]";
}

}



Jersy Restful Example

package com;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import pojo.Address;
@Path("/aa")
public class AllDemo {

@GET
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@Path("/bb")
public Address demoOne()
{
return new Address(100,"Chennai","TN");
}


@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.TEXT_PLAIN})
@Path("/cc")
public String demoTwo(Address address)
{
System.out.println(address.getState());
return " Welcome to " + address.getCity();
}

@POST
@Produces({MediaType.APPLICATION_JSON})
@Path("/dd")
public List demoThree()
{
List list = new ArrayList(Address)();
Address address1 = new Address(10,"Chennai","TN");
Address address2 = new Address(20,"Bangalore","KA");
Address address3 = new Address(10,"Hyderabad","AP");
list.add(address1);
list.add(address2);
list.add(address3);
return list;
}

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/ee")
public List(Address) demoFour(Address address)
{
System.out.println(address.getState());
List(Address) list = new ArrayList(Address)();
Address address1 = new Address(10,"Chennai","TN");
Address address2 = new Address(20,"Bangalore","KA");
Address address3 = new Address(10,"Hyderabad","AP");
list.add(address1);
list.add(address2);
list.add(address3);
address.setCity("updated City");
address.setState("Updated State");
list.add(address);
return list;
}

@GET
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@Path("/ff")
public List(Address) demoFive()
{

Address address1 = new Address(10,"Chennai","TN");
Address address2 = new Address(20,"Bangalore","KA");
Address address3 = new Address(30,"Hyderabad","AP");

List(Address) list = new ArrayList(Address)();
list.add(address1);
list.add(address2);
list.add(address3);

return list;
}
}


package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RESTClientExample {
   
    public static void main(String[] args) {
       
        try {

URL url = new URL("http://localhost:9090/JSonRest/rest/aa/bb");
               
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

conn.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

 }

}
}


package pojo;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement
//@XmlType(propOrder = {  "doorNo", "city","state" })
public class Address {
private int doorNo;
private String city;
private String state;

public Address() {
super();
// TODO Auto-generated constructor stub
}

public Address(int doorNo, String city, String state) {
super();
this.doorNo = doorNo;
this.city = city;
this.state = state;
}

public int getDoorNo() {
return doorNo;
}

public void setDoorNo(int doorNo) {
this.doorNo = doorNo;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

}

(?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5")
(display-name)Participants_RestService(/display-name)
(welcome-file-list)
(welcome-file)index.html(/welcome-file)
(welcome-file)index.htm(/welcome-file)
(welcome-file)index.jsp(/welcome-file)
(welcome-file)default.html(/welcome-file)
(welcome-file)default.htm(/welcome-file)
(welcome-file)default.jsp(/welcome-file)
(/welcome-file-list)
(servlet)
(servlet-name)Jersey REST Service(/servlet-name)
(servlet-class)com.sun.jersey.spi.container.servlet.ServletContainer(/servlet-class)
(init-param)
(param-name)com.sun.jersey.config.property.packages(/param-name)
(param-value)com(/param-value)
(/init-param)
(init-param)
(param-name)com.sun.jersey.api.json.POJOMappingFeature(/param-name)
(param-value)true(/param-value)
(/init-param)

(load-on-startup)1(/load-on-startup)
(/servlet)
(servlet-mapping)
(servlet-name)Jersey REST Service(/servlet-name)
(url-pattern)/rest/*(/url-pattern)
(/servlet-mapping)
(/web-app)


import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class RestServiceMain {

private static URI getBaseURI() {
   return UriBuilder.fromUri("http://localhost:9090/Participants_RestService/").build();
 }

public static void main(String[] args) {
   ClientConfig config = new DefaultClientConfig();
     Client client = Client.create(config);
     WebResource service = client.resource(getBaseURI());
     // Fluent interfaces
     System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
     // Get plain text
     System.out.println(service.path("rest").path("hello").accept( MediaType.TEXT_PLAIN).get(String.class));
   
     // Get XML
   
     //System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
   
     // The HTML
   
     System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));
}

}


Spring Boot MVC + Free Marker

package com.example;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FTLHelloWorld {
public static void main(String[] args) {
//Freemarker configuration object
Configuration cfg = new Configuration();
try {
//Load template from source folder
Template template = cfg.getTemplate("src/helloworld.ftl");

// Build the data-model
Map(String, Object) data = new HashMap(String, Object)();
data.put("message", "Hello World!");

//List parsing
List(String) countries = new ArrayList(String)();
countries.add("India");
countries.add("United States");
countries.add("Germany");
countries.add("France");

data.put("countries", countries);

// Console output
Writer out = new OutputStreamWriter(System.out);
template.process(data, out);
out.flush();

// File output
File f=new File("d:\\FTL_helloworld.txt");
f.createNewFile();
Writer file = new FileWriter (f);
template.process(data, file);
file.flush();
file.close();

} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}

}


package com.example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
        model.addAttribute("name", name);
        return "hello";
    }
}


package com.example;
public class User {
private String firstname;
private String lastname;
public User() {
super();
}
public User(String firstname, String lastname) {
super();
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Override
public String toString() {
return "User [firstname=" + firstname + ", lastname=" + lastname + "]";
}
}


package com.example;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {
/**
* Static list of users to simulate Database
*/
private static List(User) userList = new ArrayList(User)();

//Initialize the list with some data for index screen
static {
userList.add(new User("Bill", "Gates"));
userList.add(new User("Steve", "Jobs"));
userList.add(new User("Larry", "Page"));
userList.add(new User("Sergey", "Brin"));
userList.add(new User("Larry", "Ellison"));
}

/**
* Saves the static list of users in model and renders it
* via freemarker template.
*
* @param model
* @return The index view (FTL)
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(@ModelAttribute("model") ModelMap model) {

model.addAttribute("userList", userList);

return "index";
}

/**
* Add a new user into static user lists and display the
* same into FTL via redirect
*
* @param user
* @return Redirect to /index page to display user list
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@ModelAttribute("user") User user) {

if (null != user && null != user.getFirstname()
&& null != user.getLastname() && !user.getFirstname().isEmpty()
&& !user.getLastname().isEmpty()) {

synchronized (userList) {
userList.add(user);
}

}
return "redirect:index.html";
}
}


application.properties
spring.freemarker.template-loader-path: /
spring.freemarker.suffix: .ftl


(!DOCTYPE html)
(html lang="en")
(head)
    (meta charset="UTF-8")
    (title)Hello ${name}!(/title)
(/head)
(body)
    (h2)Hello ${name}!(/h2)
(/body)
(/html)

(html)
(head)(title) FreeMarker Spring MVC Hello World(/title)
(body)
(div id="header")
(H2)
FreeMarker Spring MVC Hello World
(/H2)
(/div)

(div id="content")
   
  (fieldset)
  (legend)Add User(/legend)
  (form name="user" action="add.html" method="post")
  Firstname: (input type="text" name="firstname" /) (br/)
  Lastname: (input type="text" name="lastname" /) (br/)
  (input type="submit" value="   Save   " /)
  (/form)
  (/fieldset)
  (br/)
  (table class="datatable")
  (tr)
  (th)Firstname(/th)  (th)Lastname(/th)
  (/tr)
    (#list model["userList"] as user)
  (tr)
  (td)${user.firstname}(/td) (td)${user.lastname}(/td)
  (/tr)
    (/#list)
  (/table)

(/div)
(/body)
(/html)

 (dependency)
 (groupId)org.springframework.boot(/groupId)
 (artifactId)spring-boot-starter-freemarker(/artifactId)
 (/dependency)

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...