Thursday 17 May 2018

Mokito

package com.in28minutes.springboot.controller;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.mockito.Mockito;

import org.skyscreamer.jsonassert.JSONAssert;

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

import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;

import org.springframework.boot.test.mock.mockito.MockBean;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.mock.web.MockHttpServletResponse;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.MvcResult;

import org.springframework.test.web.servlet.RequestBuilder;

import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.in28minutes.springboot.model.Course;

import com.in28minutes.springboot.service.StudentService;


@RunWith(SpringRunner.class)

@WebMvcTest(value = StudentController.class, secure = false)

public class StudentControllerTest {

@Autowired

private MockMvc mockMvc;

@MockBean

private StudentService studentService;

Course mockCourse = new Course("Course1", "Spring", "10 Steps",

Arrays.asList("Learn Maven", "Import Project", "First Example",

"Second Example"));

String exampleCourseJson = "{\"name\":\"Spring\",\"description\":\"10 Steps\",\"steps\":[\"Learn Maven\",\"Import Project\",\"First Example\",\"Second Example\"]}";

@Test

public void retrieveDetailsForCourse() throws Exception {

Mockito.when(

studentService.retrieveCourse(Mockito.anyString(),

Mockito.anyString())).thenReturn(mockCourse);

RequestBuilder requestBuilder = MockMvcRequestBuilders.get(

"/students/Student1/courses/Course1").accept(

MediaType.APPLICATION_JSON);

MvcResult result = mockMvc.perform(requestBuilder).andReturn();

System.out.println("leejo:"+result.getResponse());

String expected = "{id:Course1,name:Spring,description:110 Steps}";

// {"id":"Course1","name":"Spring","description":"10 Steps, 25 Examples and 10K Students","steps":["Learn Maven","Import Project","First Example","Second Example"]}

JSONAssert.assertEquals(expected, result.getResponse()

.getContentAsString(), false);

}

@Test

public void createStudentCourse() throws Exception {

Course mockCourse = new Course("1", "Smallest Number", "1",

Arrays.asList("1", "2", "3", "4"));

// studentService.addCourse to respond back with mockCourse

Mockito.when(

studentService.addCourse(Mockito.anyString(),

Mockito.any(Course.class))).thenReturn(mockCourse);

// Send course as body to /students/Student1/courses

RequestBuilder requestBuilder = MockMvcRequestBuilders

.post("/students/Student1/courses")

.accept(MediaType.APPLICATION_JSON).content(exampleCourseJson)

.contentType(MediaType.APPLICATION_JSON);

MvcResult result = mockMvc.perform(requestBuilder).andReturn();

MockHttpServletResponse response = result.getResponse();

assertEquals(HttpStatus.CREATED.value(), response.getStatus());

assertEquals("http://localhost/students/Student1/courses/1",

response.getHeader(HttpHeaders.LOCATION));

}

}

study this too   https://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/

Show quoted text

Monday 16 April 2018

WebMvcConfigurerAdapter

package com.leejo.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;

import org.hibernate.SessionFactory;

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

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

import org.springframework.core.env.Environment;

import org.springframework.orm.hibernate4.HibernateTemplate;

import org.springframework.orm.hibernate4.HibernateTransactionManager;

import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;

import org.springframework.transaction.annotation.EnableTransactionManagement;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.leejo.bo.Interceptor;

import com.leejo.model.Student;

/**

* @author Leejo Jose

* @date 01-11-2017

*

*/

@Configuration

@ComponentScan("com.leejo")

@EnableWebMvc

@PropertySource("classpath:db.properties")

@EnableTransactionManagement

public class ApplicationContextConfig extends WebMvcConfigurerAdapter{

@Bean(name = "viewResolver")

public InternalResourceViewResolver getViewResolver() {

InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

viewResolver.setPrefix("/WEB-INF/views/");

viewResolver.setSuffix(".jsp");

return viewResolver;

}  

//leejo jose demo

@Autowired

private Environment env;

@Bean

public DataSource getDataSource() {

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));

dataSource.setUrl(env.getProperty("jdbc.url"));

dataSource.setUsername(env.getProperty("jdbc.username"));

dataSource.setPassword(env.getProperty("jdbc.password"));  

return dataSource;

}

@Bean

@Autowired

public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)

{

HibernateTransactionManager htm = new HibernateTransactionManager();

htm.setSessionFactory(sessionFactory);

return htm;

}

