Repository save() is not working - spring

I am currently playing around with spring-data-neo4j and have a really weird behaviour around persisting data.
I read the Getting Started guide and looked through the Good Relationships: The Spring Data Neo4j Guide Book. Loading existing nodes works, after getting rid of smaller issues and imperfections (like using spring-ogm 1.1.4 to get rid of the neo4j-server dependency).
Let's have a look on my code...
This is entity:
package sdn.test.model;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
#NodeEntity
public class TestUser {
#GraphId
private Long id;
private String username;
private String password;
public TestUser() {
}
public TestUser(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestUser testUser = (TestUser) o;
if (getId() != null ? !getId().equals(testUser.getId()) : testUser.getId() != null) return false;
if (getUsername() != null ? !getUsername().equals(testUser.getUsername()) : testUser.getUsername() != null)
return false;
return getPassword() != null ? getPassword().equals(testUser.getPassword()) : testUser.getPassword() == null;
}
#Override
public int hashCode() {
int result = getId() != null ? getId().hashCode() : 0;
result = 31 * result + (getUsername() != null ? getUsername().hashCode() : 0);
result = 31 * result + (getPassword() != null ? getPassword().hashCode() : 0);
return result;
}
#Override
public String toString() {
return "TestUser{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
"}";
}
}
And this is my repository:
package sdn.test.repository;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import sdn.test.model.TestUser;
#Repository
public interface UserRepository extends GraphRepository<TestUser> {
#Query("MATCH (user:TestUser{username: {username}, password: {password}}) RETURN user")
TestUser findByUsernameAndPassword(#Param("username") String username, #Param("password") String password);
}
Here is the neo4j configuration:
package sdn.test.config;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.server.Neo4jServer;
import org.springframework.data.neo4j.server.RemoteServer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableNeo4jRepositories("sdn.test.repository")
#EnableTransactionManagement
public class Neo4jConfig extends Neo4jConfiguration {
#Bean
#Override
public Neo4jServer neo4jServer() {
return new RemoteServer("http://localhost:7474", "neo4j", "test");
}
#Bean
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("sdn.test.model");
}
}
Everything together lives in a simple Spring Boot application and I try to do the entity creation in this test class:
package sdn.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import sdn.test.config.Neo4jConfig;
import sdn.test.model.TestUser;
import sdn.test.repository.UserRepository;
import java.util.Date;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {
Neo4jConfig.class})
public class SimpleNeo4jTests {
#Autowired
private UserRepository userRepository;
#Test
public void createNewUser() {
long timeOffset = (new Date()).getTime();
String username = "test" + timeOffset;
String password = "password#" + timeOffset;
TestUser newUser = new TestUser(timeOffset, username, password);
userRepository.save(newUser);
// Try to load the user
TestUser actualUser = userRepository.findByUsernameAndPassword(username, password);
assertThat(actualUser, equalTo(newUser));
}
}
Last but not least, here is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.h0lg.test</groupId>
<artifactId>simple-sdn4-test</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
There is no error thrown when I call userRepository.save() and checking the "remote" server confirms the red test result.
Explicitly giving the label name with #GraphEntity(label = "TestUser") doesn't help. Using transactions explicitly didn't help either.
Any ideas and hints are highly appreciated.

