Gradle Jax-RS Mysql Jetty project not working - java

I'm using gradle and my project is building fine. When I use Jetty to deploy the war I don't see my object.
apply plugin: 'war'
apply plugin: 'eclipse'
repositories {
mavenCentral()
}
dependencies {
compile 'org.glassfish.jersey.media:jersey-media-json-jackson:2.16'
compile 'org.glassfish.jersey.bundles:jaxrs-ri:2.16'
}
compileJava {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
Java Files
Persons.java
package workspace.TomcatJNDIProject;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Id;
public class Persons implements Serializable {
private static final long serialVersionUID = 1L;
#Basic(optional = false)
#Column(name="person_id")
#Id
private int personId;
#Basic(optional = false)
#Column(name="name")
#Id
private String name;
private int Age;
private Date DOB;
private String email;
#JsonProperty(value = "person_id")
public int getId() {
return personId;
}
public void setId(int id) {
this.personId = id;
}
#JsonProperty(value = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#JsonProperty(value = "age")
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
#JsonProperty(value = "dateofbirth")
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
#JsonProperty(value = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
PeopleDAO.java
package workpace.TomcatJNDIProject;
import javax.ws.rs.core.Response;
import com.people.model.Persons;
public interface PeopleDAO {
public Response getPerson(int id);
public Response getAllPeople();
}
PeopleDAOImpl.java
package workpace.TomcatJNDIExample;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
import com.poeple.dao.PeopleDAO;
import com.poeple.model.Persons;
import com.poeple.model.StatusMessage;
import com.poeple.util.Database;
public class PeopleDAOImpl implements PeopleDAO {
private DataSource datasource = Database.getDataSource();
private Logger logger = Logger.getLogger(PeopleDAOImpl.class);
#Override
public Response getPerson(int id) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
People person = null;
String sql = "select people_id, first_name, last_name, address, city, "
+ "state, zip_code, is_active from Person where people_id = ?";
try {
conn = datasource.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
person = new People();
person.setId(rs.getInt("Person_ID"));
person.setName(rs.getString("Name"));
person.setAge(rs.getInt("Age"));
person.setDOB(rs.getDate("DateOfBirth"));
person.setEmail(rs.getString("Email"));
persons.add(person);
} else {
logger.error(String.format("Person with ID of %d is not found.", id));
StatusMessage statusMessage = new StatusMessage();
statusMessage.setStatus(Status.NOT_FOUND.getStatusCode());
statusMessage.setMessage(String.format("Customer with ID of %d is not found.", id));
return Response.status(404).entity(statusMessage).build();
}
} catch (SQLException e) {
logger.error("Error: " + e.getMessage());
e.printStackTrace();
}
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.error("Error closing resultset: " + e.getMessage());
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
logger.error("Error closing PreparedStatement: " + e.getMessage());
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logger.error("Error closing connection: " + e.getMessage());
e.printStackTrace();
}
}
}
return Response.status(200).entity(people).build();
}
}
TomcatJNDIService.java
package workpace.TomcatJNDIProject;
import java.io.IOException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import com.people.dao.PeopleDAO;
import com.people.dao.impl.PeopleDAOImpl;
import com.people.model.Persons;
#Path("tomcat")
public class TomcatJNDI {
private Logger logger = Logger.getLogger(TomcatJNDIExample.class);
#GET
#Path("/people/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response getPerson(#DefaultValue("0") #QueryParam("id") int id) {
PeopleDAO daoImpl = new PeopleDAOImpl();
logger.info("Inside getPerson...");
Response resp = daoImpl.getPerson(id);
return resp;
}
}
StatusMessage.java
package com.avaldes.model;
import org.codehaus.jackson.annotate.JsonProperty;
public class StatusMessage {
private Integer status;
private String message;
public StatusMessage() {
}
#JsonProperty(value = "status_code")
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
#JsonProperty(value = "message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I'm using
gradle build war
java -jar jetty-runner-9.1.0.M0.jar --port 8081 build/libs/Sample.war
And don't know where to get the error from basically. I don't see the json object but I also not sure how to log with jax-rs. Thank you in advance.

jetty-runner does not create a logs directory for server based logging.
If you do nothing to configure logging in your war, then all of the Jetty logs are presented on the console.
However, since you are using JAX-RS, it would be wise to configure whatever logging libraries that JAX-RS is using in your war to do whatever you need it to do (set logger levels, write to file, etc)

Related

Error when trying to map foreing key in SpringBoot

I'm trying to create an API for saving a Person and its Address, like in this model:
And i'm getting this error when trying to save an address with a foreing key:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error:
Cannot construct instance of `com.apitest.api.model.Pessoa` (although at least one Creator exists):
no int/Int-argument constructor/factory method to deserialize from Number value (1)]
I know it seems like a parser error, but it just happens when i do a request that contains the fk field, so:
This is a valid request:
{
"logradouro": "test",
"cep": "354",
"numero": "test",
"cidade": "test"
}
This one i get a 400 bad request:
{
"logradouro": "null",
"cep": "354",
"numero": "null",
"cidade": "null",
"pessoa": 1
}
Just by adding the fk field, like i said.
Models:
Person
package com.apitest.api.model;
import java.util.Date;
import java.util.List;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
#Entity
#Table(name = "pessoa")
public class Pessoa {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "nome")
private String nome;
#Column(name = "dataNascimento")
private Date dataNascimento;
public Pessoa(Integer id, String nome, Date dataNascimento) {
this.id = id;
this.nome = nome;
this.dataNascimento = dataNascimento;
}
public Pessoa(){
};
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
}
Address
package com.apitest.api.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
#Entity
#Table(name = "endereco")
public class Endereco {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id_endereco;
#Column(name = "logradouro")
private String logradouro;
#Column(name = "cep")
private String cep;
#Column(name = "numero")
private String numero;
#Column(name = "cidade")
private String cidade;
#ManyToOne
#JoinColumn(name = "id")
private Pessoa pessoa;
public Endereco(Integer id_endereco, String logradouro, String cep, String numero, String cidade, Pessoa pessoa) {
this.id_endereco = id_endereco;
this.logradouro = logradouro;
this.cep = cep;
this.numero = numero;
this.cidade = cidade;
this.pessoa = pessoa;
}
public Endereco(){
};
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
public Integer getId_endereco() {
return id_endereco;
}
public void setId_endereco(Integer id_endereco) {
this.id_endereco = id_endereco;
}
}
Controllers:
Person
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.apitest.api.model.Pessoa;
import com.apitest.api.service.PessoaService;
#RestController
public class PessoaController {
#Autowired
private PessoaService pessoaService;
#PostMapping("/pessoas")
public ResponseEntity<Pessoa> createPessoa(#RequestBody Pessoa pessoa){
return ResponseEntity.ok().body(this.pessoaService.createPessoa(pessoa));
}
}
Address
package com.apitest.api.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.apitest.api.model.Endereco;
import com.apitest.api.service.EnderecoService;
#RestController
public class EnderecoController {
#Autowired
private EnderecoService enderecoService;
#PostMapping("/endereco")
public ResponseEntity<Endereco> createEndereco(#RequestBody Endereco endereco){
return ResponseEntity.ok().body(this.enderecoService.createEndereco(endereco));
}
}
Service:
Person
package com.apitest.api.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.apitest.api.model.Pessoa;
import com.apitest.api.repository.PessoaRepository;
#Service
#Transactional
public class PessoaServiceImpl implements PessoaService {
#Autowired
private PessoaRepository pessoaRepository;
#Override
public Pessoa createPessoa(Pessoa pessoa) {
return pessoaRepository.save(pessoa);
}
#Override
public Pessoa updatePessoa(Pessoa pessoa) {
Optional<Pessoa> pessoaDb = this.pessoaRepository.findById(pessoa.getId());
Pessoa pessoaUpdate = pessoaDb.get();
pessoaUpdate.setId(pessoa.getId());
pessoaUpdate.setNome(pessoa.getNome());
return pessoaUpdate;
}
#Override
public Pessoa getPessoaById(Pessoa pessoa) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<Pessoa> getAllPessoa() {
// TODO Auto-generated method stub
return null;
}
#Override
public void deletePessoa(long pessoaId) {
// TODO Auto-generated method stub
}
}
Address
package com.apitest.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apitest.api.model.Endereco;
import com.apitest.api.repository.EnderecoRepository;
import com.apitest.api.repository.PessoaRepository;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class EnderecoServiceImpl implements EnderecoService {
#Autowired
private EnderecoRepository enderecoRepository;
#Override
public Endereco createEndereco(Endereco endereco) {
return enderecoRepository.save(endereco);
}
}
I have already tried to use JsonCreator and JsonProperty annotations but did not worked for me...
Any help would be appreciated.
You're getting this error because you're sending the value of "1" for the object Pessoa. You need to pass the fields in the object, something like this should work.
{ "logradouro": "null", "cep": "354", "numero": "null", "cidade": "null", "pessoa": {"id": 1} }
Also, I'm not sure what "null" means here, but if you want those fields to be null, don't send them. The way this is written, you're going to end up with the word null everywhere.

