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>
Related
Getting null values in database for the embedded Address entity. Using MySql database. The user entity is storing values fine but embedded Address entity is returning null value, can't figure out why it's not working. help me out guys.I am a beginner tried searching everywhere but no luck. Just a novice Api but it won't work the way i want it's really annoying.
Model class
package com.example.demo;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int id;
private String name;
#Embedded
private Address address;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "user [id=" + id + ", name=" + name + ",Address="+address+" ]";
}
public User(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
---------------------------------------------------------------------------------------------------------
**Model class**
package com.example.demo;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String cityname;
private String streetname;
private String Housename;
public Address() {
}
public Address(String cityname, String streetname, String housename) {
super();
this.cityname = cityname;
this.streetname = streetname;
Housename = housename;
}
public String getStreetname() {
return streetname;
}
public void setStreetname(String streetname) {
this.streetname = streetname;
}
public String getHousename() {
return Housename;
}
public void setHousename(String housename) {
Housename = housename;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
---------------------------------------------------------------------------------------------------------
**controller class**
package com.example.demo;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Croller {
#Autowired
TestRepo repo;
#PostMapping("/add")
public String save(#RequestBody User mode) {
repo.save(mode);
return "details saved";
}
#GetMapping("/get")
public List<User> retrive(){
return repo.findAll();
}
#GetMapping("/search")
public List<User> searchname(#RequestParam("name")String name){
return repo.name(name);
}
#GetMapping("/byid/{id}")
public Optional <User> getone (#PathVariable int id){
return repo.findById(id);
}
#PutMapping("/update")
public String updateid(#RequestBody User mode ) {
repo.save(mode);
return " user updated sucessfully";
}
#DeleteMapping("/remove/{id}")
public String delete(#PathVariable int id) {
repo.deleteById(id);
return "deleted with the given id:"+ id;
}
}
---------------------------------------------------------------------------------------------------------
Repository
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository <User, Integer> {
List <User> name(String name);
}
**Application.java**
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Demoapi2Application {
public static void main(String[] args) {
SpringApplication.run(Demoapi2Application.class, args);
}
}
Your request has to match the #RequestBody object for spring to map the keys appropriately
Try this request -
{
"id":19,
"name":"Alex",
"address":{
"cityname":"california",
"streetname":"ring road",
"Housename":"Housename"
}
}
Please make sure you give input as per your Model.
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);
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 !
Am writing an Webservice endpoint which will produce JSON and XML response. Here i would like to convert an object to JSON and setting it to string. When i try to do with the below code
Webservice Endpoint
package com.test1;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;`
#Path("v1")
public class Impl1 {
#POST
#Path("method")
#Produces({"text/xml","application/json"})
public XML method() throws JSONException
{
//JSONObject obj = new JSONObject();
JSONArray ary = new JSONArray();
Main main = new Main();`
List<Student> details = new ArrayList<Student>() ;
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
s1.setId("ID1");
s1.setValue("1");
s2.setId("ID2");
s2.setValue("2");
s3.setId("ID3");
s3.setValue("3");
details.add(s1);
details.add(s2);
details.add(s3);
main.setDetails(details);
ary.put(details);
Employee emp = new Employee();
emp.setName("Mike");
emp.setSalary(1000);
XML xml = new XML();
xml.setDetails(ary.toString());
xml.setEmp(emp);
xml.setId("1");
return xml;
}
}
XML class (JAXB)
package com.test1;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class XML {
String id;
Employee emp;
String details;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
Student Class
package com.test1;
public class Student {
String id;
String Value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
Main Class
package com.test1;
import java.util.List;
public class Main {
List<Student> details;
public List<Student> getDetails() {
return details;
}
public void setDetails(List<Student> details) {
this.details = details;
}
}
So when i hit my service am getting response as
{
"details" : "[[{\"id\":\"ID1\",\"value\":\"1\"},{\"id\":\"ID2\",\"value\":\"2\"},{\"id\":\"ID3\",\"value\":\"3\"}]]",
"emp" : {
"name" : "Arun",
"salary" : "1000.0"
},
"id" : "1"
}
Expected String valuse as
[{"id":"ID1","value":"1"},{"id":"ID2","value":"2"},{"id":"ID3","value":"3"}]
My Question is Why JSONArray which was converted as String contains "\" on every key value pair. is there any way to overcome this?
Use Jackson or google-gson or any other library.
For example
http://howtodoinjava.com/2014/06/16/jackson-examples-convert-java-object-to-from-json/
i've got Social model :
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
#NodeEntity
public class Social {
#GraphId
private Long id;
#Indexed
private Long userId;
#RelatedTo(type="FRIEND", direction=Direction.BOTH)
#Fetch private Set<Social> friends;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Set<Social> getFriends() {
return friends;
}
public void setFriends(Set<Social> friends) {
this.friends = friends;
}
public void addFriend(Social social){
this.friends.add(social);
}
}
and repository :
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.neo4j.repository.RelationshipOperationsRepository;
import com.msci.travelpad.entities.Social;
public interface SocialRepository extends GraphRepository<Social>, RelationshipOperationsRepository<Social> {
}
but when i would to find social node by userId using :
public Social findByUserId(Long userId) {
return socialRepository.findByPropertyValue("userId", userId);
}
findByUserId always return null.
Did you try to implement your own find method in the repository like:
Iterable<Social> findByUserId(Long userId);
Are the indexes created correctly (see Null return using GraphRepository from Spring Data for Neo4j)?