GraphQLMutationResolver ignoring requests - spring-boot

I've been a while trying to figure out why this code doesn't work. That's my first time using GraphQL
On one side, I got the service from another fully working project, so I don't think that's the problem.
When I try to execute the mutation or the query, it responses with a loggin:null or register:null
User.class
#Entity
public class User implements Serializable {
public enum RoleType {USER};
private Long id;
private String userName;
private String password;
private String firstName;
private String lastName;
private String email;
private RoleType role;
public User() {}
public User(String userName, String password, String firstName, String lastName, String email) {
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
//Getters and setters
}
UserServiceImpl
#Service
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
private PermissionChecker permissionChecker;
#Autowired
private BCryptPasswordEncoder passwordEncoder;
#Autowired
private UserDao userDao;
#Override
public User signUp(User user) throws DuplicateInstanceException {
if (userDao.existsByUserName(user.getUserName())) {
throw new DuplicateInstanceException("project.entities.user", user.getUserName());
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setRole(User.RoleType.USER);
userDao.save(user);
return user;
}
#Override
#Transactional(readOnly=true)
public User login(String userName, String password) throws IncorrectLoginException {
Optional<User> user = userDao.findByUserName(userName);
if (!user.isPresent()) {
throw new IncorrectLoginException(userName, password);
}
if (!passwordEncoder.matches(password, user.get().getPassword())) {
throw new IncorrectLoginException(userName, password);
}
return user.get();
}
#Override
#Transactional(readOnly=true)
public User loginFromId(Long id) throws InstanceNotFoundException {
return permissionChecker.checkUser(id);
}
#Override
public User updateProfile(Long id, String firstName, String lastName, String email) throws InstanceNotFoundException {
User user = permissionChecker.checkUser(id);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
return user;
}
#Override
public void changePassword(Long id, String oldPassword, String newPassword)
throws InstanceNotFoundException, IncorrectPasswordException {
User user = permissionChecker.checkUser(id);
if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
throw new IncorrectPasswordException();
} else {
user.setPassword(passwordEncoder.encode(newPassword));
}
}
}
user.graphqls
type User {
id: Int!,
userName: String,
password: String,
firstName: String,
lastName: String,
email: String,
role: RoleType
}
enum RoleType {
USER,
ADMIN
}
type Query {
login(userName: String, password: String): User
}
type Mutation {
register(
userName: String!,
password: String!,
firstName: String!,
lastName: String!,
email: String!
): User
}
UserMutationResolver
#Component
public class UserMutationResolver implements GraphQLMutationResolver {
#Autowired
private UserService userService;
public User register(final String userName, final String password, final String firstName, final String lastName, final String email) throws DuplicateInstanceException {
System.out.println("bump");
User user = new User(userName, password, firstName, lastName, email);
user = userService.signUp(user);
return user;
}
}
UserQueryResolver
#Component
public class UserQueryResolver implements GraphQLQueryResolver{
#Autowired
private UserService userService;
public UserQueryResolver() {
}
public User login(final String user, final String pass) throws IncorrectLoginException {
return userService.login(user, pass);
}
}
The query and mutation calls
mutation {
register(
userName: "asd",
password: "asd",
firstName: "asd",
lastName: "asd",
email: "asd#asd.asd"
) {
role
}
}
query {
login(userName: "test", password:"test") {
id,
userName
}
}
I've created the user "test" on the DB just in case the register is the only one giving problems, but it fails anyways
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.0-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>test.graphql</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test</name>
<description>test</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.14.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.graphql</groupId>
<artifactId>spring-graphql-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>com.coxautodev</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>5.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>

Related

"javax.persistence.SynchronizationType"'s signer information does not match signer information of other classes in the same package