JPA with Spring MVC doesn't insert into database using persist

I am using spring 4 and hibernate 4 to create some web services and when I try to retrieve data from the database. It work fine but the problem is when I try to insert data.
When I lunch the project as a java application every thing work fine. The problem is only when I lunch it on the server and I am using tomcat.
This is my entity:
package com.pfe.ecole.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
#SuppressWarnings("serial")
#Entity
public class Specialite implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String specialite;
#ManyToMany(mappedBy="specialites")
#JsonIgnore
private List<Professeur> professeurs;
public List<Professeur> getProfesseurs() {
return professeurs;
}
public void setProfesseurs(List<Professeur> professeurs) {
this.professeurs = professeurs;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSpecialite() {
return specialite;
}
public void setSpecialite(String specialite) {
this.specialite = specialite;
}
public Specialite() {
// TODO Auto-generated constructor stub
}
public Specialite(int id, String specialite) {
super();
this.id = id;
this.specialite = specialite;
}
public Specialite(String specialite) {
super();
this.specialite = specialite;
}
}
package com.pfe.ecole.entity;
import java.io.Serializable;
import java.util.Set;
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.ManyToMany;
#SuppressWarnings("serial")
#Entity
public class Professeur implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#Column(unique=true, nullable=false)
private String cin;
#Column(unique=true, nullable=false)
private int tel;
#ManyToMany(targetEntity=Specialite.class, cascade = CascadeType.PERSIST)
private Set<Specialite> specialites;
private String nom;
private String prenom;
#Column(unique=true, nullable=false)
private String email;
private String adresse;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Set<Specialite> getSpecialites() {
return specialites;
}
public void setSpecialite(Set<Specialite> specialites) {
this.specialites = specialites;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public Professeur() {
// TODO Auto-generated constructor stub
}
public Professeur(String cin, int tel, Set<Specialite> specialites, String nom, String prenom, String email,
String adresse) {
super();
this.cin = cin;
this.tel = tel;
this.specialites = specialites;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.adresse = adresse;
}
public Professeur(long id, String cin, int tel, Set<Specialite> specialites, String nom, String prenom,
String email, String adresse) {
super();
this.id = id;
this.cin = cin;
this.tel = tel;
this.specialites = specialites;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.adresse = adresse;
}
}
and this is my services
package com.pfe.ecole.services;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pfe.ecole.entity.Agent;
import com.pfe.ecole.entity.Specialite;
#Service("specialiteImpl")
#Transactional
public class SpecialiteImpl implements ISpecialite{
#PersistenceContext
private EntityManager em;
#Override
public Specialite add(Specialite specialite) {
em.persist(new Agent());
return specialite;
}
#Override
public Specialite update(Specialite specialite) {
em.persist(specialite);
return specialite;
}
#SuppressWarnings("unchecked")
#Override
public List<Specialite> listAllSpecialite() {
return em.createQuery("select s from Specialite s").getResultList();
}
}
package com.pfe.ecole.services;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.entity.Specialite;
#Service("professeurImpl")
#Transactional
public class ProfesseurImpl implements IProfesseur{
#PersistenceContext
private EntityManager em;
#SuppressWarnings("unchecked")
#Override
public List<Professeur> listAll(int page, int items) {
List<Professeur> profList;
profList=em.createQuery("select p from Professeur p order by p.prenom").setFirstResult(page-1).setMaxResults(items).getResultList();
return profList;
}
#Override
public Professeur findByCin(int cin) {
Query req=em.createQuery("select p from Professeur p where p.cin=:cin").setParameter("cin", cin);
try{
return (Professeur) req.getSingleResult();
}
catch(NoResultException nrEx) {
return null;
}
}
#SuppressWarnings("unchecked")
#Override
public List<Professeur> findByNom(String nom) {
Query req = em.createQuery("select p from Professeur p where p.nom=:nom ").setParameter("nom", nom);
return req.getResultList();
}
#Override
public List<Professeur> listProfBySpec(Specialite spec) {
List<Professeur> profs = new ArrayList<Professeur>();
profs.addAll(spec.getProfesseurs());
return profs;
}
#Override
public Professeur add(Professeur professeur) {
em.persist(professeur);
return professeur;
}
#Override
public Professeur update(Professeur professeur) {
em.persist(professeur);
return professeur;
}
#Override
public int count() {
// TODO Auto-generated method stub
return (int) em.createQuery("select COUNT(p) from Professeur p").getFirstResult();
}
}
and this is the controller
package com.pfe.ecole.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
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 org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.pfe.ecole.entity.Specialite;
import com.pfe.ecole.services.ISpecialite;
#Controller
#RestController
#EnableWebMvc
#CrossOrigin
public class SpecialiteCtrl {
#Autowired
ISpecialite metier;
#RequestMapping(value="/specialites",method=RequestMethod.GET)
#ResponseBody Map<String, List<Specialite>> get(){metier.add(new Specialite("ddd"));
Map<String, List<Specialite>> result = new HashMap<String,List<Specialite>>();
result.put("content", metier.listAllSpecialite());
return result;
}
}
package com.pfe.ecole.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.services.IProfesseur;
import com.pfe.ecole.services.Page;
#Controller
#RestController
#EnableWebMvc
#CrossOrigin
public class ProfCtrl {
#Autowired
IProfesseur metier;
#RequestMapping(value="/teacher",method=RequestMethod.POST)
#ResponseBody Professeur add(#RequestBody Professeur professeur) {
return metier.add(professeur);
}
#RequestMapping(value="/teachers/{page}/{items}",method=RequestMethod.GET)
#ResponseBody Page getByParm(#PathVariable("page") int page, #PathVariable("items") int items){
return getAll(page, items);
}
#RequestMapping(value="/teachers/{page}",method=RequestMethod.GET)
#ResponseBody Page getByParm(#PathVariable("page") int page){
return getAll(page, 10);
}
#RequestMapping(value="/teachers",method=RequestMethod.GET)
#ResponseBody Page getByParm(){
return getAll(1, 10);
}
private Page getAll(int page, int items){
return new Page(page,metier.count(),metier.listAll(page, items));
}
}
this is the test that works as java application
public static void main(String[] args) {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("root-context.xml");
ISpecialite m = (ISpecialite) context.getBean("specialiteImpl");
Specialite s= new Specialite("Web Dev");
m.add(s);
}
This is the error I am getting
javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
adding this annotation to service solved the problem #EnableTransactionManagement