@Bean

@Autowired

public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory)

{

HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);

return hibernateTemplate;

}

@Autowired

@Bean(name = "sessionFactory")

public SessionFactory getSessionFactory(DataSource dataSource) {

LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);  

//sessionBuilder.addAnnotatedClasses(User.class,UserProfile.class,Student.class);

sessionBuilder.scanPackages("com.leejo.model");

return sessionBuilder.buildSessionFactory();

}

@Bean

public Properties getHibernateProperties()

{

Properties properties = new Properties();

properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));

properties.put("hibernate.current_session_context_class", env.getProperty("hibernate.current_session_context_class"));

return properties;

}

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");

registry.addResourceHandler("/uploads/**").addResourceLocations("/uploads/");

registry.addResourceHandler("/albums/**").addResourceLocations("/albums/");

}

@Bean

public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {

return new PropertySourcesPlaceholderConfigurer();

}

@Autowired

@Bean(name = "studentService")

public Student getUserDetails(){

return new Student();

}

@Override

public void addInterceptors(InterceptorRegistry registry) {

// TODO Auto-generated method stub

registry.addInterceptor(new Interceptor());

}

}

Monday 2 April 2018

Java 8

forEach() method in Iterable interface

Whenever we need to traverse through a Collection, we need to create an Iterator whose whole purpose is to iterate over and then we have business logic in a loop for each of the elements in the Collection. We might get ConcurrentModificationException if iterator is not used properly.

Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only. forEach method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a separate location that we can reuse. Let’s see forEach usage with simple example.

example

package com.leejo.forech;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.function.Consumer;

import java.lang.Integer;

public class Java8ForEachExample {

public static void main(String[] args) {

//creating sample Collection

List<Integer> myList = new ArrayList<Integer>();

for(int i=0; i<10; i++) myList.add(i);

//traversing using Iterator

Iterator<Integer> it = myList.iterator();

while(it.hasNext()){

Integer i = it.next();

System.out.println("Iterator Value::"+i);

}

//traversing through forEach method of Iterable with anonymous class

myList.forEach(new Consumer<Integer>() {

public void accept(Integer t) {

System.out.println("forEach anonymous class Value::"+t);

}

});

//traversing with Consumer interface implementation

MyConsumer action = new MyConsumer();

myList.forEach(action);

}

}

//Consumer implementation that can be reused

class MyConsumer implements Consumer<Integer>{

public void accept(Integer t) {

System.out.println("Consumer impl Value::"+t);

}

}

---The number of lines might increase but forEach method helps in having the logic for iteration and business logic at separate place resulting in higher separation of concern and cleaner code.

Wednesday 28 March 2018

Javascript Validation Code to Block Free Emails (Gmail, Yahoo) & Allow Business Emails in Forms

Leejo.

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(e){

$('#btnSubmit').click(function(){ 

var email = $('#Email').val();

var reg = /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!abc.com)(?!xyz.com)(?!pqr.com)(?!rediffmail.com)(?!live.com)(?!outlook.com)(?!me.com)(?!msn.com)(?!ymail.com)([\w-]+\.)+[\w-]{2,4})?$/;

if (reg.test(email)){

return 0;

}

else{

alert('Please Enter Business Email Address');

return false;

}

});

});

</script>

</head>

<body>

<form id="yourid" action="" method="POST/GET">

<input type="text" name="email" id="Email">

<input type="submit" id="btnSubmit" name="download_submit" value="Submit">

</form>

</body>

</html>

Friday 16 March 2018

Jdbctemplate ,jpareposcutry

JPA

Using JpaRepository

 

 

JdbcTemplate operations

1.jdbcTemplate.query(qry, new BookMapper());----getting

2.jdbcTemplate.queryForObject

String qry="select * from book_master where book_id = ?";

return jdbcTemplate.queryForObject(qry, new BookMapper(),book_id);

3. jdbcTemplate.update

for adding

String qry="INSERT INTO book_master (book_name,book_author) VALUES(?,?)";

return jdbcTemplate.update(qry,book.getBook_name(),book.getBook_author());

String qry="UPDATE book_master set book_name=?,book_author=? where book_id=?";

jdbcTemplate.update(qry,book.getBook_name(),book.getBook_author(),book.getBook_id());

Spring ioc di

spring

1.What is Inversion of Control?