I am trying to connect to Oracle data base using JPA through a Spring Boot Application. I initially got the error saying
java.lang.NoSuchMethodError: javax.persistence.PersistenceContext.synchronization()Ljavax/persistence/SynchronizationType
I did a search on how to recitify the same and found that o resolve the same I should use version from 2.1.0 for the javax.persistence dependency.
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.2.0</version>
</dependency>
Upon changing the same, the error is resolved, but I am getting another error now:
java.lang.SecurityException: class "javax.persistence.SynchronizationType"'s signer information does not match signer information of other classes in the same package
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.in28minutes</groupId>
<artifactId>in28Minutes-first-webapp</artifactId>
<version>2.1.3.RELEASE</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>3.1.2.2</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</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>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>12.1.0.2</version>
</dependency>
<!-- Java 8 = JAX-B Version 2.2.8 added to correct missing entity manager error-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</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>
<verbose>true</verbose>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<contextReloadable>true</contextReloadable>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
My application class:
package com.myfirst.classes.from.db;
import java.util.Date;
//import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
//import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Component;
//import com.example.database.databasejdbcdemo.SpringDataDemoApplication;
/*#EnableAutoConfiguration(exclude = {
JndiConnectionFactoryAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
JpaRepositoriesAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
SecurityAutoConfiguration.class,DataSourceAutoConfiguration.class })*/
//#EnableJpaRepositories(basePackages="com.myfirst.classes.from.db")
#ComponentScan("com.myfirst.classes.from.db")
#SpringBootApplication
public class SpringDataDemoApplication implements CommandLineRunner{
//private org.slf4j.Logger logger= LoggerFactory.getLogger(this.getClass());
#Autowired
PersonSpringDataRepository repository ;
public static void main(String[] args) {
SpringApplication.run(SpringDataDemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("hello");
//logger.info("Person with ID 10002 ->{}",repository.findById(10002));
//logger.info("Updating person with ID 10002 ->{}",repository.save(new Person(10002,"Kunjol","Home",new Date())));
//logger.info("Person with ID 10002 ->{}",repository.findById(10002));
//logger.info("Inserting a new person now ->{}",repository.save(new Person(10007,"Karthik","Home",new Date())));
//logger.info("Person with ID 10007 ->{}",repository.findByName("Karthik"));
//repository.deleteById(10001);
//logger.info("Person with ID 10001 ->{}",repository.findById(10001));
}
}
PersonSpringDataRepository.java
package com.myfirst.classes.from.db;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Component
#Transactional
public interface PersonSpringDataRepository extends JpaRepository<Person,Integer> {
}
And the Person.java
package com.myfirst.classes.from.db;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
#Entity
#Table(name="person")
#Configuration
#ConfigurationProperties("oracle")
public class Person {
// private EntityManagerFactory entityManagerFactory;
#Id
#GeneratedValue
// #Bean
private int id;
private String name;
private String location;
private Date birth_date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getBirth_date() {
return birth_date;
}
public void setBirth_date(Date birth_date) {
this.birth_date = birth_date;
}
public Person(int id, String name, String location, Date birth_date) {
super();
this.id = id;
this.name = name;
this.location = location;
this.birth_date = birth_date;
}
public Person( String name, String location, Date birth_date) {
super();
this.name = name;
this.location = location;
this.birth_date = birth_date;
}
public Person()
{
//By default, Spring will try to instantiate beans by calling a default (no-arg) constructor.
}
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", location=" + location + ", birth_date=" + birth_date + "]";
}
}
What could be the possible reason for the issue? Any help would be highly appreciated.
I have the same error now. The root cause is that eclipselink jar contains class javax.persistence.SynchronizationType, but it also brings another dependency (jakarta.persistence) which also contains the same class - and the one that actually gets used is from other jar (and signed by other cert) than the rest of the package.
With that said, I could not find a straight solution for this. IMO the problem is in eclipselink bringing the same class twice and until that is fixed, we can only look for workarounds.
EDIT: Here is another thread which has a solution (exclude JPA API from eclipselink and bring in another one which isn't signed)
Ended up excluding jakarta.persistence in favor of hibernate-jpa-2.1-api jar and that worked!
Until, EL team becomes active and respond to https://bugs.eclipse.org/bugs/show_bug.cgi?id=549240

Not able to run the starter guide code of Building Spring Boot Rest Service

I am trying to build rest service using Spring Boot. I am learning to implement it using the this Spring's guide. I have built the application using STS as a Maven application and the code is exact replica of the guide and when I try to run the application I get the below connection error
I also tried to run the github code for the same guide provided by Spring and that code also gives same the error as above. I am new to Spring Boot and any help would be appreciated.
Below is my code
App.java
package Greetings.Web_Services;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App
{
public static void main( String[] args )
{
System.out.println("App Started");
SpringApplication.run(App.class, args);
}
}
Greetings.java
package Greetings.Web_Services;
public class Greetings {
private final long id;
private final String content;
public Greetings(long id, String content){
this.id = id;
this.content = content;
}
public long getId(){
return id;
}
public String getContent(){
return content;
}
}
GreetingsController.java
package Greetings.Web_Services;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingsController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greetings greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greetings(counter.incrementAndGet(),
String.format(template, name));
}
}
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>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
GitHub link for the project of above code
Thanks!!
The code in the guide is correct and it was not working earlier for which I had also raised an issue in the GitHub community of the guide. Later when I updated the STS and restarted, it seems to work now. One of the modifier in the community also recommended the same after I explained the scenario. Hope this saves someone's time.

How to save single document to Elasticsearch index?

