Facing difficulty with Hibernate HQL when applying it to H2 - spring

I am new to hibernate and spring maven environment.
I have tried implementing an embedded db using H2, which earlier used MySQL. there are two DAO's
OffersDao.java
package com.skam940.main.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Component("offersDao")
#Transactional
public class OffersDao {
#Autowired
private SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
#SuppressWarnings("unchecked")
public List<Offer> getOffers() {
Criteria crit = session().createCriteria(Offer.class);
crit.createAlias("user", "u").add(Restrictions.eq("u.enabled", true));
return crit.list();
}
#SuppressWarnings("unchecked")
public List<Offer> getOffers(String username) {
Criteria crit = session().createCriteria(Offer.class);
crit.createAlias("user", "u");
crit.add(Restrictions.eq("u.enabled", true));
crit.add(Restrictions.eq("u.username", username));
return crit.list();
}
public void saveOrUpdate(Offer offer) {
session().saveOrUpdate(offer);
}
public boolean delete(int id) {
Query query = session().createQuery("delete from Offer where id=:id");
query.setLong("id", id);
return query.executeUpdate() == 1;
}
public Offer getOffer(int id) {
Criteria crit = session().createCriteria(Offer.class);
crit.createAlias("user", "u");
crit.add(Restrictions.eq("u.enabled", true));
crit.add(Restrictions.idEq(id));
return (Offer) crit.uniqueResult();
}
}
and UsersDao.java
package com.skam940.main.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
#Component("usersDao")
public class UsersDao {
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
#Transactional
public void create(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
session().save(user);
}
public boolean exists(String username) {
Criteria crit = session().createCriteria(User.class);
crit.add(Restrictions.idEq(username));
User user = (User) crit.uniqueResult();
return user != null;
}
#SuppressWarnings("unchecked")
public List<User> getAllUsers() {
return session().createQuery("from User").list();
}
}
no the thing is I get an exception of
HTTP Status 500 - PreparedStatementCallback; bad SQL grammar [select username, password, enabled from users where binary username = ?]; nested exception is org.h2.jdbc.JdbcSQLException: Column "BINARY" not found; SQL statement:
And the thing I want to do here to make the username case sensitive, and apparently H2 recognises BINARY as a table name but not as a type or what ever you call that, can any one tell which which method is implementing this SQL grammar?
User.java
package com.skam940.main.dao;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;
import com.skam940.main.validation.ValidEmail;
#Entity
#Table(name="users")
public class User {
#NotBlank(groups={PersistenceValidationGroup.class, FormValidationGroup.class})
#Size(min=6, max=15, groups={PersistenceValidationGroup.class, FormValidationGroup.class})
#Pattern(regexp="^\\w{8,}$", groups={PersistenceValidationGroup.class, FormValidationGroup.class})
#Id
#Column(name="username")
private String username;
#NotBlank(groups={PersistenceValidationGroup.class, FormValidationGroup.class})
#Pattern(regexp="^\\S+$", groups={PersistenceValidationGroup.class, FormValidationGroup.class})
#Size(min=8, max=15, groups={PersistenceValidationGroup.class, FormValidationGroup.class})
private String password;
#ValidEmail(groups={PersistenceValidationGroup.class, FormValidationGroup.class})
private String email;
#NotBlank(groups={PersistenceValidationGroup.class, FormValidationGroup.class})
#Size(min=3, max=30, groups={FormValidationGroup.class})
private String name;
private boolean enabled = false;
private String authority;
public User() {
}
public User(String username, String name, String password, String email, boolean enabled,
String authority) {
this.username = username;
this.name = name;
this.password = password;
this.email = email;
this.enabled = enabled;
this.authority = authority;
}
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;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((authority == null) ? 0 : authority.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((username == null) ? 0 : username.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;
User other = (User) obj;
if (authority == null) {
if (other.authority != null)
return false;
} else if (!authority.equals(other.authority))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (enabled != other.enabled)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
#Override
public String toString() {
return "User [username=" + username + ", email=" + email + ", name="
+ name + ", enabled=" + enabled + ", authority=" + authority
+ "]";
}
}
Offer.java
package com.skam940.main.dao;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;
#Entity
#Table(name="offers")
public class Offer {
#Id
#GeneratedValue
// because this is an auto increment value
private int id;
#Size(min=5, max=255, groups={PersistenceValidationGroup.class, FormValidationGroup.class})
#Column(name="text")
private String text;
// every user can have only one offer
#ManyToOne
#JoinColumn(name="username")
private User user;
public Offer() {
this.user = new User();
}
public Offer(User user, String text) {
this.user = user;
this.text = text;
}
public Offer(int id, User user, String text) {
this.id = id;
this.user = user;
this.text = text;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getUsername() {
return user.getUsername();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((text == null) ? 0 : text.hashCode());
result = prime * result + ((user == null) ? 0 : user.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;
Offer other = (Offer) obj;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
#Override
public String toString() {
return "Offer [id=" + id + ", text=" + text + ", user=" + user + "]";
}
}
the full file content is available here -> https://app.box.com/s/c3uq71khbwf05p8asu27

This query is coming from your Spring security configuration, please check security-context.xml, you can find Spring security authentication provider that uses authorities-by-username-query as
select username, authority from users where binary username = ?
This query uses MySQL-specific function BINARY for case-sensitive comparison (http://gilfster.blogspot.com/2005/08/case-sensitivity-in-mysql.html). H2, on the other hand, is case sensitive by default.
Try to change it with
select username, authority from users where username = ?
The same applies to users-by-username-query property.

Related

cant send a postman data with ManyToOne

hi i'm working with spring boot and rest in my project and i estableshed a relation ManyToOne between two enteties but i'm unable to send the postman request to add a mission along with its category i'm not even sure that the two enteties are correctly related
he are the two entities and the contoller
the mission etity
#Entity
#Table(name="missions")
public class Mission {
public Mission() {
}
public Mission(int id, String state, String adresse, int etatMission, String image, List<Categorie> categories,
String ville, int duree, String description, String domaine) {
this.id = id;
this.state = state;
this.adresse = adresse;
this.etatMission = etatMission;
this.image = image;
this.categories = categories;
this.ville = ville;
this.duree = duree;
this.description = description;
this.domaine = domaine;
}
public List<Categorie> getCategories() {
return categories;
}
public void setCategories(List<Categorie> categories) {
this.categories = categories;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public Mission(Map<String,Object> userMap) {
if (userMap.get("id") != null)
this.id = (int )userMap.get("id");
this.state = (String) userMap.get("state");
this.duree = (int) userMap.get("duree");
this.domaine = (String) userMap.get("domaine");
this.description = (String) userMap.get("description");
this.ville=(String) userMap.get("ville");
this.adresse=(String) userMap.get("adresse");
this.etatMission=(int) userMap.get("etatMission");
this.image=(String) userMap.get("image");
this.categories=(List<Categorie>) userMap.get("categories");
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String state;
private String adresse;
private int etatMission;
private String image;
#OneToMany(mappedBy="mission",cascade=CascadeType.ALL)
private List<Categorie> categories;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
private String ville;
public int getEtatMission() {
return etatMission;
}
public void setEtatMission(int etatMission) {
this.etatMission = etatMission;
}
private int duree;
private String description;
private String domaine;
public String getDomaine() {
return domaine;
}
public void setDomaine(String domaine) {
this.domaine = domaine;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public String toString() {
return "Mission [id=" + id + ", state=" + state + ", duree=" + duree + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getDuree() {
return duree;
}
public void setDuree(int duree) {
this.duree = duree;
}
public void add(Categorie cat) {
if (categories == null) {
categories = new ArrayList<>();
}
categories.add(cat);
cat.setMission(this);
}
}
the category entety
#Entity
#Table(name="categorie")
public class Categorie {
public Categorie() {
}
public Categorie(Map<String, Object> catMap) {
this.id=(int) catMap.get("id");
this.nom = (String) catMap.get("nom");
this.mission =(Mission) catMap.get("mission_id") ;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id ;
private String nom;
#ManyToOne
#JoinColumn(name="mission_id",referencedColumnName="id")
private Mission mission;
public Categorie(int id, String nom, Mission mission) {
this.id = id;
this.nom = nom;
this.mission = mission;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Override
public String toString() {
return "Categorie [nom=" + nom + "]";
}
public Mission getMission() {
return mission;
}
public void setMission(Mission mission) {
this.mission = mission;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
here's the controller for mission
package ma.ac.emi.MinuteBrico.Controllers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ma.ac.emi.MinuteBrico.Services.MissionServices;
import ma.ac.emi.MinuteBrico.Models.Mission;
#RestController
public class MissionController {
#Autowired
private MissionServices missionService;
#CrossOrigin
#GetMapping("/missions")
public List<Mission> index(){
return missionService.findAll();
}
#CrossOrigin
#GetMapping("/missions/{id}")
public Optional<Mission> indexById(#PathVariable String id){
int missionId = Integer.parseInt(id);
return missionService.findById(missionId);
}
#CrossOrigin()
#PostMapping("/missions")
public String create(#RequestBody Map<String, Object> missionMap) {
System.out.println(missionMap);
Mission mission = new Mission(missionMap);
missionService.savemission(mission);
return "Mission ajouté";
}
}
package ma.ac.emi.MinuteBrico.Repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import ma.ac.emi.MinuteBrico.Models.Mission;
public interface MissionRepository extends JpaRepository<Mission,Integer> {
}
the postman request
{
"state": "Urgent",
"adresse": "Av ben drisse",
"etatMission": 0,
"image": "assets/Brand.jpeg",
"ville": "Chefchaouen",
"duree": 480000,
"description": "je veux quelqu\\'un pour me faire une cuisne",
"domaine": "Plomberie",
"categories":[
{
"id":15,
"nom":"Menuiserie",
"mission":{
"field":"value"
}
}
]
}
try to add #ManyToOne(cascade = CascadeType.ALL)

how i can resolve the error unable to insert NULL in ("NAWFEL". "ORDO_DEP_UUSATEUR". "EMPLOI")

I'm developing a user registration form, the problem I get is that when I want to test my web service in postman it shows me the following error in my eclipse console:
> 2020-06-02 19:50:04.559 WARN 1576 --- [nio-8484-exec-2]
> o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1400, SQLState:
> 23000 2020-06-02 19:50:04.560 ERROR 1576 --- [nio-8484-exec-2]
> o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-01400: impossible
> d'insérer NULL dans ("NAWFEL"."ORDO_DEP_UTILISATEUR"."EMPLOI")
>
> 2020-06-02 19:50:04.582 ERROR 1576 --- [nio-8484-exec-2]
> o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for
> servlet [dispatcherServlet] in context with path [] threw exception
> [Request processing failed; nested exception is
> org.springframework.dao.DataIntegrityViolationException: could not
> execute statement; SQL [n/a]; constraint [null]; nested exception is
> org.hibernate.exception.ConstraintViolationException: could not
> execute statement] with root cause
>
> oracle.jdbc.OracleDatabaseException: ORA-01400: impossible d'insérer
> NULL dans ("NAWFEL"."ORDO_DEP_UTILISATEUR"."EMPLOI")
>
> at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:513)
> ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0] at
> oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:461)
> ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0] at
> oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1104)
> ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0] at
> oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:550)
> ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0] at
> oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:268)
> ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0] at
> oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:655)
> ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
he tells me that I cannot insert a null value in the job "emploi" column, but I entered the value of the job column in my postman as you can see here:
this is my entity code :
package com.app.habilitation.entity;
import java.sql.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="ORDO_DEP_UTILISATEUR")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="IDENTIFIANT")
private Integer IDENTIFIANT;
#ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
#JoinColumn(name="EMPLOI")
private EmploiEntity emploi;
#ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
#JoinColumn(name="ENTITE")
private EntiteEntity entite;
#Column(name="LOGIN")
private String login;
#Column(name="MOTDEPASSE")
private String mdp;
#Column(name="NOM")
private String nom;
#Column(name="PRENOM")
private String prenom;
#Column(name="CREEPAR")
private Integer creerpar;
#Column(name="ANNULEPAR")
private Integer annulepar;
#Column(name="STATUT")
private String statut;
#Column(name="DATEEFFET")
private Date dateeffet;
#Column(name="DATEFIN")
private Date datefin;
#Column(name="CREELE")
private Date creele;
#Column(name="MOTIFDEDESACTIVATION")
private String motifdedesactivation;
#Column(name="ANNULELE")
private Date annulele;
#Column(name="EMAIL")
private String email;
#Column(name="CONFIRMATIONMOTDEPASSE")
private String confirmation_mot_de_passe;
public String getConfirmation_mot_de_passe() {
return confirmation_mot_de_passe;
}
public void setConfirmation_mot_de_passe(String confirmation_mot_de_passe) {
this.confirmation_mot_de_passe = confirmation_mot_de_passe;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getIDENTIFIANT() {
return IDENTIFIANT;
}
public void setIDENTIFIANT(Integer iDENTIFIANT) {
IDENTIFIANT = iDENTIFIANT;
}
public EmploiEntity getEmploi() {
return emploi;
}
public void setEmploi(EmploiEntity emploi) {
this.emploi = emploi;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getMdp() {
return mdp;
}
public void setMdp(String mdp) {
this.mdp = mdp;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Integer getCreerpar() {
return creerpar;
}
public void setCreerpar(Integer creerpar) {
this.creerpar = creerpar;
}
public Integer getAnnulepar() {
return annulepar;
}
public void setAnnulepar(Integer annulepar) {
this.annulepar = annulepar;
}
public String getStatut() {
return statut;
}
public void setStatut(String statut) {
this.statut = statut;
}
public Date getDateeffet() {
return dateeffet;
}
public void setDateeffet(Date dateeffet) {
this.dateeffet = dateeffet;
}
public Date getDatefin() {
return datefin;
}
public void setDatefin(Date datefin) {
this.datefin = datefin;
}
public Date getCreele() {
return creele;
}
public void setCreele(Date creele) {
this.creele = creele;
}
public String getMotifdedesactivation() {
return motifdedesactivation;
}
public void setMotifdedesactivation(String motifdedesactivation) {
this.motifdedesactivation = motifdedesactivation;
}
public Date getAnnulele() {
return annulele;
}
public void setAnnulele(Date annulele) {
this.annulele = annulele;
}
public EntiteEntity getEntite() {
return entite;
}
public void setEntite(EntiteEntity entite) {
this.entite = entite;
}
public UserEntity(EmploiEntity emploi, EntiteEntity entite, String login, String mdp, String nom, String prenom,
Integer creerpar, Integer annulepar, String statut, Date dateeffet, Date datefin, Date creele,
String motifdedesactivation, Date annulele, String email, String confirmation_mot_de_passe) {
this.emploi = emploi;
this.entite = entite;
this.login = login;
this.mdp = mdp;
this.nom = nom;
this.prenom = prenom;
this.creerpar = creerpar;
this.annulepar = annulepar;
this.statut = statut;
this.dateeffet = dateeffet;
this.datefin = datefin;
this.creele = creele;
this.motifdedesactivation = motifdedesactivation;
this.annulele = annulele;
this.email = email;
this.confirmation_mot_de_passe = confirmation_mot_de_passe;
}
public UserEntity() {
}
#Override
public String toString() {
return "UserEntity [IDENTIFIANT=" + IDENTIFIANT + ", emploi=" + emploi + ", entite=" + entite + ", login="
+ login + ", mdp=" + mdp + ", nom=" + nom + ", prenom=" + prenom + ", creerpar=" + creerpar
+ ", annulepar=" + annulepar + ", statut=" + statut + ", dateeffet=" + dateeffet + ", datefin="
+ datefin + ", creele=" + creele + ", motifdedesactivation=" + motifdedesactivation + ", annulele="
+ annulele + ", email=" + email + ", confirmation_mot_de_passe=" + confirmation_mot_de_passe + "]";
}
}
and this is my dao ( i use jpa) :
package com.app.habilitation.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.app.habilitation.entity.UserEntity;
public interface UserDao extends JpaRepository<UserEntity, Integer> {
}
and this is my userService :
package com.app.habilitation.service;
import java.util.List;
import com.app.habilitation.entity.UserEntity;
public interface UserService {
public void save (UserEntity theUser);
}
and this is my userServiceImpl :
package com.app.habilitation.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.app.habilitation.dao.UserDao;
import com.app.habilitation.entity.UserEntity;
#Service
public class UserServiceImpl implements UserService {
private UserDao userDao;
#Autowired
public UserServiceImpl (UserDao theuserDao) {
userDao = theuserDao;
}
#Override
#Transactional
public void save(UserEntity theUser) {
userDao.save(theUser);
}
}
and this is my controller :
package com.app.habilitation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.app.habilitation.entity.UserEntity;
import com.app.habilitation.service.UserService;
#SpringBootApplication
#RestController
#CrossOrigin(origins = "*")
//#RequestMapping("/user")
public class UserController {
private UserService userService;
#Autowired
public UserController (UserService theuserService) {
userService=theuserService;
}
#GetMapping("/")
public String login() {
return "authenticaated succesfully";
}
#GetMapping("/getUsers")
public String getUsers() {
return "users";
}
#PostMapping("/addUser")
public UserEntity addUser (#RequestBody UserEntity theUser) {
System.out.println("test");
userService.save(theUser);
return theUser;
}
}
and this is my table user (i use oracle 10g) :
can someone help me please ?
Check your Column definition, is it a Many to one or just a regular column?
#Column(name="EMPLOI")
private EmploiEntity emploi;
if it is your Emploi created right?

OSGi, Jersey, and "No message body writer has been found for class"

I am putting together a short little REST demo of OSGi R7, OpenAPI, and jsonSchema. Everything works fine, except Postman is giving the following error:
No message body writer has been found for class com.ovloop.masterdata.party.pojo.provider.Person, ContentType: application/json
My class for implementing Restful services is written as follows. BTW, I can run swagger-maven-plugin on this class and get the corresponding Swagger spec.
package com.xyz.masterdata.party.rest;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.http.whiteboard.propertytypes.HttpWhiteboardResource;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xyz.masterdata.party.pojo.provider.Person;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.tags.Tags;
#JaxrsResource
#HttpWhiteboardResource(pattern = { "" }, prefix = "")
#Path("/person")
#Tags(#Tag(name = "test", description = ""))
#OpenAPIDefinition(info = #Info(description = "Person Service", version = "1.0", title = ""))
#Component(service = PersonRestImpl.class, immediate = true, property = { "service.exported.interfaces=*",
"service.intents=osgi.async", "service.intents=jaxrs", "osgi.basic.timeout=50000" })
public class PersonRestImpl {
#GET
#Path("/person")
#Produces(MediaType.APPLICATION_JSON)
#Operation(summary = "Get person with key", description = "Get person with key")
public Person getPerson(#PathParam("person") Long personId) {
Person person = new Person();
person.setPersonId("3245234");
person.setFirstName("Tom");
person.setLastName("Petty");
person.setAge(65);
return person;
}
#GET
#Path("/persons")
#Operation(summary = "Get persons", description = "Get list of persons")
public Response getPersons() {
Person person = new Person();
person.setPersonId("3245234");
person.setFirstName("Tom");
person.setLastName("Petty");
person.setAge(65);
List<Person> persons = new ArrayList<Person>();
persons.add(person);
Gson jsonConverter = new GsonBuilder().create();
return Response.status(Status.ACCEPTED).entity(jsonConverter.toJson(persons)).build();
}
#DELETE
#Path("/delete")
#Produces(MediaType.APPLICATION_JSON)
#Operation(summary = "delete person", description = "delete person")
public boolean deletePerson(#PathParam("person") long personId) {
return true;
}
#POST
#Path("/create")
#Produces(MediaType.APPLICATION_JSON)
#Operation(summary = "Create Person", description = "Create Person")
public Person postPerson(Person person) {
// if (person.personId > 0) {
// personDao.update(person);
// return person;
// } else {
// long id = personDao.save(person);
// person.personId = 1;
// return person;
// }
return person;
}
}
My POJO, which is generated from a jsonSchema using jsonschema2pojo-maven-plugin, is as follows:
package com.xyz.masterdata.party.pojo.provider;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* Person
* <p>
*
*
*/
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"personId",
"age",
"fullName",
"firstName",
"lastName"
})
public class Person {
/**
*
* (Required)
*
*/
#JsonProperty("personId")
private String personId;
/**
* Age in years
*
*/
#JsonProperty("age")
#JsonPropertyDescription("Age in years")
private Integer age;
/**
*
* (Required)
*
*/
#JsonProperty("fullName")
private String fullName;
#JsonProperty("firstName")
private String firstName;
#JsonProperty("lastName")
private String lastName;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* (Required)
*
*/
#JsonProperty("personId")
public String getPersonId() {
return personId;
}
/**
*
* (Required)
*
*/
#JsonProperty("personId")
public void setPersonId(String personId) {
this.personId = personId;
}
public Person withPersonId(String personId) {
this.personId = personId;
return this;
}
/**
* Age in years
*
*/
#JsonProperty("age")
public Integer getAge() {
return age;
}
/**
* Age in years
*
*/
#JsonProperty("age")
public void setAge(Integer age) {
this.age = age;
}
public Person withAge(Integer age) {
this.age = age;
return this;
}
/**
*
* (Required)
*
*/
#JsonProperty("fullName")
public String getFullName() {
return fullName;
}
/**
*
* (Required)
*
*/
#JsonProperty("fullName")
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Person withFullName(String fullName) {
this.fullName = fullName;
return this;
}
#JsonProperty("firstName")
public String getFirstName() {
return firstName;
}
#JsonProperty("firstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Person withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
#JsonProperty("lastName")
public String getLastName() {
return lastName;
}
#JsonProperty("lastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Person withLastName(String lastName) {
this.lastName = lastName;
return this;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Person withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Person.class.getName()).append('#').append(Integer.toHexString(System.identityHashCode(this))).append('[');
sb.append("personId");
sb.append('=');
sb.append(((this.personId == null)?"<null>":this.personId));
sb.append(',');
sb.append("age");
sb.append('=');
sb.append(((this.age == null)?"<null>":this.age));
sb.append(',');
sb.append("fullName");
sb.append('=');
sb.append(((this.fullName == null)?"<null>":this.fullName));
sb.append(',');
sb.append("firstName");
sb.append('=');
sb.append(((this.firstName == null)?"<null>":this.firstName));
sb.append(',');
sb.append("lastName");
sb.append('=');
sb.append(((this.lastName == null)?"<null>":this.lastName));
sb.append(',');
sb.append("additionalProperties");
sb.append('=');
sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
sb.append(',');
if (sb.charAt((sb.length()- 1)) == ',') {
sb.setCharAt((sb.length()- 1), ']');
} else {
sb.append(']');
}
return sb.toString();
}
#Override
public int hashCode() {
int result = 1;
result = ((result* 31)+((this.firstName == null)? 0 :this.firstName.hashCode()));
result = ((result* 31)+((this.lastName == null)? 0 :this.lastName.hashCode()));
result = ((result* 31)+((this.fullName == null)? 0 :this.fullName.hashCode()));
result = ((result* 31)+((this.personId == null)? 0 :this.personId.hashCode()));
result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
result = ((result* 31)+((this.age == null)? 0 :this.age.hashCode()));
return result;
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Person) == false) {
return false;
}
Person rhs = ((Person) other);
return (((((((this.firstName == rhs.firstName)||((this.firstName!= null)&&this.firstName.equals(rhs.firstName)))&&((this.lastName == rhs.lastName)||((this.lastName!= null)&&this.lastName.equals(rhs.lastName))))&&((this.fullName == rhs.fullName)||((this.fullName!= null)&&this.fullName.equals(rhs.fullName))))&&((this.personId == rhs.personId)||((this.personId!= null)&&this.personId.equals(rhs.personId))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.age == rhs.age)||((this.age!= null)&&this.age.equals(rhs.age))));
}
}
My bndrun file, on the application project, appears as follows:
-runfw: org.eclipse.osgi;version=3.13
-runee: JavaSE-1.8
-runprovidedcapabilities: ${native_capability}
-resolve.effective: active
-runproperties: \
osgi.console=,\
osgi.console.enable.builtin=false
-runrequires: \
osgi.identity;filter:='(osgi.identity=org.apache.felix.gogo.shell)',\
osgi.identity;filter:='(osgi.identity=org.apache.felix.gogo.command)',\
osgi.identity;filter:='(osgi.identity=com.xyz.masterdata.application.services)',\
bnd.identity;id='com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider',\
bnd.identity;id='com.fasterxml.jackson.jaxrs.jackson-jaxrs-base',\
bnd.identity;id='com.fasterxml.jackson.core.jackson-databind',\
bnd.identity;id='com.fasterxml.jackson.core.jackson-core',\
bnd.identity;id='com.xyz.masterdata.party.rest',\
bnd.identity;id='com.xyz.masterdata.party.pojo.provider'
-runbundles: \
com.xyz.masterdata.application.services;version=snapshot,\
com.xyz.masterdata.party.rest;version=snapshot,\
com.xyz.masterdata.party.pojo.provider;version=snapshot,\
org.apache.felix.configadmin;version='[1.9.8,1.9.9)',\
org.apache.felix.configurator;version='[1.0.6,1.0.7)',\
org.apache.felix.scr;version='[2.1.10,2.1.11)',\
ch.qos.logback.classic;version='[1.2.3,1.2.4)',\
ch.qos.logback.core;version='[1.2.3,1.2.4)',\
org.apache.aries.javax.jax.rs-api;version='[1.0.0,1.0.1)',\
org.apache.aries.jax.rs.whiteboard;version='[1.0.1,1.0.2)',\
org.apache.felix.gogo.runtime;version='[1.0.10,1.0.11)',\
org.apache.felix.http.jetty;version='[4.0.6,4.0.7)',\
org.apache.felix.http.servlet-api;version='[1.1.2,1.1.3)',\
org.apache.servicemix.specs.annotation-api-1.3;version='[1.3.0,1.3.1)',\
org.osgi.service.jaxrs;version='[1.0.0,1.0.1)',\
org.osgi.util.function;version='[1.1.0,1.1.1)',\
org.osgi.util.promise;version='[1.1.0,1.1.1)',\
slf4j.api;version='[1.7.25,1.7.26)',\
org.apache.felix.gogo.command;version='[1.0.2,1.0.3)',\
org.apache.felix.gogo.shell;version='[1.0.0,1.0.1)',\
io.swagger.core.v3.swagger-annotations;version='[2.0.7,2.0.8)',\
com.google.gson;version='[2.8.5,2.8.6)',\
com.fasterxml.jackson.core.jackson-annotations;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.core.jackson-core;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.core.jackson-databind;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.jaxrs.jackson-jaxrs-base;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider;version='[2.9.8, 2.9.9)'
As mentioned above, however, when running this simple app, Postman is giving me the following error when invoking the getPerson method:
No message body writer has been found for class com.ovloop.masterdata.party.pojo.provider.Person, ContentType: application/json
But when I replace the response type from Person to Response, and hand-generate the JSON, all works well:
#GET
#Path("/person")
#Produces(MediaType.APPLICATION_JSON)
#Operation(summary = "Get person with key", description = "Get person with key")
public Response getPerson(#PathParam("person") Long personId) {
Person person = new Person();
person.setPersonId("3245234");
person.setFirstName("Tom");
person.setLastName("Petty");
person.setAge(65);
Gson jsonConverter = new GsonBuilder().create();
return Response.status(Status.ACCEPTED).entity(jsonConverter.toJson(person)).build();
}
Unfortunately, this leaves the Person data type out of my generated swagger spec, which isn't good.
So my question is how do I register a Message Body Writer for custom POJO's within an OSGi application?
Thanks in advance for your feedback,
Randy
Paul had mentioned registering a JacksonJsonProvider. I had the impression adding fasterxml's jackson provider as a required bundle would do the trick. I instead swapped this out for org.apache.aries.jax.rs.jackson, and it all worked.
Below is my updated bndrun file:
-runfw: org.eclipse.osgi;version=3.13
-runee: JavaSE-1.8
-runprovidedcapabilities: ${native_capability}
-resolve.effective: active
-runproperties: \
osgi.console=,\
org.osgi.service.http.port=6000,\
osgi.console.enable.builtin=false
-runrequires: \
osgi.identity;filter:='(osgi.identity=org.apache.felix.gogo.shell)',\
osgi.identity;filter:='(osgi.identity=org.apache.felix.gogo.command)',\
bnd.identity;id='org.apache.aries.jax.rs.jackson',\
bnd.identity;id='org.apache.aries.jax.rs.jaxb.json',\
bnd.identity;id='com.xyz.masterdata.party.rest',\
bnd.identity;id='com.xyz.masterdata.party.pojo.provider',\
bnd.identity;id='com.xyz.masterdata.application.services'
-runbundles: \
com.xyz.masterdata.party.rest;version=snapshot,\
com.xyz.masterdata.party.pojo.provider;version=snapshot,\
org.apache.felix.configadmin;version='[1.9.8,1.9.9)',\
org.apache.felix.scr;version='[2.1.10,2.1.11)',\
ch.qos.logback.classic;version='[1.2.3,1.2.4)',\
ch.qos.logback.core;version='[1.2.3,1.2.4)',\
org.apache.aries.javax.jax.rs-api;version='[1.0.0,1.0.1)',\
org.apache.aries.jax.rs.whiteboard;version='[1.0.1,1.0.2)',\
org.apache.felix.gogo.runtime;version='[1.0.10,1.0.11)',\
org.apache.felix.http.jetty;version='[4.0.6,4.0.7)',\
org.apache.felix.http.servlet-api;version='[1.1.2,1.1.3)',\
org.apache.servicemix.specs.annotation-api-1.3;version='[1.3.0,1.3.1)',\
org.osgi.service.jaxrs;version='[1.0.0,1.0.1)',\
org.osgi.util.function;version='[1.1.0,1.1.1)',\
org.osgi.util.promise;version='[1.1.0,1.1.1)',\
slf4j.api;version='[1.7.25,1.7.26)',\
org.apache.felix.gogo.command;version='[1.0.2,1.0.3)',\
org.apache.felix.gogo.shell;version='[1.0.0,1.0.1)',\
io.swagger.core.v3.swagger-annotations;version='[2.0.7,2.0.8)',\
com.fasterxml.jackson.core.jackson-annotations;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.core.jackson-core;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.core.jackson-databind;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.jaxrs.jackson-jaxrs-base;version='[2.9.8,2.9.9)',\
com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider;version='[2.9.8,2.9.9)',\
com.xyz.masterdata.application.services;version=snapshot,\
org.apache.felix.configurator;version='[1.0.6,1.0.7)',\
com.fasterxml.jackson.module.jackson-module-jaxb-annotations;version='[2.9.8,2.9.9)',\
org.apache.aries.jax.rs.jackson;version='[1.0.2,1.0.3)',\
javax.json-api;version='[1.1.4,1.1.5)',\
org.apache.cxf.cxf-core;version='[3.3.1,3.3.2)',\
org.apache.cxf.cxf-rt-frontend-jaxrs;version='[3.3.1,3.3.2)',\
org.apache.cxf.cxf-rt-security;version='[3.3.1,3.3.2)',\
org.apache.cxf.cxf-rt-transports-http;version='[3.3.1,3.3.2)',\
org.apache.ws.xmlschema.core;version='[2.2.4,2.2.5)',\
org.apache.aries.jax.rs.jaxb.json;version='[1.0.0,1.0.1)'

