jax-rs response.getEntity not working - java

I want to use javax.ws.rs.core.Response to send and receive an Card entity object. But I don't know how to convert the contents back in to a Card object.
My testCreate() method should execute the create(Card card) method, receive back the json and convert it in to a card object. But I somehow always get type mismatches or it says that the getEntity() method can't be executed like this: response.getEntity(Card.class).
Does anybody know how I have to handle the response correctly so that I can convert the returned json entity in to a Card object again?
Here my CardResource method:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response create(Card card) {
Card c = dao.create(card);
if(c.equals(null)) {
return Response.status(Status.BAD_REQUEST).entity("Create failed!").build();
}
return Response.status(Status.OK)
.entity(c)
.type(MediaType.APPLICATION_JSON)
.build();
}
And here my CardResourceTests class
#Test
public void testCreate() {
boolean thrown = false;
CardResource resource = new CardResource();
Card c = new Card(1, "Cardname", "12345678", 1, 1,
"cardname.jpg", new Date(), new Date());
try {
Response result = resource.create(c);
System.out.println(result.getEntity(Card.class)); // not working!!!
if(result.getStatus() != 200) {
thrown = true;
}
} catch(Exception e) {
e.printStackTrace();
thrown = true;
}
assertEquals("Result", false, thrown);
}
And here my Card.class
#XmlRootElement
#PersistenceCapable(detachable="true")
public class Card {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private Integer id;
#Persistent
private String name;
#Persistent
private String code;
#Persistent
private Integer cardProviderId;
#Persistent
private Integer codeTypeId;
#Persistent
private String picturePath;
#Persistent
private Boolean valid;
#Persistent
private Date mobCreationDate;
#Persistent
private Date mobModificationDate;
#Persistent
private Date creationDate;
#Persistent
private Date modificationDate;
public Card() {
this.setId(null);
this.setName(null);
this.setCode(null);
this.setCardProviderId(null);
this.setCodeTypeId(null);
this.setPicturePath(null);
this.setMobCreationDate(null);
this.setMobModificationDate(null);
this.setCreationDate(null);
this.setModificationDate(null);
}
public Card(Integer id, String name, String code, Integer cardProviderId,
Integer codeTypeId, String picturePath,
Date mobCreationDate, Date mobModificationDate) {
this.setId(id);
this.setName(name);
this.setCode(code);
this.setCardProviderId(cardProviderId);
this.setCodeTypeId(codeTypeId);
this.setPicturePath(picturePath);
this.setMobCreationDate(mobCreationDate);
this.setMobModificationDate(mobModificationDate);
this.setCreationDate(new Date());
this.setModificationDate(new Date());
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public Integer getCardProviderId() {
return cardProviderId;
}
public void setCardProviderId(Integer cardProviderId) {
this.cardProviderId = cardProviderId;
}
public void setCode(String code) {
this.code = code;
}
public Integer getCodeTypeId() {
return codeTypeId;
}
public void setCodeTypeId(Integer codeTypeId) {
this.codeTypeId = codeTypeId;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public Date getMobCreationDate() {
return mobCreationDate;
}
public void setMobCreationDate(Date mobCreationDate) {
this.mobCreationDate = mobCreationDate;
}
public Date getMobModificationDate() {
return mobModificationDate;
}
public void setMobModificationDate(Date mobModificationDate) {
this.mobModificationDate = mobModificationDate;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
}
And here my CardDAO class
public class CardDAO {
private final static Logger logger = Logger.getLogger(CardDAO.class.getName());
public Card create(Card card) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Card c = new Card(card.getId(), card.getName(), card.getCode(),
card.getCardProviderId(), card.getCodeTypeId(), card.getPicturePath(),
new Date(), new Date());
try {
pm.makePersistent(c);
} catch(Exception e) {
logger.severe("Create failed: " + e.getMessage());
return null;
} finally {
pm.close();
}
return c;
}
}

Is your Card class using #XmlRootElement and #XmlElement annotations to enable JAXB mapping JSON to/from POJO?
See example:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Book {
#XmlElement(name = "id")
String id;
//...

I am not sure that it is correct to call the annotated web-service method just like a simple method with params. Try to remove all annotations from your CardResource class and invoke this method simply like a class method.

Related

Parse Json file in MongoDB using Spring Data Java

this problem only occurs when I get the data from the database, the application is replacing the _ with . this only happens when I get the record from the database
data in database
[{"nombre": "pablo", "pais(codigo)": "52", "telefono": "", "saldo_total": "10"}, {"nombre": "pablo", "pais(codigo)": "52", "telefono": "", "saldo_total": "10"}]
entity in java code
#EnableMongoRepositories
#Document(collection = "data")
public class DataEntity extends BaseMongoEntity {
#Id
private String id;
#Field(value = "company_id")
private int companyId;
private String name;
private String url;
private List<String> variables;
private List<Object> info;
public DataEntity() {
super();
// TODO Auto-generated constructor stub
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<String> getVariables() {
return variables;
}
public void setVariables(List<String> variables) {
this.variables = variables;
}
public List<Object> getInfo() {
return info;
}
public void setInfo(List<Object> info) {
this.info = info;
}
}
query to find the record in database
public DataEntity findById(String id) {
ObjectId idO = new ObjectId(id);
Query query = new Query(Criteria.where("_id").is(idO));
return mongoTemplate.findOne(query, DataEntity.class);
}
image of data obtained in object format
only happens when the record is obtained but not when saving data in the database.

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `response` out of START_ARRAY token

I keep getting this response when im trying to execute my retrofit call for this reseponse:
package retrofit.responses;
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.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"version",
"createdDate",
"modifiedDate",
"rie",
"line1",
"line2",
"line3",
"line4",
"line5",
"county",
"postCode",
"country",
"primary",
"accomodationStatus",
"addressType",
"effectiveFrom",
"effectiveTo",
"secured"
})
#Generated("jsonschema2pojo")
public class ReferralResponse {
#JsonProperty("id")
private Object id;
#JsonProperty("version")
private Integer version;
#JsonProperty("createdDate")
private Object createdDate;
#JsonProperty("modifiedDate")
private Object modifiedDate;
#JsonProperty("rie")
private Boolean rie;
#JsonProperty("line1")
private String line1;
#JsonProperty("line2")
private Object line2;
#JsonProperty("line3")
private Object line3;
#JsonProperty("line4")
private String line4;
#JsonProperty("line5")
private Object line5;
#JsonProperty("county")
private Object county;
#JsonProperty("postCode")
private String postCode;
#JsonProperty("country")
private Object country;
#JsonProperty("primary")
private Boolean primary;
#JsonProperty("accomodationStatus")
private AccomodationStatus accomodationStatus;
#JsonProperty("addressType")
private Object addressType;
#JsonProperty("effectiveFrom")
private Long effectiveFrom;
#JsonProperty("effectiveTo")
private Object effectiveTo;
#JsonProperty("secured")
private Boolean secured;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("id")
public Object getId() {
return id;
}
#JsonProperty("id")
public void setId(Object id) {
this.id = id;
}
#JsonProperty("version")
public Integer getVersion() {
return version;
}
#JsonProperty("version")
public void setVersion(Integer version) {
this.version = version;
}
#JsonProperty("createdDate")
public Object getCreatedDate() {
return createdDate;
}
#JsonProperty("createdDate")
public void setCreatedDate(Object createdDate) {
this.createdDate = createdDate;
}
#JsonProperty("modifiedDate")
public Object getModifiedDate() {
return modifiedDate;
}
#JsonProperty("modifiedDate")
public void setModifiedDate(Object modifiedDate) {
this.modifiedDate = modifiedDate;
}
#JsonProperty("rie")
public Boolean getRie() {
return rie;
}
#JsonProperty("rie")
public void setRie(Boolean rie) {
this.rie = rie;
}
#JsonProperty("line1")
public String getLine1() {
return line1;
}
#JsonProperty("line1")
public void setLine1(String line1) {
this.line1 = line1;
}
#JsonProperty("line2")
public Object getLine2() {
return line2;
}
#JsonProperty("line2")
public void setLine2(Object line2) {
this.line2 = line2;
}
#JsonProperty("line3")
public Object getLine3() {
return line3;
}
#JsonProperty("line3")
public void setLine3(Object line3) {
this.line3 = line3;
}
#JsonProperty("line4")
public String getLine4() {
return line4;
}
#JsonProperty("line4")
public void setLine4(String line4) {
this.line4 = line4;
}
#JsonProperty("line5")
public Object getLine5() {
return line5;
}
#JsonProperty("line5")
public void setLine5(Object line5) {
this.line5 = line5;
}
#JsonProperty("county")
public Object getCounty() {
return county;
}
#JsonProperty("county")
public void setCounty(Object county) {
this.county = county;
}
#JsonProperty("postCode")
public String getPostCode() {
return postCode;
}
#JsonProperty("postCode")
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#JsonProperty("country")
public Object getCountry() {
return country;
}
#JsonProperty("country")
public void setCountry(Object country) {
this.country = country;
}
#JsonProperty("primary")
public Boolean getPrimary() {
return primary;
}
#JsonProperty("primary")
public void setPrimary(Boolean primary) {
this.primary = primary;
}
#JsonProperty("accomodationStatus")
public AccomodationStatus getAccomodationStatus() {
return accomodationStatus;
}
#JsonProperty("accomodationStatus")
public void setAccomodationStatus(AccomodationStatus accomodationStatus) {
this.accomodationStatus = accomodationStatus;
}
#JsonProperty("addressType")
public Object getAddressType() {
return addressType;
}
#JsonProperty("addressType")
public void setAddressType(Object addressType) {
this.addressType = addressType;
}
#JsonProperty("effectiveFrom")
public Long getEffectiveFrom() {
return effectiveFrom;
}
#JsonProperty("effectiveFrom")
public void setEffectiveFrom(Long effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
#JsonProperty("effectiveTo")
public Object getEffectiveTo() {
return effectiveTo;
}
#JsonProperty("effectiveTo")
public void setEffectiveTo(Object effectiveTo) {
this.effectiveTo = effectiveTo;
}
#JsonProperty("secured")
public Boolean getSecured() {
return secured;
}
#JsonProperty("secured")
public void setSecured(Boolean secured) {
this.secured = secured;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
and im trying to getID and use that in another call. This is an object that I am trying to turn into an integer an then use that in a seperate call again.
referralResponseResponse = call1.getReferral(token).execute();
int i = (int) referralResponseResponse.body().getId();
System.out.println("Int: " + i);
I should also note the json that I'm using this data from is very large so ive just used jsonpogo to extract this information to a java file and then use the parts that apply to me, I dont imagine i have to set up a java class for every part of the retruned json
Try to add following annotation for your POJO class:
#JsonIgnoreProperties(ignoreUnknown = true)

How to parse JSON using GSON?

How get value in array "rate" to invoke getters methods ?
My Json response is something as below and confused how to parse it using GSON. Please have look on the following and guide me how i can parse it using GSON.
data.json
{
"query":{
"count":2,
"created":"2017-01-03T12:45:19Z",
"lang":"en-us",
"results":{
"rate":[
{
"id":"BTC/USD",
"Name":"BTCUSD",
"Rate":"985.50",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"985.50",
"Bid":"985.35"
},
{
"id":"BTC/EUR",
"Name":"BTCEUR",
"Rate":"973.16",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"973.16",
"Bid":"973.10"
}
]
}
}
}
I use classes to parse apart
Market.java
public class Market {
#SerializedName("query")
private Query query;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
Query.java
public class Query {
#SerializedName("count")
private Integer count;
#SerializedName("created")
private String created;
#SerializedName("lang")
private String lang;
#SerializedName("results")
private Results results;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
Rate.java
public class Rate {
#SerializedName("id")
private String id;
#SerializedName("Name")
private String name;
#SerializedName("Rate")
private String rate;
#SerializedName("Date")
private String date;
#SerializedName("Time")
private String time;
#SerializedName("Ask")
private String ask;
#SerializedName("Bid")
private String bid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
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;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
}
Results.java
public class Results {
#SerializedName("rate")
private List<Rate> rate = null;
public List<Rate> getRate() {
return rate;
}
public void setRate(List<Rate> rate) {
this.rate = rate;
}
}
Trying to get the values
Main.java
public class Main {
/* ..... */
Gson gson = new Gson();
Market market = gson.fromJson(json, Market.class);
//error: incompatible types: Rate cannot be converted to List<Rate>
for( List<Rate> res : market.getQuery().getResults().getRate());
{
Log.v(LOG_TAG, res); // error: cannot find symbol variable res
}
}
how to do it properly ?
The syntax of your for each loop is incorrect. Since you are attempting to loop through a list of Rate objects, the type of res should be a Rate, not a list of Rates:
for (Rate res : market.getQuery().getResults().getRate()) {
// code here
}
As an aside, you should consider checking for null values before dereferencing all of those child objects as you run the risk of throwing a NullPointerException at runtime.

How to order descending the data in hibernate

I want to order the data descending in hibernate,
but not working at all,
this is my code,
#SuppressWarnings("unchecked")
#Override
public List<MPNValas> listAllMPNValas() throws Exception{
DetachedCriteria criteria = DetachedCriteria.forClass(MPNValas.class);
criteria.addOrder(Order.desc("ID"));
List<MPNValas> mpnvalasList = getHibernateTemplate().findByCriteria(criteria);
return mpnvalasList;
}
this is my controller,
#RequestMapping("/admin/mpn-valas.html")
public ModelAndView listMPNValas(ModelMap model)throws Exception
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String sessionUser = user.getUsername();
try{
UserAdmin dataUser = userService.get(sessionUser);
model.addAttribute("userData", dataUser);
} catch(Exception e){
e.printStackTrace();
}
ModelAndView mav = new ModelAndView("mpnvalas");
List<MPNValas> mpnvalas = mpnvalasService.listAllMPNValas();
mav.addObject("mpnvalas", mpnvalas);
return mav;
}
and this is the class,
package prod.support.model.gwprod;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="LOOKUP")
public class MPNValas {
private Integer ID;
private String TIPE;
private String KODE_PERUSAHAAN;
private String CODE;
private String NAME;
private String VALUE;
#Id
#Column(name="ID", unique=true, nullable=false)
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
#Column(name="TIPE")
public String getTIPE() {
return TIPE;
}
public void setTIPE(String TIPE) {
this.TIPE = TIPE;
}
#Column(name="KODE_PERUSAHAAN")
public String getKODE_PERUSAHAAN() {
return KODE_PERUSAHAAN;
}
public void setKODE_PERUSAHAAN(String KODE_PERUSAHAAN) {
this.KODE_PERUSAHAAN = KODE_PERUSAHAAN;
}
#Column(name="CODE")
public String getCODE() {
return CODE;
}
public void setCODE(String CODE) {
this.CODE = CODE;
}
#Column(name="NAME")
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME;
}
#Column(name="VALUE")
public String getVALUE() {
return VALUE;
}
public void setVALUE(String VALUE) {
this.VALUE = VALUE;
}
/**
* #param args
*/
}
and this the list of data
that I miss something??
any help will be pleasure :))
You miss nothing, just note that the argument to the desc method is case sensitive and should match the name of the attribute to sort by.
Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.desc("id"));

How to write query in hibernate(HQL) to perform 2 joins without mapping?

I want to convert the following query into HQL:
SELECT C.ID, E.DESCRIPTION as STATUS, E1.DESCRIPTION as SUBJECT
FROM CRED C
join CODE_EVN E
ON E.CODE = C.STATUS_CODE
AND E.SUBCODE = C.STATUS_SUBCODE
join CODE_EVN E1
ON E1.CODE = C.SUBJECT_CODE
AND E1.SUBCODE = C.SUBJECT_SUBCODE
I have two classes User and Codes with no mapping in between them, so how do I execute the following query in Hibernate?
I have tried out many things but nothing seems to work
These are my 2 bean classes:
User class:
#Entity
#Table(name="CRED")
public class User {
private String id;
private String STATUS_CODE;
private String STATUS_SUBCODE;
private String SUBJECT_CODE;
private String SUBJECT_SUBCODE;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setSTATUS_CODE(String sTATUS_CODE) {
STATUS_CODE = sTATUS_CODE;
}
public String getSTATUS_CODE() {
return STATUS_CODE;
}
public void setSTATUS_SUBCODE(String sTATUS_SUBCODE) {
STATUS_SUBCODE = sTATUS_SUBCODE;
}
public String getSTATUS_SUBCODE() {
return STATUS_SUBCODE;
}
public void setSUBJECT_CODE(String sUBJECT_CODE) {
SUBJECT_CODE = sUBJECT_CODE;
}
public String getSUBJECT_CODE() {
return SUBJECT_CODE;
}
public void setSUBJECT_SUBCODE(String sUBJECT_SUBCODE) {
SUBJECT_SUBCODE = sUBJECT_SUBCODE;
}
public String getSUBJECT_SUBCODE() {
return SUBJECT_SUBCODE;
}
}
Codes class:
#Entity
#Table(name="CODE_EVN")
public class Codes {
#Id
private String CODE;
private String SUBCODE;
private String DESCRIPTION;
public void setCODE(String cODE) {
CODE = cODE;
}
public String getCODE() {
return CODE;
}
public void setSUBCODE(String sUBCODE) {
SUBCODE = sUBCODE;
}
public String getSUBCODE() {
return SUBCODE;
}
public void setDESCRIPTION(String dESCRIPTION) {
DESCRIPTION = dESCRIPTION;
}
public String getDESCRIPTION() {
return DESCRIPTION;
}
}

Categories

Resources