I am trying to put into my ES index mapping an exemplary two fielded book class entity like below. As a result I ONLY get the index and mapping created but the JSON is not put in the place.
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class ElasticSearchTransactionsApplicationTests {
#Autowired
private BookRepository bookRepository;
#Autowired
private ElasticsearchTemplate elasticsearchTemplate;
#Test
public void shouldCreateSingleBookEntityWitRepository(){
elasticsearchTemplate.deleteIndex(Book.class);
elasticsearchTemplate.createIndex(Book.class);
elasticsearchTemplate.putMapping(Book.class);
elasticsearchTemplate.refresh(Book.class);
//given
IndexQuery queryCreatingBookEntity = new BookBuilder("1").setTitle("BBB").buildBookIndex();
//when
elasticsearchTemplate.index(queryCreatingBookEntity);
elasticsearchTemplate.refresh(Book.class);
//then
assertThat(bookRepository.findOne("1"), is(notNullValue()));
}
While it creates the index and mapping BUT it does not put the Book inside it - why?
EDIT
Test fils like this:
java.lang.AssertionError:
Expected: is not null
but: was null
Expected :is not null
Actual :null
<Click to see difference>
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
When I GET _all/_mapping
{
"bookshop": {
"mappings": {
"book": {
"properties": {
"bid": {
"type": "string"
},
"title": {
"type": "string"
}
}
}
}
}
}
Also I check my index and mapping created but when I try to get the content:
GET /bookshop/book/1
{
"_index": "bookshop",
"_type": "book",
"_id": "1",
"found": false
}
So I get found false. So no book added.
EDIT 2
I have ES 2.3.5 form their official repo. below are the version packages.
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RC1</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-data-elasticsearch</artifactId>
</dependency>
<dependency> <!--version 2.0.2 to getClient form ElasticTemplate-->
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
</dependency>
</dependencies>
<!-- For executable JAR packaging-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository><!--version 2.0.2 to getClient form ElasticTemplate-->
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots><enabled>false</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
Book.java
#Data
#Document(indexName = "bookshop", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
public class Book {
#Id
private String bID;
#Field(type = FieldType.String, store = true)
private String title;
}
I have also put my book.java with lombok generated #Data and extended #Document content
My code is almost similar to yours. I've used this when I was playing with Spring Data Elasticsearch ages ago. I've just updated the version to 1.4.0.RELEASE The test is passing.
The 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.demo</groupId>
<artifactId>data-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>data-demo</name>
<description>Demo project for Spring Data ES and JPA</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
</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>
The Book.class
package com.demo.model;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.annotation.Id;
/**
* Holds the details of book.
*/
#Document(indexName = "book")
public class Book {
#Id
private String bookId;
private String title;
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
The Repository
package com.demo.search.repository;
import com.demo.model.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Holds the Elasticsearch CRUD operations for {#link Book} entity.
*/
public interface BookSearchRepository extends ElasticsearchRepository<Book, String> {
}
And finally, the test.
package com.demo.search.repository;
import com.demo.model.Book;
import org.junit.Before;
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.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* Test things on {#link BookSearchRepository}
*/
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class BookSearchRepositoryTest {
#Autowired
private BookSearchRepository bookRepository;
#Autowired
private ElasticsearchTemplate elasticsearchTemplate;
#Before
public void before() {
elasticsearchTemplate.deleteIndex(Book.class);
elasticsearchTemplate.createIndex(Book.class);
elasticsearchTemplate.putMapping(Book.class);
elasticsearchTemplate.refresh(Book.class);
}
#Test
public void shouldSaveBook(){
Book book = new Book();
book.setBookId("1");
book.setTitle("Learning Scala");
Book indexedBook = bookRepository.save(book);
assertThat(indexedBook, is(notNullValue()));
assertThat(indexedBook.getBookId(), is(book.getBookId()));
assertThat(bookRepository.findOne("1"), is(notNullValue()));
}
}

Spring 4 gs-rest-service gives Not acceptable 406 error

I'm trying to run the sample gs-rest-service-complete (https://spring.io/guides/gs/rest-service/) and get:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 12 15:03:05 SGT 2015
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation
I've not made any modification on the code.
Here's the Greeting.java file
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
The Controller class:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping(value="/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
I use the Application class to launch through spring boot:
package hello;
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);
}
}
And here is the pom.xml file:
<?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>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
I use Spring Tool Suite and imported the project directly from server. I run the project using spring boot.
Any specific configuration I've forgotten ?
I finally got this example to work by adding 2 dependencies in the pom.xml :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
This is a strange behavior as those dependencies are included in spring-boot:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
It was working for jackson-databind but not for the other two.
If anyone can explain this, please let me know.

Spring Boot data source

I use Spring boot in my Application and trying to create a DataSource using UCP and stuck with the following error. Similar question has already been posted but interested in knowing the reason with this configuration.
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 143 more
But I have add the hibernate.dialect.
Aplication.java,
#Configuration //#EnableAutoConfiguration #ComponentScan #EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) #SpringBootApplication public class DialerApplication {
public static void main(String[] args) {
SpringApplication.run(DialerApplication.class, args);
} }
DataSource file,
#Configuration
#ComponentScan
#EnableTransactionManagement
#EnableAutoConfiguration
#EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervytech.dialer.db.repository" })
public class ApplicationDataSource {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
.getLogger(ApplicationDataSource.class);
/** The Constant TEST_SQL. */
private static final String TEST_SQL = "select 1 from dual";
/** The pooled data source. */
private PoolDataSource pooledDataSource;
/** The environment. */
private Environment environment;
/** The Constant CONNECTION_WAIT_TIMEOUT_SECS. */
private static final int CONNECTION_WAIT_TIMEOUT_SECS = 300;
/**
* Data source.
*
* #return the pool data source
*/
#Bean(name = "dialerDataSource")
#Primary
public PoolDataSource dialerDataSource() {
this.pooledDataSource = PoolDataSourceFactory.getPoolDataSource();
final String databaseDriver = environment
.getRequiredProperty("application.datasource.driverClassName");
final String databaseUrl = environment
.getRequiredProperty("application.datasource.url");
final String databaseUsername = environment
.getRequiredProperty("application.datasource.username");
final String databasePassword = environment
.getRequiredProperty("application.datasource.password");
final String initialSize = environment
.getRequiredProperty("application.datasource.initialSize");
final String maxPoolSize = environment
.getRequiredProperty("application.datasource.maxPoolSize");
final String minPoolSize = environment
.getRequiredProperty("application.datasource.minPoolSize");
// final String poolName =
// environment.getRequiredProperty("application.datasource.poolName");
try {
pooledDataSource.setConnectionFactoryClassName(databaseDriver);
pooledDataSource.setURL(databaseUrl);
pooledDataSource.setUser(databaseUsername);
pooledDataSource.setPassword(databasePassword);
pooledDataSource.setInitialPoolSize(Integer.parseInt(initialSize));
pooledDataSource.setMaxPoolSize(Integer.parseInt(maxPoolSize));
pooledDataSource.setMinPoolSize(Integer.parseInt(minPoolSize));
pooledDataSource.setSQLForValidateConnection(TEST_SQL);
pooledDataSource.setValidateConnectionOnBorrow(Boolean.TRUE);
pooledDataSource
.setConnectionWaitTimeout(CONNECTION_WAIT_TIMEOUT_SECS);
// pooledDataSource.setConnectionPoolName(poolName);
} catch (NumberFormatException e) {
LOGGER.error("Unable to parse passed numeric value", e);
} catch (SQLException e) {
LOGGER.error("exception creating data pool", e);
}
LOGGER.info("Setting up datasource for user:{} and databaseUrl:{}",
databaseUsername, databaseUrl);
return this.pooledDataSource;
}
#Bean(name = "dialerEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
lef.setDataSource(dialerDataSource());
lef.setJpaVendorAdapter(vendorAdapter);
lef.setPackagesToScan("com.nervytech.dialer.db.domain");
lef.setJpaProperties(additionalProperties());
lef.setPersistenceUnitName("dialerPersistenceUnit");
lef.afterPropertiesSet();
return lef.getObject();
}
#Bean(name = "dialerTransactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("hibernate.show_sql","true");
return properties;
}
/**
* Sets the environment.
*
* #param environment
* the new environment
*/
#Autowired
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
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.nervytech</groupId>
<artifactId>dialer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>dialer</name>
<description>Nervy Dialer</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>com.nervytech.dialer.DialerApplication</start-class>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</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-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-ws</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mail</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<!-- <version>3.2.1</version>-->
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ucp</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- <version>5.1.6</version>-->
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
Not sure why this error is still coming though the dialect is there in the dialerEntityManagerFactory.
Thanks,
Baskar.S
After further research, I found a solution and wanted to share.
Below is my property file.
application.datasource.driverClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
application.datasource.url=jdbc:mysql://localhost:3306/dbName
application.datasource.username=root
application.datasource.password=root
application.datasource.initialSize=5
application.datasource.maxPoolSize=5
application.datasource.minPoolSize=5
There was some empty space after the database name in the datasource.url. Spring will throw such error if the database connection is not established during the startup.
But adding the below property will let you start Spring boot though the db connection is not established.
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect
But Spring boot will reestablish the connection on the fly whenever the DB connection could be established after the startup.
Thanks,
Baskar.S

Resources