How to retrieve data from DB and print in jsp using spring and hibernate?

I have already written the code for inserting my data into my DB but I'm a bit confused on how to retrieve that data in json format and print in my jsp view using a jQuery data table. I have written some code on retrieving but I'm still stuck. Please help.
Here are my code snippets:
entity class:
package model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
#Entity
public class Products {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
#Size(min=1)
private String productName;
#Min(value=1, message = "Value cannot be zero or negative")
private double unitPrice;
#Size(min=1)
private String productDescription;
#Size(min=1)
private String category;
#Min(value = 1, message = " Quantity should be greater than zero and positive")
#Max(value= 99, message = " Quantity limit exceeded, value should be less than 100")
private int productQty;
public Products() {}
public Products(int productId, String productName, double unitPrice, String productDescription, String category, int productQty) {
super();
this.productQty = productQty;
this.productId = productId;
this.productName = productName;
this.unitPrice = unitPrice;
this.productDescription = productDescription;
this.category = category;
}
public int getProductQty() {
return productQty;
}
public void setProductQty(int productQty) {
this.productQty = productQty;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
DAOImplementation class:
package model.daoimpl;
import java.util.List;
import org.hibernate.Session;
import model.config.HibernateUtil;
import model.dao.IProductsDAO;
import model.entity.Products;
public class ProductsDAOImpl implements IProductsDAO {
private Session sess;
public ProductsDAOImpl() {
sess = HibernateUtil.getSessionFactory().openSession();
}
public boolean insertProduct(Products p) {
boolean b = true;
try
{
sess.beginTransaction();
sess.save(p);
sess.getTransaction().commit();
}catch(Exception ex)
{
b = false;
sess.getTransaction().rollback();
ex.printStackTrace();
}
return b;
}
public List<Products> getProducts()
{
List<Products> lp = null;
try
{
sess.beginTransaction();
lp = sess.createQuery("from Product",Products.class).getResultList();
}catch(Exception ex)
{
ex.printStackTrace();
}
return lp;
}
}
controller class:
#Controller
public class ProductController {
#RequestMapping(value="/manageproducts", method= RequestMethod.GET)
public String manageProductPage() {
return "manageproducts";
}
#RequestMapping(value="/insertproducts",method = RequestMethod.POST)
public String addInserProductsPage(#ModelAttribute("Products")Products p) {
IProductsDAO ip = new ProductsDAOImpl();
boolean b = ip.insertProduct(p);
if(b)
return "success";
else
return "manageproducts";
}
#RequestMapping(value="/listproducts", method = RequestMethod.GET)
public List<Products> listAllProducts(){
IProductsDAO ip = new ProductsDAOImpl();
return ip.getProducts();
}
}
So as you can see I have created the getproducts function but I haven't created the view for displaying products for which I want to use the jQuery datatable, Also I'm a bit confused on how to map the view with my controller. So please help.
You can use Model to send your list to the view page
#RequestMapping(value="/listproducts", method = RequestMethod.GET)
public String listAllProducts(Model model){
IProductsDAO ip = new ProductsDAOImpl();
List<Products> products = ip.getProducts();
model.addAttribute ("products",products);
Return "your view name without .jsp";
}

Apache cxf basic authentication

I have a running example of apache cxf but when I run this wsdl file provided by my code is not authenticated I don't know how to pass the username and password to soapui
The code is:
ORDER.JAVA
package demo.order;
public class Order {
private String customerID;
private String itemID;
private int qty;
private double price;
// Constructor
public Order() {
}
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID) {
this.customerID = customerID;
}
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
package demo.order;
import javax.jws.WebService;
#WebService
public interface OrderProcess {
String processOrder(Order order);
}
package demo.order;
import javax.jws.WebService;
#org.apache.cxf.interceptor.InInterceptors (interceptors = {"demo.order.server.OrderProcessUserCredentialInterceptor" })
#WebService
public class OrderProcessImpl implements OrderProcess {
public String processOrder(Order order) {
System.out.println("Processing order...");
String orderID = validate(order);
return orderID;
}
/**
* Validates the order and returns the order ID
**/
private String validate(Order order) {
String custID = order.getCustomerID();
String itemID = order.getItemID();
int qty = order.getQty();
double price = order.getPrice();
if (custID != null && itemID != null && qty > 0 && price > 0.0) {
return "ORD1234";
}
return null;
}
}
_______________
package demo.order.client;
import demo.order.OrderProcess;
import demo.order.Order;
import org.apache.cxf.frontend.ClientProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class Client {
public Client() {
}
public static void main(String args[]) throws Exception {
ClassPathXmlApplicationContext context
= new ClassPathXmlApplicationContext(new String[] {"demo/order/client/client-beans.xml"});
OrderProcess client = (OrderProcess) context.getBean("orderClient");
OrderProcessClientHandler clientInterceptor = new OrderProcessClientHandler();
clientInterceptor.setUserName("John");
clientInterceptor.setPassword("password");
org.apache.cxf.endpoint.Client cxfClient = ClientProxy.getClient(client);
cxfClient.getOutInterceptors().add(clientInterceptor);
Order order = new Order();
order.setCustomerID("C001");
order.setItemID("I001");
order.setQty(100);
order.setPrice(200.00);
String orderID = client.processOrder(order);
String message = (orderID == null) ? "Order not approved" : "Order approved; order ID is " + orderID;
System.out.println(message);
}
}
_____________________
package demo.order.client;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class OrderProcessClientHandler extends AbstractSoapInterceptor {
public String userName;
public String password;
public OrderProcessClientHandler() {
super(Phase.WRITE);
addAfter(SoapPreProtocolOutInterceptor.class.getName());
}
public void handleMessage(SoapMessage message) throws Fault {
System.out.println("OrderProcessClientHandler handleMessage invoked");
DocumentBuilder builder = null;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc = builder.newDocument();
Element elementCredentials = doc.createElement("OrderCredentials");
Element elementUser = doc.createElement("username");
elementUser.setTextContent(getUserName());
Element elementPassword = doc.createElement("password");
elementPassword.setTextContent(getPassword());
elementCredentials.appendChild(elementUser);
elementCredentials.appendChild(elementPassword);
// Create Header object
QName qnameCredentials = new QName("OrderCredentials");
Header header = new Header(qnameCredentials, elementCredentials);
message.getHeaders().add(header);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
_________________________
CLIENTBEAN.XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:client id="orderClient" serviceClass="demo.order.OrderProcess" address="http://localhost:8080/OrderProcess" />
</beans>
_______________________
package demo.order.server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import demo.order.OrderProcess;
import demo.order.OrderProcessImpl;
public class OrderProcessServerStart {
public static void main(String[] args) throws Exception {
OrderProcess orderProcess = new OrderProcessImpl();
JaxWsServerFactoryBean server = new JaxWsServerFactoryBean();
server.setServiceBean(orderProcess);
server.setAddress("http://localhost:8787/OrderProcess");
server.create();
System.out.println("Server ready....");
Thread.sleep(5 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
___________________________
package demo.order.server;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class OrderProcessUserCredentialInterceptor extends AbstractSoapInterceptor {
private String userName;
private String password;
public OrderProcessUserCredentialInterceptor() {
super(Phase.PRE_INVOKE);
}
public void handleMessage(SoapMessage message) throws Fault {
System.out.println("OrderProcessUserCredentialInterceptor handleMessage invoked");
QName qnameCredentials = new QName("OrderCredentials");
// Get header based on QNAME
if (message.hasHeader(qnameCredentials )) {
Header header = message.getHeader(qnameCredentials);
Element elementOrderCredential= (Element) header.getObject();
Node nodeUser = elementOrderCredential.getFirstChild();
Node nodePassword = elementOrderCredential.getLastChild();
if (nodeUser != null) {
userName = nodeUser.getTextContent();
}
if (nodePassword != null) {
password = nodePassword.getTextContent();
}
}
System.out.println("userName retrieved from SOAP Header is " + userName);
System.out.println("password retrieved from SOAP Header is " + password);
// Perform dummy validation for John
if ("John".equalsIgnoreCase(userName) && "password".equalsIgnoreCase(password)) {
System.out.println("Authentication successful for John");
} else {
throw new RuntimeException("Invalid user or password");
}
}
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;
}
}
_______________
I have these files and the program compile succesfully and creting the wsdl file
but its not working on soapui means username and password are null when requsting through soapui,
please suggest me how to overcome this problem of basic authentication
and how to pass the usename and password to soap ui
For Basic authentication in SOAP UI, navigate to your Request, single click on it will display a panel in the left bottom corner. Your config for BASIC Authentication should be something like this:
Add your username and password to the appropriate fields.
For your client I see you are using Spring. So jaxws:client provides username and password attributes for authentication. You can add them like this:
<jaxws:client id="orderClient"
serviceClass="demo.order.OrderProcess"
address="http://localhost:8080/OrderProcess"
username="yourUsername"
password="yourPassword"/>

Resources