Looks like you're setting the #GraphId of your TestUser node entity via the test:
TestUser newUser = new TestUser(timeOffset, username, password);
public TestUser(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
Application code should never assign a value to the #GraphId. Could you remove that and see if it helps?

Related

Optimistic locking Test in spring data JPA

I'm trying to test the optimistic locking mechanism in spring data jpa by loading a certain entity twice using findBy function, then updating the first one and asserting that when the second one is updated, it will throw an OptimisticLockingFailureException.
But the problem is that no exception is thrown and the second update is done successfully.
After investigation i found that findBy function hits the database only the first time and caches the returned entity. and when i call it again it returns cached entity. which means that both loaded entities are equal. so the first update reflects in both entities making the second entity does not have the stale data.
so, how do i force loading the second entity from the data base in the second findBy function call ?
Here is my code:-
Test class
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class PersistenceTests {
#Autowired
private ProductRepository repository;
private ProductEntity savedEntity;
#DynamicPropertySource
static void databaseProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", () -> "jdbc:mysql://localhost:3306/code_snippet");
registry.add("spring.datasource.username", () -> "root");
registry.add("spring.datasource.password", () -> "System");
registry.add("spring.jpa.hibernate.ddl-auto", () -> "create-drop");
}
#BeforeEach
void setupDb() {
repository.deleteAll();
ProductEntity entity = new ProductEntity(1, "n", 1);
savedEntity = repository.save(entity);
assertEqualsProduct(entity, savedEntity);
}
#Test
void optimisticLockError() {
// Store the saved entity in two separate entity objects
ProductEntity entity1 = repository.findById(savedEntity.getId()).get();
ProductEntity entity2 = repository.findById(savedEntity.getId()).get();
// Update the entity using the first entity object
entity1.setName("n1");
repository.save(entity1);
// Update the entity using the second entity object.
// This should fail since the second entity now holds an old version number,
// i.e. an Optimistic Lock Error
assertThrows(OptimisticLockingFailureException.class, () -> {
entity2.setName("n2");
repository.save(entity2);
});
// Get the updated entity from the database and verify its new sate
ProductEntity updatedEntity = repository.findById(savedEntity.getId()).get();
assertEquals(1, (int) updatedEntity.getVersion());
assertEquals("n1", updatedEntity.getName());
}
private void assertEqualsProduct(ProductEntity expectedEntity, ProductEntity actualEntity) {
assertEquals(expectedEntity.getId(), actualEntity.getId());
assertEquals(expectedEntity.getVersion(), actualEntity.getVersion());
assertEquals(expectedEntity.getProductId(), actualEntity.getProductId());
assertEquals(expectedEntity.getName(), actualEntity.getName());
assertEquals(expectedEntity.getWeight(), actualEntity.getWeight());
}
}
Entity
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
#Entity
#Table(name = "product")
public class ProductEntity {
#Id
#GeneratedValue
private Integer id;
#Version
private Integer version;
private int productId;
private String name;
private int weight;
public ProductEntity() {
}
public ProductEntity(int productId, String name, int weight) {
this.productId = productId;
this.name = name;
this.weight = weight;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
Repository
import java.util.Optional;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ProductRepository extends PagingAndSortingRepository<ProductEntity, Integer> {
Optional<ProductEntity> findByProductId(int productId);
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.javaworld.codesnippet</groupId>
<artifactId>writing-persistence-tests</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>writing-persistence-tests</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Main Class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class WritingPersistenceTestsApplication {
public static void main(String[] args) {
SpringApplication.run(WritingPersistenceTestsApplication.class, args);
}
}
The problem is that your test method is by default transactional. You can disable the transactional for this method by adding:
#Test
#Transactional(value = Transactional.TxType.NEVER)
Than you get in the second save ObjectOptimisticLockingFailureException

Not able to save data in cosmos db through spring boot micro service

i'm trying to save entity in cosmos db through spring boot micro service. I'm not getting any error, only 1 warning '[osEventLoop-6-1] c.a.d.c.i.d.rntbd.RntbdRequestManager : ChannelHandlerContext(RntbdRequestManager#0, [id: 0x999bfbac, L:0.0.0.0/0.0.0.0:56979 ! R:cdb-ms-prod-*****-****.documents.azure.com/********]) channelUnregistered exceptionally'
but data is not getting saved in cosmos db. i'm using reactivecosmosrepository.
here is my pom.xml
<properties>
<java.version>1.8</java.version>
<azure.version>2.2.0</azure.version>
</properties>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-cosmosdb-spring-boot-starter</artifactId>
<version>${azure.version}</version>
</dependency>
my entity
import com.microsoft.azure.spring.data.cosmosdb.core.mapping.Document;
#Document(collection = "dashboardsnapshot")
public class DashboardSnapshot {
private String id;
private String clientId;
private String snapshotJSON;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSnapshotJSON() {
return snapshotJSON;
}
public void setSnapshotJSON(String snapshotJSON) {
this.snapshotJSON = snapshotJSON;
}
#Override
public String toString() {
return "DashboardSnapshot [id=" + id + ", clientId=" + clientId + ", snapshotJSON=" + snapshotJSON + "]";
}
}
my repository
import org.springframework.stereotype.Repository;
import com.ka.concept.dashboardconfig.entity.DashboardSnapshot;
import com.microsoft.azure.spring.data.cosmosdb.repository.ReactiveCosmosRepository;
import reactor.core.publisher.Flux;
#Repository
public interface SnapshotDao extends ReactiveCosmosRepository<DashboardSnapshot, String>{
Flux<DashboardSnapshot> findbyClientId(String ClientId);
}
my service
#Service
public class SnapshotServiceImpl implements SnapshotService{
#Autowired
public SnapshotDao snapshotdao;
#Override
public boolean saveSnapshotConfig(DashboardSnapshot snapshotJSON) {
// TODO Auto-generated method stub
snapshotdao.save(snapshotJSON);
return true;
}
}
#AksYou should call subscribe(). The publisher does not do anything till some one subscribes.
snapshotdao.save(snapshotJSON).subscribe();

How to create a set of user defined types using spring data cassandra?

I am using Spring Data Cassandra 1.5.8.RELEASE to connect with my cassandra db 3.11.2.
I tried creating #Table pojo with a Set as a column field but it is throwing the following errors:
user defined type not found, and
some other cassandra mapping exceptions.
Can somebody help me in data modeling an 'Employee' table having a column that represents a set of Department UDTs? (Using spring boot, spring data cassandra 1.5.8+ and Apache cassandra 3.11.2+)
Firstly, my main problem was with CassandraConfig.java, where I was un-necessarily overriding certain methods, where as the default implementation itself was more than enough.
Here, I am posting my complete solution for the benefit of those who are trying this use-case for the very first time.
Project Folder Structure:
Step 1: Creating cassandra data models:
CREATE KEYSPACE cassandra_sample
WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};
CREATE TYPE dept_details (
dept_name text,
dept_address text
);
CREATE TABLE emp_details (
emp_id int PRIMARY KEY,
emp_name text,
emp_designation text,
dept_info set<frozen<dept_details>>
);
Step 2: pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cassandra.sample</groupId>
<artifactId>spring-data-cassandra-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringDataCassandraSample</name>
<description>SpringDataCassandraSample</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
</project>
Step 3: Application.java
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Step 4: application.properties
# ===============================
# == DATA SOURCE
# ===============================
spring.data.cassandra.keyspace-name=cassandra_sample
spring.data.cassandra.contact-points=localhost
spring.data.cassandra.port=9042
spring.data.cassandra.schema-action=create_if_not_exists
Step 5: CassandraConfig.java
package com.cassandra.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
/**
* Created by jt on 10/6/17.
*/
#Configuration
public class CassandraConfig extends AbstractCassandraConfiguration {
#Value("${spring.data.cassandra.keyspace-name}")
private String keyspaceName;
#Override
protected String getKeyspaceName() {
return keyspaceName;
}
}
Step 6: Department.java
package com.cassandra.sample.domain;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.UserDefinedType;
#UserDefinedType("dept_details")
public class Department {
#Column("dept_name")
private String departmentName;
#Column("dept_address")
private String departmentAddress;
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentAddress() {
return departmentAddress;
}
public void setDepartmentAddress(String departmentAddress) {
this.departmentAddress = departmentAddress;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((departmentAddress == null) ? 0 : departmentAddress.hashCode());
result = prime * result + ((departmentName == null) ? 0 : departmentName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Department other = (Department) obj;
if (departmentAddress == null) {
if (other.departmentAddress != null)
return false;
} else if (!departmentAddress.equals(other.departmentAddress))
return false;
if (departmentName == null) {
if (other.departmentName != null)
return false;
} else if (!departmentName.equals(other.departmentName))
return false;
return true;
}
}
Step 7: Employee.java
package com.cassandra.sample.domain;
import java.util.Set;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
#Table("emp_details")
public class Employee {
#PrimaryKey("emp_id")
private int employeeId;
#Column("emp_name")
private String employeeName;
#Column("emp_designation")
private String designation;
#Column("dept_info")
private Set<Department> departmentDetails;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public Set<Department> getDepartmentDetails() {
return departmentDetails;
}
public void setDepartmentDetails(Set<Department> departmentDetails) {
this.departmentDetails = departmentDetails;
}
}
Step 8: EmployeeRepository.java
package com.cassandra.sample.repository;
import org.springframework.data.cassandra.repository.CassandraRepository;
import com.cassandra.sample.domain.Employee;
public interface EmployeeRepository extends CassandraRepository<Employee> {
Employee findByEmployeeId(int employeeId);
void deleteByEmployeeId(Integer employeeId, Class<Employee> employee) ;
}
Step 9: EmployeeRepositoryTest.java
package com.cassandra.sample.repository;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.cassandra.sample.domain.Department;
import com.cassandra.sample.domain.Employee;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class EmployeeRepositoryTest {
#Autowired
private EmployeeRepository employeeRepository;
// Note: Comment or UnComment the test methods as per the db-operation you are performing
/*#Test
public void insertEmployee(){
Employee employee = prepareEmployee();
employeeRepository.save(employee);
}*/
#Test
public void retrieveEmployee(){
Iterable<Employee> employees=employeeRepository.findAll();
for(Employee emp:employees){
System.out.println("Employee name :"+emp.getEmployeeName());
Set<Department> departments=emp.getDepartmentDetails();
for(Department dept:departments){
System.out.println("Department Name :"+dept.getDepartmentName());
}
}
}
/*#Test
public void updateEmployee(){
Employee employee=employeeRepository.findByEmployeeId(421);
employee.setEmployeeName("Test Employee Updated");
employee.setDesignation("SSE");
Set<Department> departments=employee.getDepartmentDetails();
Department department1=new Department();
department1.setDepartmentName("Civil");
department1.setDepartmentAddress("Test Dept Addr 3");
departments.add(department1);
employee.setDepartmentDetails(departments);
employeeRepository.save(employee);
}*/
/*#Test
public void deleteEmployee(){
employeeRepository.delete(employeeRepository.findByEmployeeId(421));
}*/
private Employee prepareEmployee() {
Set<Department> departments = prepareDepartments();
Employee employee=new Employee();
employee.setEmployeeId(421);
employee.setEmployeeName("Test Employee");
employee.setDesignation("Tech Lead");
employee.setDepartmentDetails(departments);
return employee;
}
private Set<Department> prepareDepartments() {
Set<Department> departments=new HashSet<>();
Department department1=new Department();
department1.setDepartmentName("EEE");
department1.setDepartmentAddress("Test Dept Addr 1");
departments.add(department1);
Department department2=new Department();
department2.setDepartmentName("CSE");
department2.setDepartmentAddress("Test Dept Addr 2");
departments.add(department2);
return departments;
}
}

Spring boot interacts with Postgresql on different machine

I am new to Spring boot .I want to integrate my flow to read or insert data in postgressql ,I used crud repository but the save operation does not save anything on my postgresql hosted on a different machine.FindAll and find command also give data added by save operation but not what i added myself on Data base
Application.properties
spring.datasource.url= jdbc:postgresql://160.110.67.94:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.generate-ddl=true
Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.experian.model.RiskScoreBusinessRules;
import com.experian.repo.RiskScoreBusinessRulesRepository;
#RestController
public class WebController {
#Autowired
RiskScoreBusinessRulesRepository repository;
#RequestMapping("/save")
public String process(){
repository.save(new RiskScoreBusinessRules("Inherent Risks","Client`s business based risks", "Demographic","Client Location","Border crossings (airports, ports, marinas, Land border-crossings",120,"<89","89 to 178", ">178", "BR "));
//repository.save(new RiskScoreBusinessRules("Adam", "Johnson"));
// repository.save(new RiskScoreBusinessRules("Kim", "Smith"));
// repository.save(new RiskScoreBusinessRules("David", "Williams"));
// repository.save(new RiskScoreBusinessRules("Peter", "Davis"));
return "Done";
}
// public static final String customer_uri = "riskScore";
#RequestMapping("/findall")
public String findAll(){
String result = "<html>";
for(RiskScoreBusinessRules riskBR : repository.findAll()){
result += "<div>" + riskBR.toString() + "</div>";
}
return result + "</html>";
}
#RequestMapping("/findbyGroupName")
public String fetchDataByGroupName(#RequestParam("groupName") String groupName){
String result = "<html>";
for(RiskScoreBusinessRules riskBR: repository.findByGroupName(groupName)){
result += "<div>" + riskBR.toString() + "</div>";
}
return result + "</html>";
}
}
model
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "RiskScoreBusinessRules")
public class RiskScoreBusinessRules implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "groupName")
private String groupName;
#Column(name = "categorization")
private String categorization ;
#Column(name = "subCategorization")
private String subCategorization;
#Column(name = "riskAttribute")
private String riskAttribute;
#Column(name = "parameters")
private String parameters;
#Column(name = "weighting")
private float weighting ;
#Column(name = "normalisedScore")
private float normalisedScore;
#Column(name = "maximumScore")
private float maximumScore;
#Column(name = "actualScore")
private int actualScore;
#Column(name = "lowValue")
private String lowValue ;
#Column(name = "mediumValue")
private String mediumValue ;
#Column(name = "maxValue")
private String maxValue ;
#Column(name = "lastUpdatedBy")
private String lastUpdatedBy;
public RiskScoreBusinessRules(String groupName, String categorization, String subCategorization,
String riskAttribute, String parameters, int actualScore, String lowValue, String mediumValue, String maxValue, String lastUpdatedBy)
//float weighting, float normalisedScore, float maximumScore,
{
super();
this.groupName = groupName;
this.categorization = categorization;
this.subCategorization = subCategorization;
this.riskAttribute = riskAttribute;
this.parameters = parameters;
//this.weighting = weighting;
//this.normalisedScore = normalisedScore;
// this.maximumScore = maximumScore;
this.actualScore = actualScore;
this.lowValue = lowValue;
this.mediumValue = mediumValue;
this.maxValue = maxValue;
this.lastUpdatedBy = lastUpdatedBy;
}
#Override
public String toString() {
return "RiskScoreBusinessRules [id=" + id + ", groupName=" + groupName + ", categorization=" + categorization
+ ", subCategorization=" + subCategorization + ", riskAttribute=" + riskAttribute + ", parameters="
+ parameters + ", weighting=" + weighting + ", normalisedScore=" + normalisedScore + ", maximumScore="
+ maximumScore + ", actualScore=" + actualScore + ", lowValue=" + lowValue + ", mediumValue="
+ mediumValue + ", maxValue=" + maxValue + ", lastUpdatedBy=" + lastUpdatedBy + "]";
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getCategorization() {
return categorization;
}
public void setCategorization(String categorization) {
this.categorization = categorization;
}
public String getSubCategorization() {
return subCategorization;
}
public void setSubCategorization(String subCategorization) {
this.subCategorization = subCategorization;
}
public String getRiskAttribute() {
return riskAttribute;
}
public void setRiskAttribute(String riskAttribute) {
this.riskAttribute = riskAttribute;
}
public String getParameters() {
return parameters;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
public float getWeighting() {
return weighting;
}
public void setWeighting(float weighting) {
this.weighting = weighting;
}
public float getNormalisedScore() {
return normalisedScore;
}
public void setNormalisedScore(int normalisedScore) {
this.normalisedScore = normalisedScore;
}
public float getMaximumScore() {
return maximumScore;
}
public void setMaximumScore(float maximumScore) {
this.maximumScore = maximumScore;
}
public int getActualScore() {
return actualScore;
}
public void setActualScore(int actualScore) {
this.actualScore = actualScore;
}
public String getLowValue() {
return lowValue;
}
public void setLowValue(String lowValue) {
this.lowValue = lowValue;
}
public String getMediumValue() {
return mediumValue;
}
public void setMediumValue(String mediumValue) {
this.mediumValue = mediumValue;
}
public String getMaxValue() {
return maxValue;
}
public void setMaxValue(String maxValue) {
this.maxValue = maxValue;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public RiskScoreBusinessRules() {
super();
// TODO Auto-generated constructor stub
}
}
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.experian</groupId>
<artifactId>api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>experianAPI</name>
<description>Demo project for Experian</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF- 8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

how to run this JAXRS-program? what should i do?

I have already spent a month to run this program but did not find any solution.
This is a copied program. I just want to run it at any how.
I wanna run it as rest service. is there any mistake in it ?
Please help .
This is all i have in my project.
Thank you in advance !!
Here is my program :
Coustomer.java
package com.abhi.shek.idea.book;
public class Customer {
private int id;
private String firstName;
private String lastName;
private String street;
private String city;
private String state;
private String zip;
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
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;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Here is my another class :
CustomerResource.java
package com.abhi.shek.idea.book;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
#Path("/customers")
public class CustomerResource{
private Map<Integer, Customer> customerDB = new ConcurrentHashMap<Integer, Customer>();
private AtomicInteger idCounter = new AtomicInteger();
#POST
#Path("/create")
#Consumes("application/xml")
public Response createCustomer(InputStream is) {
Customer customer = readCustomer(is);
customer.setId(idCounter.incrementAndGet());
customerDB.put(customer.getId(), customer);
System.out.println("Created customer " + customer.getId());
return Response.created(
URI.create("/customers/" + customer.getId())).build();
}
#GET
#Path("{name}")
#Produces("MediaType.APPLICATION_JSON")
public StreamingOutput getCustomer(#PathParam("name")String name) {
final Customer customer = customerDB.get(name);
if (customer == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return new StreamingOutput() {
public void write(OutputStream outputStream)
throws IOException, WebApplicationException {
outputCustomer(outputStream, customer);
}
};
}
#PUT
#Path("{id}")
#Consumes("application/xml")
public void updateCustomer(#PathParam("id") int id, InputStream is) {
Customer update = readCustomer(is);
Customer current = customerDB.get(id);
if (current == null)
throw new WebApplicationException(Response.Status.NOT_FOUND);
current.setFirstName(update.getFirstName());
current.setLastName(update.getLastName());
current.setStreet(update.getStreet());
current.setState(update.getState());
}
protected void outputCustomer(OutputStream os, Customer cust)
throws IOException {
PrintStream writer = new PrintStream(os);
writer.println("<customer id=\"" + cust.getId() + "\">");
writer.println("<first-name>" + cust.getFirstName()
+ "</first-name>");
writer.println("<last-name>" + cust.getLastName()
+ "</last-name>");
writer.println("<street>" + cust.getStreet() + "</street>");
writer.println("<city>" + cust.getCity() + "</city>");
writer.println("<state>" + cust.getState() + "</state>");
writer.println("<zip>" + cust.getZip() + "</zip>");
writer.println("<country>" + cust.getCountry() + "</country>");
writer.println("</customer>");
}
protected Customer readCustomer(InputStream is) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(is);
Element root = doc.getDocumentElement();
Customer cust = new Customer();
if (root.getAttribute("id") != null
&& !root.getAttribute("id").trim().equals("")) {
cust.setId(Integer.valueOf(root.getAttribute("id")));
}
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
if (element.getTagName().equals("first-name")) {
cust.setFirstName(element.getTextContent());
}
else if (element.getTagName().equals("last-name")) {
cust.setLastName(element.getTextContent());
}
else if (element.getTagName().equals("street")) {
cust.setStreet(element.getTextContent());
}
else if (element.getTagName().equals("city")) {
cust.setCity(element.getTextContent());
}
else if (element.getTagName().equals("state")) {
cust.setState(element.getTextContent());
}
else if (element.getTagName().equals("zip")) {
cust.setZip(element.getTextContent());
}
else if (element.getTagName().equals("country")) {
cust.setCountry(element.getTextContent());
}
}
return cust;
} catch (Exception e) {
throw new WebApplicationException(e,
Response.Status.BAD_REQUEST);
}
}
}
Here is my third program :
ShoppingApplication.java
package com.abhi.shek.idea.book;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
#ApplicationPath("/services")
public class ShoppingApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ShoppingApplication() {
singletons.add(new CustomerResource());
}
#Override
public Set<Class<?>> getClasses() {
return empty;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
Here is my pom.xml file :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.abhi.shek.idea.book</groupId>
<artifactId>JAXRS-Book</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.9</version>
</dependency>
</dependencies>
And the last web.xml file :
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com /xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JAXRS-Book</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>com.abhi.shek.idea.book.ShoppingApplication</servlet-name>
<servlet-class>
org.glassfish.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.abhi.shek.idea.book.CustomerResource</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>com.abhi.shek.idea.book.ShoppingApplication</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Errors : On the console :
SEVERE: Servlet [RestClient] in web application [/JAXRS-RestClient] threw load() exception
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
another error is :
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init> (RootResourceUriRules.java:99)

Resources