.Inversion of Control is a principle in software engineering by which the control of objects or portions of a program is transferred to a container or framework

.IoC enables a framework to take control of the flow of a program and make calls to our custom code. To enable this, frameworks use abstractions with additional behavior built in

. If we want to add our own behavior, we need to extend the classes of the framework or plugin our own classes.

-->Advantage

.decoupling the execution of a task from its implementation

.making it easier to switch between different implementations

.greater modularity of a program

.greater ease in testing a program by isolating a component or mocking its dependencies and allowing components to communicate through contracts

 

 

--Inversion of Control can be achieved through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).

 

2.What is Dependency Injection?

.Dependency injection is a pattern through which to implement IoC, where the control being inverted is the setting of object’s dependencies.

.The act of connecting objects with other objects, or “injecting” objects into other objects, is done by an assembler rather than by the objects themselves.

3.The Spring IoC Container

.In the Spring framework, the IoC container is represented by the interface ApplicationContext. The Spring container is responsible for instantiating, configuring and assembling objects known as beans, as well as managing their lifecycle.

.The Spring framework provides several implementations of the ApplicationContext interface 

--ClassPathXmlApplicationContext and FileSystemXmlApplicationContext for standalone applications

--WebApplicationContext,AnnotationConfigWebApplicationContext for web applications.   

.In order to assemble beans, the container uses configuration metadata, which can be in the form of XML configuration or annotations.

eg:ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");

4.Dependency Injection in Spring

public class Store {

private Item item;

public Store(Item item) {

this.item = item;

}

}

--To set the item attribute in the example above, we can use metadata. Then, the container will read this metadata and use it to assemble beans at runtime.

--Dependency Injection in Spring can be done through constructors, setters or fields.

5. Constructor-Based Dependency Injection

http://www.baeldung.com/inversion-control-and-dependency-injection-in-spring

6.Setter-Based Dependency Injection

7.Autowiring Dependencies

Wiring allows the Spring container to automatically resolve dependencies between collaborating beans by inspecting the beans that have been defined.

There are four modes of autowiring a bean using an XML configuration:

no: the default value – this means no autowiring is used for the bean and we have to explicitly name the dependencies

byName: autowiring is done based on the name of the property, therefore Spring will look for a bean with the same name as the property that needs to be set

byType: similar to the byName autowiring, only based on the type of the property. This means Spring will look for a bean with the same type of the property to set. If there’s more than one bean of that type, the framework throws an exception.

constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans with the same type as the constructor arguments

@Bean(autowire = Autowire.BY_TYPE)

Java class loader

What is Java ClassLoader?

We know that Java Program runs on Java Virtual Machine (JVM). When we compile a Java Class, it transforms it in the form of bytecode that is platform and machine independent compiled program and store it as a .class file. After that when we try to use a Class, Java ClassLoader loads that class into memory.

There are three types of built-in ClassLoader in Java:

1.Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes

2.Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.

3.System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.

1-->You should never be messing with rt.jar, it contains class files which is trusted by JVM and loaded without stringent security check it does for other class files. The runtime (rt.jar) holds all the (most of the..) java classes that form the Java SE. It is added to the classpath automatically

follow linkhttps://www.journaldev.com/349/java-classloader

Override hashcode and equals why

Override only equals

If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket (as they have a different hashCode). So, although they are equal, as they don't hash to the same bucket, the map can't realize it and both of them stay in the map.

Although it is not necessary to override equals() if we override hashCode(), let's see what would happen in this particular case where we know that two objects of MyClass are equal if their importantField is equal but we do not override equals().

Override only hashCode

Imagine you have this

MyClass first = new MyClass("a","first");

MyClass second = new MyClass("a","second");

If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to the business requirement).

But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.

Hope it was clear

Word count using collection

package com.lightbend.akka.sample;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

