Spring Boot with Mongo DB ( Delete Data)

pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.subu</groupId>
<artifactId>SpringWithMongoDB</artifactId>
<packaging>war</packaging>
<parent>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.4.1</version>
</dependency>
<!– <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>
</dependency> –>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<finalName>SpringWithMongoDB</finalName>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url&gt;
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url&gt;
</pluginRepository>
</pluginRepositories>
</project>

 

Application.java

package com.subu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableScheduling
public class Application extends SpringBootServletInitializer {

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

@Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
}

private static Class<Application> applicationClass = Application.class;

}

 

NameController.java

package com.subu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.subu.entity.MultiListType;
import com.subu.entity.NameType;
import com.subu.repository.DBRepository;

@RestController
public class NameController {

@Autowired
private DBRepository dbRepository;

@Autowired
private MongoOperations mongoOperations;
@RequestMapping(value = “/restservice/delete/name”, method = RequestMethod.POST, produces = { MediaType.APPLICATION_XML_VALUE }, headers = “Accept=application/xml”)
public ResponseEntity<?> deleteNameDetails(@RequestBody MultiListType requestParameter,final HttpServletRequest request) throws Exception {

List<NameType> msg = requestParameter.getNameType();
for (NameType nameType : msg) {
Query query = new Query();
query.addCriteria(Criteria.where(“name”).is(nameType.getName()));
NameType nameTypes = mongoOperations.findOne(query, NameType.class);
if (nameTypes == null)
nameTypes = new NameType();
nameTypes.setName(nameType.getName());
nameTypes.setSurname(nameType.getSurname());
nameType.setAddress(nameType.getAddress());
nameType.setPhone(nameType.getPhone());
dbRepository.delete(nameTypes);
}
Map<String, Object> dataMap = new HashMap<>();
dataMap.put(“message”, “Name Details Deleted successfully”);
return ResponseEntity.ok(dataMap);
}

}

 

MultiListType.java

package com.subu.entity;

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

public class MultiListType {

private List<NameType> nameType;

public List<NameType> getNameType() {
if (nameType == null) {
nameType = new ArrayList<>();
}
return this.nameType;
}

}

 

NameType.java

package com.subu.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = “name”)
public class NameType {

@Id
private String id;
private String name;
private String surname;
private String address;
private String phone;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSurname() {
return surname;
}

public void setSurname(String surname) {
this.surname = surname;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

}

 

DBRepository.java

package com.subu.repository;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import com.subu.entity.NameType;

public interface DBRepository extends MongoRepository<NameType, String> {

List<NameType> findByName(String name);
}

 

application.properties

spring.data.mongodb.database=test
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

 

Request

deletedetails

 

Data Before Deleting

beforedelete

Data After Deleting

afterdelete

Spring Boot with Mongo DB ( Update Data )

pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.subu</groupId>
<artifactId>SpringWithMongoDB</artifactId>
<packaging>war</packaging>
<parent>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.4.1</version>
</dependency>
<!– <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>
</dependency> –>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<finalName>SpringWithMongoDB</finalName>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url&gt;
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url&gt;
</pluginRepository>
</pluginRepositories>
</project>

 

Application.java

package com.subu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableScheduling
public class Application extends SpringBootServletInitializer {

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

@Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
}

private static Class<Application> applicationClass = Application.class;

}

 

NameController.java

package com.subu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.subu.entity.MultiListType;
import com.subu.entity.NameType;
import com.subu.repository.DBRepository;

@RestController
public class NameController {

@Autowired
private DBRepository dbRepository;

@Autowired
private MongoOperations mongoOperations;

@RequestMapping(value = “/restservice/name”, method = RequestMethod.POST, produces = { MediaType.APPLICATION_XML_VALUE }, headers = “Accept=application/xml”)
public ResponseEntity<?> updateNameDetails(
@RequestBody MultiListType requestParameter,
final HttpServletRequest request) throws Exception {

List<NameType> msg = requestParameter.getNameType();
for (NameType nameType : msg) {
Query query = new Query();
query.addCriteria(Criteria.where(“name”).is(nameType.getName()));
NameType nameTypes = mongoOperations.findOne(query, NameType.class);
if (nameTypes == null)
nameTypes = new NameType();
nameTypes.setName(nameType.getName());
nameTypes.setSurname(nameType.getSurname());
nameType.setAddress(nameType.getAddress());
nameType.setPhone(nameType.getPhone());
dbRepository.save(nameTypes);
}
Map<String, Object> dataMap = new HashMap<>();
dataMap.put(“message”, “Name Details Updated successfully”);
return ResponseEntity.ok(dataMap);
}

}

 

