Apache cxf basic authentication - spring

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"/>

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 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";
}

DuplicateKeyException in mongodb and spring boot

I am using Spring Boot and MongoDB and I am able to store a document in MongoDB successfully. When I was trying to insert a second document, it is showing duplicatekeyexception. The total message of exception is as follows:
com.mongodb.DuplicateKeyException: Write failed with error code 11000
and error message 'E11000 duplicate key error collection:
Football_Admin.SignUp index: id dup key: { : 0 }'
The code is as follows:
SignUpRepository.java
package com.admin.Repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.admin.Model.SignUp;
#Repository
public interface SignUpRepository extends MongoRepository<SignUp,String>{
}
Controller
#Controller
#RequestMapping("/SignIn_Up")
public class HomeController {
#Autowired
SignUpRepository repository;
#RequestMapping(value = "/addadmin", method = RequestMethod.POST)
public String addAdmin(#ModelAttribute("SignUp") SignUp sign) throws NoSuchAlgorithmException,InvalidKeySpecException {
String originalPassword = sign.getPassword();
String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
String email = sign.getEmail();
String fullname = sign.getFullName();
try {
sign.setEmail(email);
sign.setFullName(fullname);
sign.setPassword(generatedSecuredPasswordHash);
repository.save(sign);
}
catch (DuplicateKeyException e) {
e.printStackTrace();
}
System.out.println(generatedSecuredPasswordHash);
System.out.println("Email name is:"+sign.getEmail());
System.out.println("Full Name is:"+sign.getFullName());
System.out.println("Password is:"+sign.getPassword());
return "welcome";
}
Entity
package com.admin.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="SignUp")
public class SignUp {
#Id
private int id;
private String fullName;
private String email;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return id+""+fullName+""+password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
MongoDb driver don't know how to create a unique Id of type int when inserting so you received unique index exception
So either you manually create and maintain your index (quite hard) or change your id field type to ObjectId

Spring JPA annotation based web app

I am have JSON message as request object coming into Controller.
I am trying to map the object to model class in the Controller class but unable to do so.
Can anyone help me with the procedure.
package com.firm.trayportal.contoller;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.firm.trayportal.jparepository.trayMoveRepository;
import com.firm.trayportal.jparepository.LocationRepository;
import com.firm.trayportal.jparepository.StopoffRepository;
import com.firm.trayportal.model.trayMove;
import com.firm.trayportal.model.Location;
import com.firm.trayportal.model.Stopoff;
import com.firm.trayportal.service.trayMoveService;
#RestController
public class trayPortalquoteController {
/* #Autowired
JdbcTemplate template;*/
private trayMove trayMove;
private Location location;
private Stopoff stopoff;
// Service Layer
private trayMoveService trayMoveService;
private static final Logger logger = Logger
.getLogger(trayPortalquoteController.class);
#RequestMapping(value = "/quote", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} )
public ThumbsUp getActivetrayOrder(HttpServletRequest request, #RequestBody trayquoteRto rto) {
logger.debug("Start processing");
if (rto != null) {
logger.debug(String.format("Driver: %s/Load Number: %s/Stop %s",
rto.getDriver(), rto.getLn(), rto.getStops() != null
&& rto.getStops().get(0) != null ? rto.getStops()
.get(0).getStop() : "?"));
/*
* Querying String insertSql =
* "insert into tray_move (move_type, carrier_id, ln) values(?,?,?)"
* ;
*
* Object[] params = new Object[] {rto.getType(), rto.getDriver(),
* rto.getLn()}; // define SQL types of the arguments int[] types =
* new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
*/
// execute insert query to insert the data
// return number of row / rows processed by the executed query
try {
// int row = template.update(insertSql, params, types);
trayMove trayMove = new trayMove();
trayMove = savetrayInfo(rto);
// trayMoveService.populate(trayMove); // return type ?
// trayMove row = trayMoveRepo.saveAndFlush(trayMove);
// logger.debug(row + " row inserted.");
} catch (Exception _ex) {
logger.debug("Exception executing sql query:( Message: "
+ _ex.getMessage());
logger.debug("Exception executing sql query:( Message: "
+ _ex.getStackTrace());
}
} else {
logger.debug("quote RTO is NULL");
}
return new ThumbsUp();
}
private Stopoff saveStopOff(trayquoteRto rto) {
// TODO Auto-generated method stub
return null;
}
private Location saveLocationInfo(trayquoteRto rto) {
// TODO Auto-generated method stub
return null;
}
public trayMove savetrayInfo(trayquoteRto rto) {
System.out.println("In savetrayInfo method");
//trayMove.setMoveId(100005);
trayMove.setMoveType("IPU");
System.out.println("In savetrayInfo MoveType");
System.out.println("setMoveType");
trayMove.setCarrierId(rto.getDriver());
trayMove.setLn(rto.getLn());
// TODO:rto.getName(); ??
trayMove.setShippersno(rto.getShippersno());
return trayMove;
}
public Location saveLocInfo(trayquoteRto rto) {
// location.set
// location.setAddress1(address1);
return location;
}
}
/*
* create table tray_move ( move_type varchar(16), carrier_id varchar(32), ln
* varchar(32) );
*/
class trayquoteRto {
private String type;
private String driver;
private String ln;
private String shippersno;
private String oramplocation;
private String orampadd1;
private String orampadd2;
private String orampphone;
private String orampstate;
private String orampzip;
private String dramplocation;
private String drampadd1;
private String drampadd2;
private String drampphone;
private String drampstate;
private String drampzip;
private List<Stops> stops = new ArrayList<Stops>();
public String getType() {
return type;
}
public String getDriver() {
return driver;
}
public String getLn() {
return ln;
}
public String getShippersno() {
return shippersno;
}
public String getOramplocation() {
return oramplocation;
}
public String getOrampadd1() {
return orampadd1;
}
public String getOrampadd2() {
return orampadd2;
}
public String getOrampphone() {
return orampphone;
}
public String getOrampstate() {
return orampstate;
}
public String getOrampzip() {
return orampzip;
}
public String getDramplocation() {
return dramplocation;
}
public String getDrampadd1() {
return drampadd1;
}
public String getDrampadd2() {
return drampadd2;
}
public String getDrampphone() {
return drampphone;
}
public String getDrampstate() {
return drampstate;
}
public String getDrampzip() {
return drampzip;
}
public List<Stops> getStops() {
return stops;
}
}
class Stops {
String name;
String add1;
String add2;
String city;
String ext;
String phone;
String st;
String zip;
Integer stop;
Date apptment1;
Date apptment2;
public String getName() {
return name;
}
public String getAdd1() {
return add1;
}
public String getAdd2() {
return add2;
}
public String getCity() {
return city;
}
public String getExt() {
return ext;
}
public String getPhone() {
return phone;
}
public String getSt() {
return st;
}
public String getZip() {
return zip;
}
public Date getApptment1() {
return apptment1;
}
public Date getApptment2() {
return apptment2;
}
public Integer getStop() {
return stop;
}
}
class ThumbsUp {
private String message = "success";
public String getMessage() {
return message;
}
}
#Service
#Repository
public class trayMoveService {
#Autowired
private trayMoveRepository trayMoveRepo;
#Qualifier("trayMove")
public void populate(trayMove dm) {
trayMoveRepo.saveAndFlush(dm);
}
}
#Transactional
public interface trayMoveRepository extends JpaRepository<trayMove, Integer>{
}
The setter method doesnt work. I think m missing some annotations. Can someone direct me to the tutorial please ?
The application is Spring JPA(EclipseLink) annotation based.

Facing difficulty with Hibernate HQL when applying it to H2

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.

Resources