public class Testr {

//

// public static void main(String[] argv) {

//  Map<String, String> map = new HashMap<String, String>();

//  map.put("1","one");

//  map.put("2","two");

//  map.put("3","three");

//  map.put("4","four");

//   

// System.out.println(getKeyFromValue(map,"three"));

//  }

//

//  public static Object getKeyFromValue(Map hm, Object value) {

//  for (Object o : hm.keySet()) {

//  if (hm.get(o).equals(value)) {

//  return o;

//  }

//  }

//  return null;

//  }

// main() method - entry point to start execution

public static void main(String[] args) {

 

// sample test string

String testStr = "Science blank Maths blank blank Physics blank Maths Science Science";

 

// invoke to count & print for supplied file

countAndPrintRepeatedWordOccurences(testStr);

}

 

/**

* this method is used to count number repeated word occurrences

* @param fileName

*/

public static void countAndPrintRepeatedWordOccurences(String strContent) {

 

// Step 1: create Map of String-Integer

Map<String, Integer> mapOfRepeatedWord = new HashMap<String, Integer>();

 

// Step 2: split line using space as delimiter

String[] words = strContent.split(" ");

 

// Step 3: iterate through String[] array

for(String word : words) {

 

// Step 4: convert all String into lower case, before comparison

String tempUCword = word.toLowerCase();

 

// Step 5: check whether Map contains particular word, already 

if(mapOfRepeatedWord.containsKey(tempUCword)){

 

// Step 6: If contains, increase count value by 1

mapOfRepeatedWord.put(tempUCword, mapOfRepeatedWord.get(tempUCword) + 1);

else {

 

// Step 7: otherwise, make a new entry

mapOfRepeatedWord.put(tempUCword, 1);

}

}

 

System.out.println("Before sorting : \n");

System.out.println("Words" + "\t\t" + "Count");

System.out.println("======" + "\t\t" + "=====");

 

// Step 8: print word along with its count

for(Map.Entry<String, Integer> entry : mapOfRepeatedWord.entrySet()){

System.out.println(entry.getKey() + "\t\t" + entry.getValue());

}

 

// Step 9: Sorting logic by invoking sortByCountValue() method

Map<String, Integer> wordLHMap = sortByCountValue(mapOfRepeatedWord);

 

System.out.println("\n\nAfter sorting in descending order of count : \n");

System.out.println("Words" + "\t\t" + "Count");

System.out.println("======" + "\t\t" + "=====");

 

// Step 10: Again print after sorting

for(Map.Entry<String, Integer> entry : wordLHMap.entrySet()){

System.out.println(entry.getKey() + "\t\t" + entry.getValue());

}

}

 

/**

* this method sort acc. to count value

* @param mapOfRepeatedWord

* @return

*/

public static Map<String, Integer> sortByCountValue(

Map<String, Integer> mapOfRepeatedWord) {

 

// get entrySet from HashMap object

Set<Map.Entry<String, Integer>> setOfWordEntries = mapOfRepeatedWord.entrySet();

 

// convert HashMap to List of Map entries

List<Map.Entry<String, Integer>> listOfwordEntry = 

new ArrayList<Map.Entry<String, Integer>>(setOfWordEntries);

 

// sort list of entries using Collections class utility method sort(ls, cmptr)

Collections.sort(listOfwordEntry, 

new Comparator<Map.Entry<String, Integer>>() {

 

@Override

public int compare(Entry<String, Integer> es1, 

Entry<String, Integer> es2) {

return es2.getValue().compareTo(es1.getValue()); // NOTE

}

});

 

// store into LinkedHashMap for maintaining insertion order

Map<String, Integer> wordLHMap = 

new LinkedHashMap<String, Integer>();

 

// iterating list and storing in LinkedHahsMap

for(Map.Entry<String, Integer> map : listOfwordEntry){

wordLHMap.put(map.getKey(), map.getValue());

}

 

return wordLHMap;

}

}

Jax -rs

Webservice

1.Jersey is an open source framework for developing RESTful Web Services. It serves as a reference implementation of JAX-RS.

2.In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods. In a REST based architecture you have a REST server which provides access to the resources. A REST client can access and modify the REST resources.

3.Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation)

4.A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul web service defines the base URI for the services

===>jersy type controller

@Path("/authenticate")

@POST

@Produces(MediaType.APPLICATION_JSON)

@Consumes(MediaType.APPLICATION_JSON)

===>spring web service

@GetMapping("books")

Sunday 11 March 2018

Spring boot

spring boot: use because of --> if we wan to develop an end to end sys like controller service or from scratch we can use spring boot

. spring boot feature that provide when create an API or application 

. spring boot is==== spring is frame for entrprice java applicationn ,, boot stands for is bootstrap a spring application ,,it make easy to create stand alone ,production -grade spring based application that you can "just run"

--stand alone 

--production grade 

. Spring is dependency injunction in older definition ,, now it is more..... lot of things in spring ,, 

. spring has infrastructure suport to connect with db like casandra,mongo