MultiListType.java

package com.subu.entity;

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

public class MultiListType {

private List<NameType> nameType;

public List<NameType> getNameType() {
if (nameType == null) {
nameType = new ArrayList<>();
}
return this.nameType;
}

}

 

NameType.java

package com.subu.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = “name”)
public class NameType {

@Id
private String id;
private String name;
private String surname;
private String address;
private String phone;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSurname() {
return surname;
}

public void setSurname(String surname) {
this.surname = surname;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

}

 

DBRepository.java

 

package com.subu.repository;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import com.subu.entity.NameType;

public interface DBRepository extends MongoRepository<NameType, String> {

List<NameType> findByName(String name);
}

 

application.properties

spring.data.mongodb.database=test
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

 

Request:

updaterequest

 

Before DB Update

beforeupdate

After DB Update

afterupdate

Sprint Boot with Mongo DB ( View Data )

Code:

pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.subu</groupId>
<artifactId>SpringWithMongoDB</artifactId>
<packaging>war</packaging>
<parent>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.4.1</version>
</dependency>
<!– <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> –>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<finalName>SpringWithMongoDB</finalName>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url&gt;
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url&gt;
</pluginRepository>
</pluginRepositories>
</project>

 

Application.java

package com.subu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableScheduling
public class Application extends SpringBootServletInitializer{

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

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
private static Class<Application> applicationClass = Application.class;

}

 

NameController.java

package com.subu.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.subu.entity.NameType;
import com.subu.repository.DBRepository;

@RestController
public class NameController {

@Autowired
private DBRepository dbRepository;

@RequestMapping(value = “/restservice/name/{id}”, method = RequestMethod.GET,produces={MediaType.APPLICATION_XML_VALUE},headers = “Accept=application/xml”)
public ResponseEntity<?> viewNameDetails(@PathVariable String id, final HttpServletRequest request)throws Exception {
List<NameType> msg=dbRepository.findByNameId(id);
return ResponseEntity.ok(msg);
}
}

 

NameType.java

package com.subu.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = “names”)
public class NameType {

@Id
private String id;
private String nameId;
private String name;
private String surname;
public String getNameId() {
return nameId;
}
public void setNameId(String nameId) {
this.nameId = nameId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}

 

DBRepository.java

package com.subu.repository;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import com.subu.entity.NameType;

public interface DBRepository extends MongoRepository<NameType, String> {

List<NameType> findByNameId(String id);
}

 

 

application.properties ( keep it under src/main/resources )

spring.data.mongodb.database=test
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

 

MONGODB:

mongodatabase

 

RESPONSE

 

mongodb

 

 

Spring Boot REST with XML ( Use Spring-Data-Rest to return response as XML )

Well with latest Spring IO Platform we can achieve this and with IO Platform we dont need to worry about version also.

CODE:

Pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.subu</groupId>
<artifactId>SpringBootExamples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.4.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Person.java

package com.subu;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.*;

@Entity
@XmlRootElement(name = “person”)
@Table(name=”person”)

public class Person implements Serializable{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Long id;

@XmlAttribute(name = “first-name”)
private String first_name;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getFirst_name() {
return first_name;
}

public void setFirst_name(String first_name) {
this.first_name = first_name;
}

public String getLast_name() {
return last_name;
}

public void setLast_name(String last_name) {
this.last_name = last_name;
}

public String getDate_of_birth() {
return date_of_birth;
}

public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}

@XmlAttribute(name = “last-name”)
private String last_name;

@XmlAttribute(name = “dob”)
private String date_of_birth;

}

 

Application.java

package com.subu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableScheduling
public class Application extends SpringBootServletInitializer{

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

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
private static Class<Application> applicationClass = Application.class;

}

 

PersonController.java

package com.subu;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonController {

@Autowired
private PersonRepository personRepository;

@RequestMapping(value = “/persons/{id}”, method = RequestMethod.GET,produces={MediaType.APPLICATION_XML_VALUE},headers = “Accept=application/xml”)
public ResponseEntity<?> getPersonDetails(@PathVariable Long id, final HttpServletRequest request)throws Exception {
Person personResponse=personRepository.findPersonById(id);
return ResponseEntity.ok(personResponse);
}}

 

PersonRepository.java

package com.subu;

import java.util.List;

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

public interface PersonRepository extends JpaRepository<Person, Long> {

Person findPersonById(Long id);

}

JpaConfiguration.java