Getting Date as null when using java.sql.Date

I am trying to insert the date into database and I am using java.sql.Date but the problem when user is submitting the form I am getting Null value. As per some restriction I am only allowed to use java.sql.Date not util.Date.
Entity
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="Users")
public class Users {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="User_ID")
private int ID;
#Column(name="User_first_name")
#NotEmpty(message="Field cannot be left blank")
private String First_Name;
#Column(name="user_last_name")
private String Last_Name;
#Column(name="user_contact")
private int Contact;
#Column(name="user_email")
private String Email;
#Column(name="user_date_birth")
#DateTimeFormat(pattern="dd/MM/yyyy")
private Date DateOfBirth;
#Column(name="user_joining_date")
private Date DateOfJoining;
#Column(name="user_salary")
#NotNull
private int Salary;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public int getContact() {
return Contact;
}
public void setContact(int contact) {
Contact = contact;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public Date getDateOfBirth() {
return DateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
DateOfBirth = dateOfBirth;
}
public Date getDateOfJoining() {
return DateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
DateOfJoining = dateOfJoining;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
}
Controller
package com.example.crud;
import java.text.SimpleDateFormat;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.crud.entities.Users;
import com.example.crud.service.TaskService;
#Controller
public class HomeController {
#Autowired
private TaskService service;
private Logger logger = LoggerFactory.getLogger(HomeController.class);
#InitBinder
public void initBinder(WebDataBinder binder){
System.out.println("exe");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(java.sql.Date.class,"DateOfBirth", new CustomDateEditor(sdf, true));
}
#RequestMapping(value="/Add", method=RequestMethod.GET)
public String index(Map<String, Object> model){
Users users = new Users();
model.put("users", users);
logger.debug("users");
return "home";
}
#RequestMapping(value="/Register", method=RequestMethod.POST)
public String Register(#ModelAttribute("users") Users users, BindingResult result, Model model){
System.out.println(users.getFirst_Name());
System.out.println(users.getDateOfBirth());
// service.Register(users);
return "home";
}
}
Register your own custom editor.
public class SqlDateEditor extends PropertyEditorSupport {
private DateFormat dateFormat;
public SqlDateEditor (final DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
#Override
public void setAsText(String text) {
try {
setValue(new java.sql.Date(this.dateformat.parse(text).getTime())
} catch (ParseException e) {
throw new IllegalArgumentException("Could not parse date: " + e.getMessage());
}
}
#Override
public String getAsText() {
java.sql.Date value = (java.sql.Date) getValue();
return (value != null ? this.dateFormat.format(value) : "");
}
}
At your controller:
#InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(java.sql.Date.class, new SqlDateEditor(new SimpleDateFormat("dd/MM/yyyy")));
}

Remove a filed from JSON response?

I have already created a restful api using java and glassfish but I'm facing a problem (not an error).
When I receive the JSON response from my API it works fine but contains the name of the beans.
{"***countriesBean***":[ //(I need my response without this field)
{"CountryID":"3","CountryName":"asdasdasd","DefaultCurrencyID":"0","DefaultLanguageID":"0"},{"CountryID":"16","CountryName":"sddd","DefaultCurrencyID":"1","DefaultLanguageID":"0"},{"CountryID":"1","CountryName":"Lebanon","DefaultCurrencyID":"3","DefaultLanguageID":"0"},{"CountryID":"2","CountryName":"asdasd","DefaultCurrencyID":"0","DefaultLanguageID":"2"}
]
}
this is the bean
package beans;
import javax.ws.rs.FormParam;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author ahmad.s
*/
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class CountriesBean {
// #XmlElement
#XmlElement(name="CountryID")
private Integer COUNTRY_ID;
#XmlElement(name="CountryName")
private String COUNTRY_NAME;
#XmlElement(name="LanguageID")
private Integer LANGUAGE_ID;
#XmlElement(name="DefaultCurrencyID")
private Integer DEFAULT_CURRENCY_ID;
#XmlElement(name="DefaultLanguageID")
private Integer DEFAULT_LANGUAGE_ID;
#XmlElement(name="TaskID")
private Integer TASK_ID;
#XmlElement(name="CurrencyID")
private Integer CURRENCY_ID;
public Integer getCURRENCY_ID() {
return CURRENCY_ID;
}
public void setCURRENCY_ID(Integer CURRENCY_ID) {
this.CURRENCY_ID = CURRENCY_ID;
}
public Integer getTASK_ID() {
return TASK_ID;
}
public void setTASK_ID(Integer TASK_ID) {
this.TASK_ID = TASK_ID;
}
public Integer getDEFAULT_LANGUAGE_ID() {
return DEFAULT_LANGUAGE_ID;
}
public void setDEFAULT_LANGUAGE_ID(Integer DEFAULT_LANGUAGE_ID) {
this.DEFAULT_LANGUAGE_ID = DEFAULT_LANGUAGE_ID;
}
public Integer getDEFAULT_CURRENCY_ID() {
return DEFAULT_CURRENCY_ID;
}
public void setDEFAULT_CURRENCY_ID(Integer DEFAULT_CURRENCY_ID) {
this.DEFAULT_CURRENCY_ID = DEFAULT_CURRENCY_ID;
}
public Integer getCOUNTRY_ID() {
return COUNTRY_ID;
}
public void setCOUNTRY_ID(Integer COUNTRY_ID) {
this.COUNTRY_ID = COUNTRY_ID;
}
public String getCOUNTRY_NAME() {
return COUNTRY_NAME;
}
public void setCOUNTRY_NAME(String COUNTRY_NAME) {
this.COUNTRY_NAME = COUNTRY_NAME;
}
public Integer getLANGUAGE_ID() {
return LANGUAGE_ID;
}
public void setLANGUAGE_ID(Integer LANGUAGE_ID) {
this.LANGUAGE_ID = LANGUAGE_ID;
}
}
this the Countries Service Class
package service;
import beans.CountriesBean;
import com.xperteam.DBC.DataBaseConnection;
import entity.Countries;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
*
* #author ahmad.s
*/
#Stateless
#Path("countries")
public class CountriesFacadeREST extends AbstractFacade<Countries> {
#PersistenceContext(unitName = "WeddingRestApiPU")
private EntityManager em;
public CountriesFacadeREST() {
super(Countries.class);
}
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(Countries entity) {
super.create(entity);
}
#PUT
#Path("{id}")
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void (#PathParam("id") Long id, Countries entity) {
super.(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Long id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Countries find(#PathParam("id") Long id) {
return super.find(id);
}
#GET
#Override
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Countries> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Countries> findRange(#PathParam("from") Integer from, #PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String countREST() {
return String.valueOf(super.count());
}
#Override
protected EntityManager getEntityManager() {
return em;
}
#GET
#Path("/getAllCountries") // webresources/beans.contactbean/getContactID?ContactID=? get contact info by id
#Produces(MediaType.APPLICATION_JSON)
public ArrayList<CountriesBean> getAllCountries() {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<CountriesBean> CountriesList = new ArrayList<CountriesBean>();
CountriesBean CountriesBean = null;
StringBuffer query = new StringBuffer();
query.append(" SELECT ");
query.append(" COUNTRIES.COUNTRY_ID, ");
query.append(" COUNTRIES_TRANS.COUNTRY_TRANS_NAME,COUNTRIES.DEFAULT_CURRENCY_ID,COUNTRIES.DEFAULT_LANGUAGE_ID ");
query.append(" FROM COUNTRIES INNER JOIN COUNTRIES_TRANS ON COUNTRIES_TRANS.COUNTRY_ID=COUNTRIES.COUNTRY_ID ");
query.append(" WHERE COUNTRIES_TRANS.LANGUAGE_ID = 1 ");
int counter = 1;
try {
DataBaseConnection DataBaseConnection = new DataBaseConnection();
Connection con = DataBaseConnection.GetConnection();
preparedStatement = con.prepareStatement(new String(query));
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
CountriesBean = new CountriesBean();
CountriesBean.setCOUNTRY_ID(resultSet.getInt("COUNTRY_ID"));
CountriesBean.setCOUNTRY_NAME(resultSet.getString("COUNTRY_TRANS_NAME"));
CountriesBean.setDEFAULT_CURRENCY_ID(resultSet.getInt("DEFAULT_CURRENCY_ID"));
CountriesBean.setDEFAULT_LANGUAGE_ID(resultSet.getInt("DEFAULT_LANGUAGE_ID"));
CountriesList.add(CountriesBean);
}
con.close();
} catch (SQLException sqlException) {
CountriesList = null;
System.out.println("getWeddingType : " + sqlException.getMessage());
} catch (NamingException ex) {
Logger.getLogger(CountriesFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
} finally {
query = null;
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (Exception exception) {
}
}
return CountriesList;
}
}
I cannot verify your problem without your code.
Please see a basic example with your expectation:
public class Customer {
String fullName;
String email;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer{" +
"fullName='" + fullName + '\'' +
", email='" + email + '\'' +
'}';
}
}
..
#Path("/services")
public class MaisonService {
#GET
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public Customer getSampleCustomer() {
Customer sampleCustomer = new Customer();
sampleCustomer.setFullName("Trinh Toan Trung");
sampleCustomer.setEmail("trinhtoantrung#gmail.com");
return sampleCustomer;
}
..
The output:
{"email":"trinhtoantrung#gmail.com","fullName":"Trinh Toan Trung"}
There are many simple ways to do it, following is the most simplest as you are able to get the response as your POJO or DTO clas
MyResponse ob = new ObjectMapper().readValue(jsonString, MyResponse.class);

Simple json structure throwing error when converting to pojo

I am attempting to convert a json String to a java pojo but receive this error when parsing :
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class com.json.pojo.Userdatum] from JSON String; no single-String constructor/factory method
at org.codehaus.jackson.map.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:379)
at org.codehaus.jackson.map.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:268)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromString(BeanDeserializer.java:765)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:585)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)
at com.json.pojo.ParseJson.main(ParseJson.java:21)
here is my conversion code :
package com.json.pojo;
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
public class ParseJson {
public static void main(String args[]){
String str = "\"userdata\": [ {\"userid\": \"user1\",\"title\": \"Next weeks preview\", \"date\": \"19/12/2013\",\"time\": \"15:00\"}";
org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
com.json.pojo.Userdatum user = mapper.readValue(str, com.json.pojo.Userdatum.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And my pojo :
package com.json.pojo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("com.googlecode.jsonschema2pojo")
#JsonPropertyOrder({
"userdata"
})
public class UserData {
#JsonProperty("userdata")
private List<Userdatum> userdata = new ArrayList<Userdatum>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("userdata")
public List<Userdatum> getUserdata() {
return userdata;
}
#JsonProperty("userdata")
public void setUserdata(List<Userdatum> userdata) {
this.userdata = userdata;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.json.pojo;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("com.googlecode.jsonschema2pojo")
#JsonPropertyOrder({
"userid",
"title",
"date",
"time"
})
public class Userdatum {
#JsonProperty("userid")
private String userid;
#JsonProperty("title")
private String title;
#JsonProperty("date")
private String date;
#JsonProperty("time")
private String time;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("userid")
public String getUserid() {
return userid;
}
#JsonProperty("userid")
public void setUserid(String userid) {
this.userid = userid;
}
#JsonProperty("title")
public String getTitle() {
return title;
}
#JsonProperty("title")
public void setTitle(String title) {
this.title = title;
}
#JsonProperty("date")
public String getDate() {
return date;
}
#JsonProperty("date")
public void setDate(String date) {
this.date = date;
}
#JsonProperty("time")
public String getTime() {
return time;
}
#JsonProperty("time")
public void setTime(String time) {
this.time = time;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
There must be something wrong with the generated pojo but it looks correct ?
This works, for some reason I needed to use the #JsonProperty even though my properties are matching the json attributes, I did'nt think they were required.
package com.json.pojo;
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
public class ParseJson {
public static void main(String args[]){
String str = "{ \"userdata\": [ {\"userid\": \"user1\",\"title\": \"Next weeks preview\", \"date\": \"19/12/2013\",\"time\": \"15:00\"} ] }";
org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
try {
com.json.pojo.RequestBean user = mapper.readValue(str, com.json.pojo.RequestBean.class);
System.out.println(user.getToAdd().size());
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.json.pojo;
import java.io.Serializable;
import java.util.List;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class RequestBean implements Serializable {
#JsonProperty("userdata")
private List<SimpleBean> userdata;
public List<SimpleBean> getToAdd() {
return userdata;
}
public void setToAdd(List<SimpleBean> toAdd) {
this.userdata = toAdd;
}
// constructors, getters, setters
}
package com.json.pojo;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class SimpleBean implements Serializable {
#JsonProperty("userid")
private String userid;
#JsonProperty("title")
private String title;
#JsonProperty("date")
private String date;
#JsonProperty("time")
private String time;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}

Categories

Resources