mongodb vs CRUD operation using spring boot - mongodb

Below is 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.test</groupId>
<artifactId>DemoMongoDBProduc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>DemoMongoDBProduc</name>
<description>Say Hello To Boot Using Mongo</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.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-mongodb</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-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>
// **Below is my main method**
package com.mono.mongo.crud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoMongoDbProducApplication {
public static void main(String[] args) {
SpringApplication.run(DemoMongoDbProducApplication.class, args);
}
}
// Below is my Controller class
package com.mono.mongo.crud.controller;
import java.util.List;
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.mono.mongo.crud.model.Person;
import com.mono.mongo.crud.service.PersonService;
#RestController
public class PersonController {
#Autowired
private PersonService personService;
#RequestMapping("/create")
public String create(#RequestParam String firstName, #RequestParam String lastName, #RequestParam int age) {
Person p = personService.create(firstName, lastName, age);
return p.toString();
}
#RequestMapping("/get")
public Person getPerson(#RequestParam String firstName) {
return personService.getByFirstName(firstName);
}
#RequestMapping("/getAll")
public List<Person> getAll(){
return personService.getAll();
}
#RequestMapping("/update")
public String update(#RequestParam String firstName, #RequestParam String lastName, #RequestParam int age) {
Person p = personService.update(firstName, lastName, age);
return p.toString();
}
#RequestMapping("/delete")
public String delete(#RequestParam String firstName) {
personService.delete(firstName);
return "Deleted : "+firstName;
}
#RequestMapping("/delete")
public String deleteAll() {
personService.deleteAll();
return "Deleted all records";
}
}
// Below is my Service class
package com.mono.mongo.crud.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mono.mongo.crud.model.Person;
import com.mono.mongo.crud.repository.PersonRepository;
#Service
public class PersonService {
#Autowired
private PersonRepository personRepository;
// Create operation
public Person create(String firstName, String lastName, int age)
{
return personRepository.save(new Person(firstName, lastName, age));
}
// Retrieve operation
public List<Person> getAll()
{
return personRepository.findAll();
}
public Person getByFirstName(String firstName)
{
return personRepository.findByFirstName(firstName);
}
// Update Operation
public Person update(String firstName, String lastName, int age)
{
Person p = personRepository.findByFirstName(firstName);
p.setLastName(lastName);
p.setAge(age);
return personRepository.save(p);
}
// Delete Operation
public void deleteAll() {
personRepository.deleteAll();
}
public void delete(String firstName) {
Person p = personRepository.findByFirstName(firstName);
personRepository.delete(p);
}
}
// Below is my PersonRepository class
package com.mono.mongo.crud.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.mono.mongo.crud.model.Person;
#Repository
public interface PersonRepository extends MongoRepository<Person, String> {
public Person findByFirstName(String firstName);
public List<Person> findbyAge(int age);
// public Person findByFirstName(String firstName);
// public List<Person> findByAge(int age);
}
// Below is my Service class
package com.mono.mongo.crud.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mono.mongo.crud.model.Person;
import com.mono.mongo.crud.repository.PersonRepository;
#Service
public class PersonService {
#Autowired
private PersonRepository personRepository;
// Create operation
public Person create(String firstName, String lastName, int age)
{
return personRepository.save(new Person(firstName, lastName, age));
}
// Retrieve operation
public List<Person> getAll()
{
return personRepository.findAll();
}
public Person getByFirstName(String firstName)
{
return personRepository.findByFirstName(firstName);
}
// Update Operation
public Person update(String firstName, String lastName, int age)
{
Person p = personRepository.findByFirstName(firstName);
p.setLastName(lastName);
p.setAge(age);
return personRepository.save(p);
}
// Delete Operation
public void deleteAll() {
personRepository.deleteAll();
}
public void delete(String firstName) {
Person p = personRepository.findByFirstName(firstName);
personRepository.delete(p);
}
}
// Below is my POJO class
package com.mono.mongo.crud.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Person {
#Id
String id;
String firstName;
String lastName;
int age;
public Person(String firstName, String lastName, int age)
{
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Person FirstName: "+firstName+" LastName: "+lastName+" age: "+age;
}
}
I am using spring tool suite as IDE, MongoDB, Maven 3.2. I am trying to learn CRUD operation using MongoDB. But when I am running this code as Spring Boot App I am getting
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personController': Unsatisfied dependency expressed through field 'personService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personService': Unsatisfied dependency expressed through field 'personRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findbyAge found for type Person!
Can some one tell me where and what mistake I am doing
Here is the screenshot of the error I am getting:

In your Repository class.
Rename interface method from
findbyAge(int age);
to
findByAge(int age);