package com.subu;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.eclipse.persistence.config.BatchWriting;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = “com.subu”)
public class JpaConfiguration extends JpaBaseConfiguration {

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(final EntityManagerFactoryBuilder builder) {
final LocalContainerEntityManagerFactoryBean ret =
builder.dataSource(dataSource())
.packages(“com.subu”)
.properties(jpaProperties())
.persistenceUnit(“com.subu”)
.build();
return ret;
}

@Bean
public DataSource dataSource() {
// In classpath from spring-boot-starter-web
final Properties props = new Properties();
props.put(“driverClassName”, “com.mysql.jdbc.Driver”);
props.put(“jdbcUrl”, “jdbc:mysql://localhost:3306/master?createDatabaseIfNotExist=false”);
props.put(“username”, “root”);
props.put(“password”, “mysql”);
HikariConfig hc = new HikariConfig(props);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}

@Bean
public Map<String, String> jpaProperties() {
Map<String, String> props = new HashMap<>();
props.put(“eclipselink.weaving”, “false”);
props.put(“eclipselink.logging.level.sql”, “FINE”);
props.put(“eclipselink.logging.parameters”, “true”);
props.put(“javax.persistence.schema-generation.database.action”, “create”);
//props.put(“javax.persistence.sql-load-script-source”, “sql/import.sql”);
return props;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
final MultiTenantJpaTransactionManager transactionManager = new MultiTenantJpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}

@Override
protected AbstractJpaVendorAdapter createJpaVendorAdapter() {
return new EclipseLinkJpaVendorAdapter();
}

@Override
protected Map<String, Object> getVendorProperties() {
final Map<String, Object> ret = new HashMap<>();
ret.put(PersistenceUnitProperties.BATCH_WRITING, BatchWriting.JDBC);
return ret;
}
}

MultiTenantJpaTransactionManager.java

package com.subu;

import java.io.Serializable;
import javax.persistence.EntityManager;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class MultiTenantJpaTransactionManager extends JpaTransactionManager {

@Override
protected void doBegin(final Object transaction, final TransactionDefinition definition) {
super.doBegin(transaction, definition);
final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager
.getResource(getEntityManagerFactory());
final EntityManager em = emHolder.getEntityManager();

}
}

SecurityConfig.java

 

package com.subu;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(“user1”).password(“user1”).roles(“USER”)
.and()
.withUser(“user2”).password(“secret2”).roles(“USER”);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated();
http.httpBasic();
http.csrf().disable();
}
}

EnableWebMvcSecurity.java

package com.subu;

public @interface EnableWebMvcSecurity {

}

 

TABLE:

tabletable1table2

 

OUTPUT :

xml

WatchService in Java 7

                                                File change notifications

In JDK 7 release , the addition of File Change Notifications finally carved into NIO 2.0.The WatchService API lets you receive notification events upon changes in file under a Directory  i.e on creation, modification and deletion of file.

There are 3 events to watch for:

ENTRY_CREATE
ENTRY_DELETE
ENTRY_MODIFY
The steps involved are:

i) Create a WatchService object which consists of a queue to hold WatchKeys

WatchService watchService =FileSystems.getDefault().newWatchService();

ii) Get Path to the watchable directory

Path path= Paths.get(“C:\\User\\code\\watchservice\\”);

iii) We need to register the directory to this WatchService and need to specify the types of events

path.register((watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);

iv) Start a loop to listen to Events and Iterate through the keys

WatchKey key = watchService.take(); // this will return the keys

v) We will then call the pollEvents method to retrieve all the events for this WatchKey object

WatchEvent<?> event : key.pollEvents()

vi) Returns the event type

WatchEvent.Kind<Path> kind = watchEvent.kind();

vii) The reset method sets the WatchKey state back to “ready” and returns a boolean indicating if the WatchKey is still valid or not.This is the most import part of Watch Service functionality.

key.reset();

 

CODE:

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.StandardWatchEventKinds;

public class WatchServiceJava7Feature {

public static void main(String[] args) throws Exception {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path= Paths.get(“C:\\User\\code\\watchservice\\”);
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
while(true)
{
WatchKey key = watchService.take(); // this will return the keys
for(WatchEvent<?> event : key.pollEvents())
{
WatchEvent<Path> watchEvent = (WatchEvent<Path>) event;
WatchEvent.Kind<Path> kind = watchEvent.kind();
switch(kind.name()) {
case “ENTRY_MODIFY”:
System.out.println(“Case Modify :Event on “+ event.context().toString() + ” is “+ kind);
break;
case “ENTRY_DELETE”:
System.out.println(“Case Delete :Event on “+ event.context().toString() + ” is “+ kind);
break;
case “ENTRY_CREATE”:
System.out.println(“Case Create :Event on “+ event.context().toString() + ” is “+ kind);
break;
}

}
key.reset();
}

}}

 