. spring have not of configuration,in different ways

.spring boot ---

its stand alone , what u get u can start run ,and don't want start web server don't want to search for servlet ,and also is production ready

 

.--->convert simple maven to spring boot project

we using a <parent> tag with spring parameter to show the app is child of this parent spring 

 

<parent>

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

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

<version>2.0.0.RELEASE</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

this parent project above showing

spring boot team create a project  "spring-boot-starter-parent" above spring boot team created a project called spring-boot-starter-parent ,which contains opinionated set of maven configuration

and it provide set of maven depetency into pom.xml for creating the project. 

then we add "spring-boot-starter-jdbc" , "spring-boot-starter-web" which download the jar which mete dependency (these are articact id in dependency)

-->there is <properties> tag in pom.xml ,here which is used for use latest version of jdk  

<properties>

<java.version>1.8</java.version>

</properties>

-->in spring boot application we have a class with public static void main because spring boot is stand alone son need a class which bootstrap the app,,so don not need diployee on server or servelt container

main methord start the app, it create the servelet container and it do everything 

--> steps in class which has main method

1.we need to tell this is the spring application for that use @SpringBootApplication this tell this is the starting position

2.the we need to tell,spring boot to start this application and create servelet container and host this application on that servelt container ,this step done in one line

is SpringAppliction.run(CourseApi.class,args); ----->courseApi is calls which contain the main method

@SpringBootApplication

public class CourseApi {

//this class we are going for boot strap the application

public static void main(String[] args) {

SpringApplication.run(CourseApi.class, args);

}

}

spring is container that contain controller,business services,data services spring has container that contain all those services this is called application context of the application

each logics are implemented in classes with corresponding annotation like service classes annotated with @service and data access annotated with @Repository and son on.

spring want to look these classes and distinguish these classes according to annotation.so we need to scan the class path. so need give component scan.
#####
->@SpringBootApplication(scanBasePackages= {"com.leejo.controller"})

-->Here we need controller to handle the request,@RestController ->it means we can map to request to methord of class which use this anottation

 

-->@ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseEntity in detail===> we can many things with responseentity

@RequestMapping("/handle")

public ResponseEntity<String> handle() {

URI location = ...;

HttpHeaders responseHeaders = new HttpHeaders();

responseHeaders.setLocation(location);

responseHeaders.set("MyResponseHeader", "MyValue");

return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);

}

--->RequestEntity and ResponseEntity

 

@RequestMapping("getTopicsRequest")

public ResponseEntity<List<Topics>> getTopicsRequest(RequestEntity<List<Topics>> requestEntity){

System.out.println("request body : " + requestEntity.getBody());

HttpHeaders headers = requestEntity.getHeaders();

System.out.println("request headers : " + headers);

HttpMethod method = requestEntity.getMethod();

System.out.println("request method : " + method);

System.out.println("request url: " + requestEntity.getUrl());

return new ResponseEntity<>(null,HttpStatus.OK);

}

 

--->@RequestBody sample this can use viseversa with RequestEntity

@RequestMapping("getTopicsRequestBody")

public ResponseEntity<List<Topics>> getTopicsRequestBody(@RequestBody List<Topics> topics){

System.out.println("request body : " + topics);

return new ResponseEntity<>(null,HttpStatus.OK);

}

if you want to show the URI as requestentity above exapmle we have to use "UriComponentsBuilder" in parameter list

@PostMapping("book")

public ResponseEntity<Void> addBook(@RequestBody Book book,UriComponentsBuilder builder){

int flag=bookServiceImpl.addBook(book);

if(flag==0) {

return new ResponseEntity<Void>(HttpStatus.CONFLICT);

}

HttpHeaders headers = new HttpHeaders();

headers.setLocation(builder.path("/book/{book_id}").buildAndExpand(book.getBook_id()).toUri());

return new ResponseEntity<Void>(headers, HttpStatus.CREATED);

}

Wednesday 28 February 2018

Spring web service one

Spring MVC Framework and REST

1.Spring MVC :-Client request to Dispatcher-->handler mapping-->Controller-->view

2.REST spring  :-client request to web service in URI form--->intercepted by Dispatcher it find the controller based on incoming request -->request proced by controller and responds is return to the dispatcher which then dispatched to view

Using the @ResponseBody Annotation

When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.

##Using the @RestController Annotation

   Spring 4.0 introduced @RestController

    By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default