I have resolved the issue. It was quite simple and I was doing a silly mistake.
In the Controller class for delete() method and deleteAll() method the #RequestMapping was delete like #RequestMapping("/delete") only, instead I have changed it to #RequestMapping("/deleteAll") for complete deletion and #RequestMapping("/delete") for the deleteByFirstName. And it worked for me.

Related

Spring Boot MongoDB Can't find a codec for class

I'm new to MongoDb, I pulled a simple aggregation from compass. Now I am trying to return the data, unfortunately I am getting this error:
Caused by: org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.example.DemoMongo.model.User.
this is my configuration in spring boot:
Model
#Document("user")
public class User {
#Id
private String id;
private String name;
private List<Indirizzi> indirizzi;
public String getId() {
return id;
}
public String getName() {
return name;
}
public List<Indirizzi> getIndirizzi() {
return indirizzi;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setIndirizzi(List<Indirizzi> indirizzi) {
this.indirizzi = indirizzi;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", indirizzi=" + indirizzi + "]";
}
#Document("indirizzi")
public class Indirizzi {
#Id
private String id;
private String via;
public String getId() {
return id;
}
public String getVia() {
return via;
}
public void setId(String id) {
this.id = id;
}
public void setVia(String via) {
this.via = via;
}
#Override
public String toString() {
return "Indirizzi [id=" + id + ", via=" + via + "]";
}
}
Repository
public class UserRepositoryImpl implements UserCustomRepository {
private final MongoTemplate mongoTemplate;
#Autowired
public UserRepositoryImpl(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
#Override
public List<User> getUser() {
MongoCollection<Document> collection = this.mongoTemplate.getCollection("user");
AggregateIterable<User> result = collection.aggregate(Arrays.asList(new Document("$lookup",
new Document("from", "indirizzi")
.append("localField", "indirizzi")
.append("foreignField", "_id")
.append("as", "indirizzi"))),User.class);
List<User> list= new ArrayList<>();
MongoCursor<User> iterator = result.iterator(); //<- ERROR! Can't find a codec for class com.example.DemoMongo.model.User.
while (iterator.hasNext()) {
User user = iterator.next();
list.add(user);
}
return null;
}
}
public interface UserRepository extends MongoRepository<User,String>,UserCustomRepository{
public List<User>getUser();
}
public interface UserCustomRepository {
List<User> getUser();
}
POM dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</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>
</dependency>
</dependencies>
Thanks in advance

SpringBoot connect to MongoDB

I am learning on Spring boot to insert data into MongoDB and encountered some issues. Please give me some of your advise, thank you.
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 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.6.2</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>com.onboard.proj</groupId>
<artifactId>onboard</artifactId>
<version>0.0.1-SNAPSHOT</version>
<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-mongodb</artifactId>
</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-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
UserController.java
#RestController
public class UserController {
#Autowired
MongoService db;
#PostMapping("/create")
public User createNew(#RequestParam("name") String name, #RequestParam("role") String role){
User obj = new User(name, role);
User newObj = db.save(obj);
return newObj;
}
}
MongoService.java
#Service
public class MongoService {
#Autowired
MongoRepository repo;
public User save(User u) {
return repo.save(u);
}
}
MongoRepository.java
public class MongoRepository {
#Autowired
private MongoTemplate template;
public User save(User e) {
if(e != null) {
template.insert(e);
}
return e;
}
}
User.java
#Document
public class User {
#Id
private String id;
//#Field("name")
private String name;
//#Field("role")
private String role;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getRole() {
return role;
}
public void setName(String name) {
this.name = name;
}
public void setRole(String role) {
this.role = role;
}
public User(String name, String role) {
super();
this.name = name;
this.role = role;
}
public User() {
super();
}
}
I tried to use PostMan and did the following setting, but couldnt reach the UserController. The result from Postman is always 404, NOT FOUND.
Add the annotation #RequestMapping("/") also on class level since Spring requires a mapping for your class also, not only the method.
#RestController
#RequestMapping("/")
public class UserController {
Also you have
#RequestParam("name") String name, #RequestParam("role") String role
but in Postman you pass name and role in JSON body. It is not coded to work like this. You should pass name and role as query parameters in Postman.
#RestController
#RequestMapping("/")
public class UserController {
#Autowired
MongoService db;
#PostMapping("/create")
public User createNew(#RequestParam("name") String name, #RequestParam("role") String role){
User obj = new User(name, role);
User newObj = db.save(obj);
return newObj;
}
}
it is better to use swagger you can get endpoints easily.

Content type 'application/json;charset=UTF-8' not supported Spring Boot REST API

In my Spring Boot Rest API i can get "Utilisateurs" class instances from database (GET), but when i try to add a new instance using POST method i get the following error :
{
"timestamp": "2019-08-08T20:17:41.292+0000",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'application/json;charset=UTF-8' not supported",
"path": "/utilisateurs/signup"
}
What Should i change to avoid this Unsupported Media Type Error ?
I've tried sending the post method with and without "Content-Type : application/json" header
This is the class "Utilisateurs" :
package ma.netrent.entities;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
public class Utilisateur implements Serializable {
#Id
#GeneratedValue
private long id;
private String image;
private String prenom;
private String nom;
private String email;
private String password;
private String quartier;
private String ville;
private String pays;
#Column(columnDefinition = "float default -1")
private float note;
private boolean accountExpired;
private boolean accountLocked;
public List<Role> getRoles() {
return roles;
}
public void setRoles(ArrayList<Role> roles) {
this.roles = roles;
}
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private List<Role> roles;
#OneToMany(fetch = FetchType.LAZY)
private List<Commentaire> commentaires;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "proprietaire", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Immobilier> immobiliers;
public Utilisateur() {
}
public Utilisateur(long id) {
setId(id);
}
public Utilisateur(Utilisateur u) {
this.id = u.id;
this.image = u.image;
this.accountExpired = u.accountExpired;
this.password = u.password;
this.accountLocked = u.accountLocked;
this.commentaires = u.commentaires;
this.regisrationDate = u.regisrationDate;
this.immobiliers = u.immobiliers;
this.note = u.note;
this.prenom = u.prenom;
this.nom = u.nom;
this.email = u.email;
}
public Utilisateur(String email, String password, ArrayList<Role> roles) {
this.roles = roles;
this.password = password;
this.email = email;
}
public List<Commentaire> getCommentaires() {
return commentaires;
}
public void setCommentaires(List<Commentaire> commentaires) {
this.commentaires = commentaires;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isAccountExpired() {
return accountExpired;
}
public void setAccountExpired(boolean accountExpired) {
this.accountExpired = accountExpired;
}
public boolean isAccountLocked() {
return accountLocked;
}
public void setAccountLocked(boolean accountLocked) {
this.accountLocked = accountLocked;
}
#SuppressWarnings("deprecation")
#PrePersist
void onCreate() {
this.setRegisrationDate(new Timestamp((new Date()).getDate()));
}
#SuppressWarnings("deprecation")
#PreUpdate
void onPersist() {
System.out.println("yoyo");
this.setRegisrationDate(new Timestamp((new Date()).getDate()));
}
#Temporal(TemporalType.DATE)
private Date regisrationDate;
public float getNote() {
return note;
}
public void setNote(float note) {
this.note = note;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#JsonIgnore
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#JsonIgnore
public List<Immobilier> getImmobiliers() {
return immobiliers;
}
public void setImmobiliers(List<Immobilier> immobiliers) {
this.immobiliers = immobiliers;
}
public String getQuartier() {
return quartier;
}
public void setQuartier(String quartier) {
this.quartier = quartier;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getPays() {
return pays;
}
public void setPays(String pays) {
this.pays = pays;
}
public Date getRegisrationDate() {
return regisrationDate;
}
public void setRegisrationDate(Date regisrationDate) {
this.regisrationDate = regisrationDate;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
The Controller i send the post request to : (utilisateurs/signup)
package ma.netrent.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
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 ma.netrent.entities.Utilisateur;
import ma.netrent.responseEntities.UtilisateurResponse;
import ma.netrent.services.UtilisateurService;
#RestController
#RequestMapping(value = "/utilisateurs")
public class UtilisateursController {
#Autowired
private UtilisateurService utilisateurService;
#Autowired
private PasswordEncoder bcryptEncoder;
#RequestMapping(method = RequestMethod.GET, value = "/all")
public ResponseEntity<UtilisateurResponse> tousLesUtilisateurs() {
List<Utilisateur> allUtilisateurs = utilisateurService.getAllUtilisateurs();
return (!allUtilisateurs.isEmpty()) ?
utilisateursResponse(allUtilisateurs, null, HttpStatus.OK):
utilisateursResponse(null, "Aucun Utilisateur dans la base de données", HttpStatus.OK);
}
#RequestMapping(value="/signup", method = RequestMethod.POST)
public ResponseEntity<UtilisateurResponse> ajouterClient(#RequestBody Utilisateur u) {
System.out.println(u.getEmail());
String msg;
HttpStatus httpStatus;
if(utilisateurService.existByEmail(u.getEmail())) {
msg="Email déjà utilisé !";
httpStatus = HttpStatus.CONFLICT;
}else {
msg="Compte Crée avec succé";
u.setPassword(bcryptEncoder.encode(u.getPassword()));
utilisateurService.addUtilisateur(u);
httpStatus = HttpStatus.CREATED;
}
return utilisateursResponse(null, msg, httpStatus);
}
#RequestMapping(value="/{id}", method = RequestMethod.DELETE)
public ResponseEntity<UtilisateurResponse> supprimerUtilisateur(#PathVariable long id) {
String msg;
HttpStatus httpStatus;
if( utilisateurService.existById(id) ) {
utilisateurService.deleteUtilisateur(id);
msg="compte Supprimé !";
httpStatus = HttpStatus.OK;
}else {
msg="Cet utilisateur n'existe pas dans la base de données.";
httpStatus = HttpStatus.NOT_FOUND;
}
return utilisateursResponse(null, msg, httpStatus);
}
#RequestMapping(value="/{id}", method = RequestMethod.PUT)
public ResponseEntity<UtilisateurResponse> modifierUtilisateur(#PathVariable long id, #RequestBody Utilisateur u) {
String msg;
HttpStatus httpStatus;
if( utilisateurService.existById(id) ) {
utilisateurService.updateUtilisateur(id, u);
msg="utilisateur modifié !";
httpStatus = HttpStatus.OK;
}else {
msg="cet utilisateur n'existe pas dans la base de données.";
httpStatus = HttpStatus.NOT_FOUND;
}
return utilisateursResponse(null, msg, httpStatus);
}
#RequestMapping(value="/{id}", method = RequestMethod.GET)
public ResponseEntity<UtilisateurResponse> majUtilisateur(#PathVariable long id) {
String msg=null;
HttpStatus httpStatus;
List<Utilisateur> utilisateurs = new ArrayList<Utilisateur>();
if( utilisateurService.existById(id) ) {
httpStatus = HttpStatus.OK;
utilisateurs.add(utilisateurService.getUtilisateur(id));
}else {
msg="cet utilisateur n'existe pas dans la base de données.";
httpStatus = HttpStatus.NOT_FOUND;
}
return utilisateursResponse(utilisateurs, msg, httpStatus);
}
public static ResponseEntity<UtilisateurResponse> utilisateursResponse( List<Utilisateur> utilisateurs,
String message, HttpStatus statusCode) {
HttpHeaders headers = new HttpHeaders();
int status = statusCode.value();
headers.add("status", String.valueOf(statusCode));
headers.add("message", message);
return ResponseEntity.status(status).headers(headers)
.body(new UtilisateurResponse( message, statusCode, utilisateurs));
}
}
The Security Configuration
package ma.netrent.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import ma.netrent.repository.UtilisateurRepository;
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
#EnableJpaRepositories(basePackageClasses = UtilisateurRepository.class)
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
#Autowired
private UserDetailsService jwtUserDetailsService;
#Autowired
private JwtRequestFilter jwtRequestFilter;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
return new PasswordEncoder() {
#Override
public String encode(CharSequence rawPassword) {
return BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt(4));
}
#Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
};
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// We don't need CSRF for this example
httpSecurity.csrf().disable()
// dont authenticate this particular request
.authorizeRequests()
.antMatchers("/utilisateurs/signup","/login").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// all other requests need to be authenticated
.anyRequest().authenticated()
.and().
// make sure we use stateless session; session won't be used to
// store user's state.
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
The CORS Filter :
package ma.netrent.config;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCORSFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(MyCORSFilter.class);
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//response.setHeader("Access-Control-Max-Age", "3600");
//response.setHeader("Access-Control-Allow-Headers", " Content-Type, Accept, X-Requested-With, remember-me");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig filterConfig) {
LOGGER.info("Filter initialized");
}
#Override
public void destroy() {
}
}
and 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.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.netrent</groupId>
<artifactId>netRent415</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>netRent415</name>
<description>plateforme communautaire gratuite de location de logements entre particuliers.</description>
<properties>
<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-security</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-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0.pr1</version>
</dependency>
<!--
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- compiles the jsp pages -->
<!--
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit5-engine</artifactId>
<version>5.0.0-ALPHA</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.paypal.sdk</groupId>
<artifactId>rest-api-sdk</artifactId>
<version>1.13.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Dumb reason : i have 2 setters for the roles attribute. Super DUMB, but might help someone.

Getting java.lang.NoSuchFieldError: ERRORS_IGNORED for hibernate-ogm with mongodb

I am trying to use hibernate-ogm with mongodb and getting no such fieds error
persistence.xml
<persistence-unit name="mongodb-test" transaction-type="JTA">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<properties>
<property name="hibernate.ogm.datastore.provider" value="mongodb"></property>
<property name="hibernate.ogm.datastore.host" value="192.168.0.237"></property>
<property name="hibernate.ogm.datastore.create_database" value="true"></property>
<property name="hibernate.ogm.datastore.database" value="anand_test"></property>
<property name="hibernate.ogm.mongodb.connection_timeout" value="5000"></property>
<property name="hibernate.ogm.mongodb.authentication_mechanism" value="PLAIN"></property>
<property name="hibernate.ogm.datastore.document.association_storage" value="IN_ENTITY"></property>
<property name="hibernate.ogm.mongodb.association_document_storage" value="GLOBAL_COLLECTION"></property>
<property name="hibernate.ogm.mongodb.write_concern" value="ACKNOWLEDGED"></property>
<property name="hibernate.ogm.mongodb.read_preference" value="PRIMARY_PREFERRED"></property>
</properties>
</persistence-unit>
Person.java
import javax.persistence.Entity;
import javax.persistence.Id;
import org.bson.types.ObjectId;
import org.hibernate.annotations.Type;
#Entity
public class Person {
#Id
#Type(type = "objectid")
private String id;
private String firstName;
private String lastName;
public String getId() {
return id;
}
public void setId(String 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 Person(){
}
public Person(String firstName,String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
TestMongoconnection.java
import com.mongodb.Person;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class TestMongoConnection {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("mongodb-test");
EntityManager manager = entityManagerFactory.createEntityManager();
manager.getTransaction().begin();
Person anandMohan = new Person("Anand","Mohan");
manager.persist(anandMohan);
manager.getTransaction().commit();
manager.close();
}
}
I am having mongodb version 3.0.2 and hibernate-ogm 4.2.0 final with mongodb java version 3.x jars
The problem is with the java jar version of the mongodb as 3.x version is not yet supported have to use 2.x version of it
https://forum.hibernate.org/viewtopic.php?f=31&t=1040127&p=2485319#p2485319

GAE : Google Cloud SQL + JPA is not working

When i connected my cloud sql instance with JPA using EclipseLink 2.2.1, it shows following error
W 2012-10-24 12:21:46.120
org.datanucleus.metadata.xml.AbstractMetaDataHandler error: MetaData Parser encountered an error in file "file:/base/data/home/apps/s~appengineaplicationID/8.362672796318745816/WEB-INF/classes/META-INF/persistence.xml" at line 2, column 248 : cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'. - Please check your specification of DTD and the validity of the MetaData XML that you have specified.
W 2012-10-24 12:21:46.885
Error for /jpatest
java.lang.ExceptionInInitializerError
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
Caused by: org.datanucleus.exceptions.NucleusUserException: No available StoreManager found for the datastore URL key "". Please make sure you have all relevant plugins in the CLASSPATH (e.g datanucleus-rdbms?, datanucleus-db4o?), and consider setting the persistence property "datanucleus.storeManagerType" to the type of store you are using e.g rdbms, db4o
W 2012-10-24 12:21:46.887
Nested in java.lang.ExceptionInInitializerError:
javax.persistence.PersistenceException: Provider error. Provider: org.datanucleus.jpa.PersistenceProviderImpl
at javax.persistence.Persistence.createFactory(Persistence.java:176)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:112)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:66)
at com.my.jpa.EMF.<clinit>(EMF.java:8)
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
C 2012-10-24 12:21:46.893
Uncaught exception from servlet
java.lang.ExceptionInInitializerError
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
My code for persistance.xml is
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPATest">
<class>com.my.jpa.Contact</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.google.cloud.sql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms://instance_name/db" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>
My Entity Manager Factory Class is :
public final class EMF {
private static final EntityManagerFactory emfInstance = Persistence
.createEntityManagerFactory("JPATest");
private EMF() {
}
public static EntityManagerFactory get() {
return emfInstance;
}
}
Servlet is :
public class JPATestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
ContactService service = new ContactService();
service.createContact(new Contact("Manu", "Mohan", "686019", "TVM"));
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
Entity Class is :
#Entity
public class Contact {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String phoneNumber;
private String address;
public Contact() {
}
public Contact(String fn, String ln, String pn, String addr) {
this.firstName = fn;
this.lastName = ln;
this.phoneNumber = pn;
this.address = addr;
}
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 getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
One would think that if you want to use EclipseLink, then you would set the "provider" in "persistence.xml", since you have other JPA implementation(s) in the CLASSPATH too, or alternatively you fix the CLASSPATH to make sure there is only 1 JPA implementation present