OUTPUT:

Case Create :Event on New Text Document.txt is ENTRY_CREATE
Case Delete :Event on New Text Document.txt is ENTRY_DELETE
Case Modify :Event on New Text Document (2).txt is ENTRY_MODIFY

 

 

 

How to get HTTP response for a URL in Java?

Response:

log4j: Threshold =”null”.
log4j: Level value for root is [info].
log4j: root level set to INFO
log4j: Class name: [org.apache.log4j.RollingFileAppender]
log4j: Setting property [maxFileSize] to [10000KB].
log4j: Setting property [maxBackupIndex] to [3].
log4j: Parsing layout of class: “org.apache.log4j.PatternLayout”
log4j: Setting property [conversionPattern] to [%d [%d{yyyy-MM-dd HH:mm:ss:SSS Z}] [%t] %-5p %c %L – %m %n].
log4j: setFile ended
log4j: Adding appender named [] to category [root].
Response–>STATUS 200

Code:

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public class HttpResponseCheck {
private static final Logger logger = HttpResponseCheckLogger.getLogger(HttpResponseCheck.class);

public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
// args[0] =http://hostname:port/xyz/zbc
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
// Read in all of the post results into a String.
String output = “”;
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println(“Response–>” + output);
}

catch (Exception e) {
System.out.println(“Exception” + e);

}}}

 

Reverse XML tags using java

Many times we need to reverse the xml tag

</Request>
</name>
</address>
<pincode>123456</pincode>
<area>ABC</area>
<flat>XYZ</flat>
<address>
<name>
<Request>

as below :

<Request>
<name>
<address>
<flat>XYZ</flat>
<area>ABC</area>
<pincode>123456</pincode>
</address>
</name>
</Request>

 

Steps:

 

reverserequest

  1. Create a xml with reverse request
  2. Click on ReverseXMLrequest.bat

 

      3. Enter the source file and destination file path

reverserequest_batch

4) The File with correct xml will be generated in destination path.

 

Code:

==================================

  1. Create a Mavenized project.
  2. Add dependencies jars like commons-io
  3. pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.subhasish</groupId>
<artifactId>ReverseXMLRequest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>

<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net repository</name>
<url>http://download.java.net/maven/2</url&gt;
</repository>
</repositories>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>attached</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<mainClass>com.subhasish.ReverseXMLRequest</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<finalName>ReverseXMLRequest</finalName>
</build>
</project>

 

4) ReverseXMLRequest.java

package com.subhasish;

import org.apache.commons.io.input.*;
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import javax.xml.transform.*;
import javax.xml.parsers.*;
public class ReverseXMLRequest {

public static void main(String[] args) throws ParserConfigurationException,IOException,SAXException,TransformerException{
String ch;
String destinationPath=args[1];
String tempPath=”C://temp.xml”;
try(ReversedLinesFileReader fr = new ReversedLinesFileReader(new File(args[0]));)
{
Path path = Paths.get(tempPath);
Files.deleteIfExists(path);
Files.createFile(path);
do {
ch = fr.readLine();
Files.write(path, ch.getBytes(),StandardOpenOption.APPEND);

} while (ch != null);
}
catch(Exception e)
{
formatXML(tempPath,destinationPath);
}}

public static void formatXML(String path,String destinationPath) throws IOException
{
Path deletePath = Paths.get(path);
try
{
final InputSource src = new InputSource(new FileInputStream(new File(path)));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation(“LS”);
final LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter(“format-pretty-print”,Boolean.TRUE);
LSOutput lsOutput = impl.createLSOutput();
lsOutput.setEncoding(“UTF-8”);
Writer stringWriter = new StringWriter();
lsOutput.setCharacterStream(stringWriter);
writer.write(document, lsOutput);
String result = stringWriter.toString();
Path formattedpath = Paths.get(destinationPath);
Files.createFile(formattedpath);
Files.deleteIfExists(deletePath);
Files.write(formattedpath, result.getBytes(),StandardOpenOption.APPEND);
System.out.println(“DONE”);
} catch (Exception e)
{
Files.deleteIfExists(deletePath);
}
}}

 

5)  ReverseXMLrequest.bat

@echo off
set /p sourceinput=”Enter Source Path::”
set /p destinput=”Enter Destination Path::”
java -jar ReverseXMLRequest.jar %sourceinput% %destinput%
pause