Friday 2 February 2018

Create Json From Java Code

to download eclipse https://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/neon3



Model or pojo

package test;

public class ProjectLIst {

String idProject;
String siteLocation;
String name;
String type;
String siteMangr;

public ProjectLIst(){}

public ProjectLIst(String idProject,String siteLocation,String name,String type,String siteMangr){
this.idProject=idProject;
this.siteLocation=siteLocation;
this.name=name;
this.type=type;
this.siteMangr=siteMangr;
}





public String getIdProject() {
return idProject;
}

public void setIdProject(String idProject) {
this.idProject = idProject;
}

public String getSiteLocation() {
return siteLocation;
}
public void setSiteLocation(String siteLocation) {
this.siteLocation = siteLocation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSiteMangr() {
return siteMangr;
}
public void setSiteMangr(String siteMangr) {
this.siteMangr = siteMangr;
}



}

##################################
package test;

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

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;


public class JsonCreating {
public static void main(String args[]){
ProjectLIst p1=new ProjectLIst("1","kochi","lee","steel","vimal");
ProjectLIst p2=new ProjectLIst("1","kochi","lfsdee","sdfdteel","errvimal");
ProjectLIst p3=new ProjectLIst("1","kochiee","wewelee","stedfel","erfdfvimal");
List<ProjectLIst> pList=new ArrayList<ProjectLIst>();
pList.add(p1);
pList.add(p2);
pList.add(p3);
Gson gson = new Gson();
Type type = new TypeToken<List<ProjectLIst>>() {}.getType();
        //String json = gson.toJson(list, type);
String myjson=gson.toJson(pList,type);
System.out.println(myjson);
}

}


############################
Nested

package test;

import java.util.List;

public class ProjectLIst {

String idProject;
String siteLocation;
String name;
String type;
String siteMangr;

List<Phone> phons;

public ProjectLIst(){}

public ProjectLIst(String idProject,String siteLocation,String name,String type,String siteMangr,List<Phone> ph){
this.idProject=idProject;
this.siteLocation=siteLocation;
this.name=name;
this.type=type;
this.siteMangr=siteMangr;
this.phons=ph;
}





public List<Phone> getPhons() {
return phons;
}

public void setPhons(List<Phone> phons) {
this.phons = phons;
}

public String getIdProject() {
return idProject;
}

public void setIdProject(String idProject) {
this.idProject = idProject;
}

public String getSiteLocation() {
return siteLocation;
}
public void setSiteLocation(String siteLocation) {
this.siteLocation = siteLocation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSiteMangr() {
return siteMangr;
}
public void setSiteMangr(String siteMangr) {
this.siteMangr = siteMangr;
}



}

----
package test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class JsonNested {
public static void main(String args[]){
  Phone ph1=new Phone();
  ph1.setPhnnum("33333333");
  Phone ph=new Phone();
  ph.setPhnnum("33333333");
  List<Phone> phonelist=new ArrayList<Phone>();
  phonelist.add(ph);
  phonelist.add(ph1);
ProjectLIst p1=new ProjectLIst("1","kochi","lee","steel","vimal",phonelist);
ProjectLIst p2=new ProjectLIst("1","kochi","lfsdee","sdfdteel","errvimal",phonelist);
ProjectLIst p3=new ProjectLIst("1","kochiee","wewelee","stedfel","erfdfvimal",phonelist);
List<ProjectLIst> pList=new ArrayList<ProjectLIst>();
pList.add(p1);
pList.add(p2);
pList.add(p3);
Gson gson = new Gson();
Type type = new TypeToken<List<ProjectLIst>>() {}.getType();
        //String json = gson.toJson(list, type);
String myjson=gson.toJson(pList,type);
System.out.println(myjson);
}

}
  output
[{"idProject":"1","siteLocation":"kochi","name":"lee","type":"steel","siteMangr":"vimal","phons":[{"phnnum":"33333333"},{"phnnum":"33333333"}]},{"idProject":"1","siteLocation":"kochi","name":"lfsdee","type":"sdfdteel","siteMangr":"errvimal","phons":[{"phnnum":"33333333"},{"phnnum":"33333333"}]},{"idProject":"1","siteLocation":"kochiee","name":"wewelee","type":"stedfel","siteMangr":"erfdfvimal","phons":[{"phnnum":"33333333"},{"phnnum":"33333333"}]}]