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);
Related
I have a problem in accessing get method of a generic class in REST API project. there are no errors but it returns null. here I mention the code. The idea working fine when I implemented without REST API. Insert and GetALL methods are working fine in REST API but problem is Repo class Get method couldn't work with REST.
package lk.ac.jfn.vau.DeptApi.Model;
public class Department extends PrimaryID<Long>{
private String Name;
private String Location;
public Department() {
//super();
}
public Department(long id, String name, String location) {
super(id);
Name = name;
Location = location;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
}
package lk.ac.jfn.vau.DeptApi.Model;
public class PrimaryID<U> {
private U Id;
public PrimaryID() {
}
public PrimaryID(U id) {
Id = id;
}
public U getId() {
return Id;
}
public void setId(U id) {
Id = id;
}
}
package lk.ac.jfn.vau.DeptApi.Repo;
import java.util.ArrayList;
import java.util.List;
import lk.ac.jfn.vau.DeptApi.Model.PrimaryID;
public class Repo<T extends PrimaryID<U>,U> {
List<T> list= new ArrayList<T>();
public List<T> getAll(){
return list;
}
public void insert(T obj) {
list.add(obj);
}
public T get(U id) {
for(T obj:list) {
//objects are there
System.out.println(obj);
//but getId returns null
if(obj.getId().equals(id)) {
return obj;
}
}
return null;
}
public void Delete(U id) {
list.remove(get(id));
}
public void Update(U id,T obj) {
list.set(list.indexOf(get(id)), obj);
}
}
package lk.ac.jfn.vau.DeptApi.Repo;
import lk.ac.jfn.vau.DeptApi.Model.Department;
public class DepartmentRepo extends Repo<Department, Long> {
}
package lk.ac.jfn.vau.DeptApi;
import java.util.List;
import javax.ws.rs.Consumes;
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 lk.ac.jfn.vau.DeptApi.Model.Department;
import lk.ac.jfn.vau.DeptApi.Repo.DepartmentRepo;
#Path("/dept")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class DepartmentResource {
private static DepartmentRepo repo = new DepartmentRepo();
#GET
public List<Department> getDepartments() {
return repo.getAll();
}
#POST
public void addDepartment(Department department) {
repo.insert(department);
}
#GET
#Path("/{id}")
public Department getDepartment(#PathParam("id") long id) {
return repo.get(id);
}
#DELETE
#Path("/{id}")
public void deleteDepartment(#PathParam("id") long id) {
repo.Delete(id);
}
}
I found the problem. Problem is Object to JSON conversion. when I updated the JSON library it worked fine.
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
I stuck with my Springboot Crud project and i need your helps.Problem is i want to use GET with my barcode string variable , and to DELETE and PUT using my id int variable but somehow i could not managed to DELETE and PUT with id variable and i stuck with this all the day. i will post my code and i will apriciate every help
Application.java
package com.javahelps.restservice;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.javahelps.restservice.entity.User;
import com.javahelps.restservice.repository.UserRepository;
import com.javahelps.restservice.repository.UserRepository2;
import com.javahelps.restservice.repository.UserRepository3;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
protected CommandLineRunner init(final UserRepository userRepository , UserRepository2 userRepository2,UserRepository3 userRepository3) {
return null;
};
}
UserController.java
package com.javahelps.restservice.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties.Session;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javahelps.restservice.entity.User;
import com.javahelps.restservice.repository.UserRepository;
import com.javahelps.restservice.repository.UserRepository3;
import javassist.tools.web.BadHttpRequest;
#RestController
#RequestMapping(path = "/productnames")
public class UserController {
#Autowired
private UserRepository repository;
private UserRepository3 repository3;
#GetMapping
public Iterable<User> findAll() {
return repository.findAll();
}
#GetMapping(path = "/{barcode}")
public User find(#PathVariable("barcode") String barcode) {
return repository.findOne(barcode);
}
#PostMapping(consumes = "application/json")
public User create(#RequestBody User user) {
return repository.save(user);
}
#DeleteMapping(path = "/{barcode}")
public void delete(#PathVariable("barcode") String barcode) {
repository.delete(barcode);
}
#DeleteMapping(path = "1/{id}")
public void delete(#PathVariable("id") Integer id) {
repository.delete(id);
}
#PutMapping(path = "/{barcode}")
public User update(#PathVariable("barcode") String barcode, #RequestBody User user) throws BadHttpRequest {
if (repository.exists(barcode)) {
user.setBarcode(barcode);
return repository.save(user);
} else {
throw new BadHttpRequest();
}
}
}
UserRepository.java
package com.javahelps.restservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;
import com.javahelps.restservice.entity.User;
#RestResource(exported = false)
#Repository
public interface UserRepository extends JpaRepository<User,String> {
}
User.java
package com.javahelps.restservice.entity;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="ProductNames")
public class User {
private int id;
#Id
private String barcode;
private String name;
private String category;
private int qty;
private Date dater;
private Date datel;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Date getDater() {
return dater;
}
public void setDater(Date dater) {
this.dater = dater;
}
public Date getDatel() {
return datel;
}
public void setDatel(Date datel) {
this.datel = datel;
}
#Override
public String toString() {
return "User{" + "='" +", id='"+ id + '\'' +", name='"+ barcode + '\'' + ", name='" + name + '\'' + ", category='" + category + '\''
+ ", qty='" + qty + '\'' + ", dater='" + dater + '\''+", datel='" + datel + '\'' +'}';
}
}
For delete based on id, since your primary key is not int id you have to write the below custom code in your interface extending JpaRepository.
And in your rest controller you have to invoke it like repository.deleteById(id);
#Repository
public interface UserRepository extends JpaRepository<User,String> {
#Modifying
#Transactional
#Query(value="delete from User u where u.id= ?1")
void deleteById(int id);
}
Similarly you may have to write code for your update statement as well (for PUT case).
Hope this helps.
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)
I am using Json to get object details in my POST method to save it in database. The id field is stored correctly but the rest are just taken as null. Can someone point out why.
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.ws.rs.GET;
import javax.ws.rs.*;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.ocpsoft.example.hibernate.model.SimpleObject;
import org.ocpsoft.example.hibernate.util.EntityManagerUtil;
import org.ocpsoft.example.hibernate.dao.SimpleObjectDao;
#Stateless
#Path("/pid")
public class Service {
#GET
#Path("{id}")
public String get(#PathParam("id") long id){
System.out.println("in GET request");
SimpleObjectDao objDao=new SimpleObjectDao();
objDao.startConnection();
SimpleObject obj=objDao.find(id);
objDao.closeConnection();
Gson gson=new Gson();
return gson.toJson(obj);
}
#POST
#Path("/add")
#Consumes("application/json")
//#Produces({MediaType.APPLICATION_JSON})
public String postdata(SimpleObject obj)
{
//SimpleObject obj = (SimpleObject) ob;
//Gson gson=new Gson();
//System.out.println(obj.toString());
//System.out.println("object "+obj.toString());
SimpleObjectDao objDao=new SimpleObjectDao();
objDao.startConnection();
objDao.save(obj);
objDao.closeConnection();
return "Success";
}
}
My object definition is
package org.ocpsoft.example.hibernate.model;
import javax.persistence.*;
import java.io.Serializable;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlRootElement;
import java.lang.Override;
/**
* #author Lincoln Baxter, III
*/
#Entity
#XmlRootElement(name="SimpleObject")
public class SimpleObject implements Serializable
{
private static final long serialVersionUID = -2862671438138322400L;
#Id
//#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private Long id = null;
//private int Pid;
#Column(name= "Pname")
private String Pname = null;
#Column(name= "Pcost")
private double Pcost = 0.0f;
#Column(name= "Pcat")
private String Pcat = null;
public Long getId()
{
return this.id;
}
public String getPname() {
return Pname;
}
public void setPname(String pname) {
Pname = pname;
}
public double getPcost() {
return Pcost;
}
public void setPcost(double pcost) {
Pcost = pcost;
}
public String getPcat() {
return Pcat;
}
public void setPcat(String pcat) {
Pcat = pcat;
}
public void setId(final Long id)
{
this.id = id;
}
public String toString()
{
String result = "";
if (id != null)
result += id;
return result;
}
#Override
public boolean equals(Object that)
{
if (this == that)
{
return true;
}
if (that == null)
{
return false;
}
if (getClass() != that.getClass())
{
return false;
}
if (id != null)
{
return id.equals(((SimpleObject) that).id);
}
return super.equals(that);
}
#Override
public int hashCode()
{
if (id != null)
{
return id.hashCode();
}
return super.hashCode();
}
}
Apart from Id all the others are not transferred to the object. com where I am going wrong.
I am checking using chrome postman with json as
{ "SimpleObject" :{"id":1,"Pname":"watch","Pcost":200.12,"Pcat":"wearables"}}
Maybe your ID column is auto generate, I think values on POST method cannot cast to your object
Try this :
#POST
#Path("/add")
#Consumes("application/x-www-form-urlencoded")
#Produces(MediaType.APPLICATION_JSON)
public String postdata(MultivaluedMap<String, String> formParams)
we need build SimpleObject object from form params.
hope this help !
I'm writing my first project with J2EE. I would like to populate some tables of a DB by a servlet.
For example:
This is my entity "Administrator.java"
package cinema.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Amministratore implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String user_name;
private String psw;
private String name;
private String surname;
private String email;
public Administrator () {
}
public Administrator (String user_name, String name, String surname,String psw, String email) {
this.user_name=user_name;
this.name=name;
this.surname=surname;
this.psw=psw;
this.email=email;
}
public String getPsw () {
return psw;
}
public void setPsw(String psw) {
this.psw = psw;
}
public String getUserName () {
return user_name;
}
public void setUserName (String user_name) {
this.user_name=user_name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname=surname;
}
public String getEmail() {
return email;
}
public void getEmail(String email) {
this.email=email;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Amministratore)) {
return false;
}
Amministratore other = (Amministratore) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "cinema.entity.Amministratore[ id=" + id + " ]";
}
}
This is my servlet:
package cinema.servlet;import cinema.entity.Administrator;
import cinema.interfacce.AdminBeanRemote;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "InitializeServlet", urlPatterns = {"/InitializeServlet"})
public class InitializeServlet extends HttpServlet {
#EJB
AdminBeanRemote adminBean;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
adminBean.cleanAdmin();
adminBean.addNewAdmin("admin1", "Silvia", "Fichera", "admin1", "admin1#cinema.it");
adminBean.addNewAdmin("admin2", "Giulia", "Fichera", "admin2", "admin2#cinema.it");
adminBean.addNewGestore("gestore1", "Mike", "Bongiorno", "gestore1", "gestore1#cinema.it");
adminBean.addNewAdmin("gestore2", "Carlo", "Conti", "gestore2", "gestore2#cinema.it");
try {
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
} finally {
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
And in AdminBean I have the functions cleanAdmin() and addNewAdmin:
package cinema.bean;
import cinema.entity.*;
import cinema.interfacce.AdminBeanRemote;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;`
#Stateless
#Remote
public class AdminBean implements AdminBeanRemote {
#PersistenceContext
private EntityManager em;
#Override
public void cleanAdmin() {
List admin = em.createQuery("SELECT c FROM Administrator c").getResultList();
for(Iterator iter = admin.iterator(); iter.hasNext();) {
em.remove(iter.next());
}
em.flush();
}
#Override
public boolean addNewAdmin(String user_name, String name, String surname, String psw, String email)throws PersistenceException {
if(em.find(Administrator.class, user_name)!=null) {
System.out.println("Admin already existing");
return false;
}else{
Administrator administrator;
administrator = new Administrator(user_name, name, surname, psw, email);
em.persist(administrator);
}
return true;
}
}
Any suggestions?
I can't find the file persistance.xml and NetBeans creates my tables in its samples db.
Thanks for your help and sorry if there's incorrect syntax!