Rest client using Jersey returns empty object - java

im trying to develop a simple RESTful webservice client. Using java and the javax jersey+dependencies. My problem is when trying to convert from the XML the object comes in, it returns an empty object.
The test is a simple test. I whish to get the language with a specific id, from my test i can see that the XML im getting is the same as in a browser.
The code for the classes is as follows:
Language
package data;
import javax.xml.bind.annotation.*;
#XmlRootElement(name = "prestashop")
#XmlType
public class Language {
private int id;
private String name;
private String iso_code;
private String language_code;
private boolean active;
private boolean is_rtl;
private String date_format_lite;
private String date_format_full;
public Language() {
}
public Language(String name, String iso_code, String date_format_lite,
String date_format_full) {
this.name = name;
this.iso_code = iso_code;
this.date_format_lite = date_format_lite;
this.date_format_full = date_format_full;
}
public Language(int id, String name, String iso_code, String language_code,
boolean active, boolean is_rtl, String date_format_lite,
String date_format_full) {
this.id = id;
this.name = name;
this.iso_code = iso_code;
this.language_code = language_code;
this.active = active;
this.is_rtl = is_rtl;
this.date_format_lite = date_format_lite;
this.date_format_full = date_format_full;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIso_code() {
return iso_code;
}
public void setIso_code(String iso_code) {
this.iso_code = iso_code;
}
public String getLanguage_code() {
return language_code;
}
public void setLanguage_code(String language_code) {
this.language_code = language_code;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isIs_rtl() {
return is_rtl;
}
public void setIs_rtl(boolean is_rtl) {
this.is_rtl = is_rtl;
}
public String getDate_format_lite() {
return date_format_lite;
}
public void setDate_format_lite(String date_format_lite) {
this.date_format_lite = date_format_lite;
}
public String getDate_format_full() {
return this.date_format_full;
}
public void setDate_format_full(String date_format_full) {
this.date_format_full = date_format_full;
}
#Override
public String toString(){
return "Language ["
+ "id=" + id + ", "
+ "name=" + name + ", "
+ "iso_code=" + iso_code + ", "
+ "language_code=" + language_code + ", "
+ "active=" + active + ", "
+ "is_rtl=" + is_rtl + ", "
+ "date_format_lite=" + date_format_lite + ", "
+ "date_format_full=" + date_format_full+ ","
+ " ]";
}
}
Main
package webservicetest2;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import data.Language;
import java.net.URI;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.JAXBException;
public class WebServiceTest2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws JAXBException {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new HTTPBasicAuthFilter("KEY", ""));
WebResource service = client.resource(getBaseURI());
System.out.println(service.path("languages")
.path("7")
.accept(MediaType.TEXT_XML)
.get(String.class));
Language language;
language = (Language) service.path("languages")
.path("7")
.accept(MediaType.TEXT_XML)
.get(Language.class);
System.out.println(language.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/api").build();
}
}
The output
run:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<language>
<id><![CDATA[7]]></id>
<name><![CDATA[Danish]]></name>
<iso_code><![CDATA[da]]></iso_code>
<language_code><![CDATA[da]]></language_code>
<active><![CDATA[1]]></active>
<is_rtl><![CDATA[0]]></is_rtl>
<date_format_lite><![CDATA[Y-m-d]]></date_format_lite>
<date_format_full><![CDATA[Y-m-d H:i:s]]></date_format_full>
</language>
</prestashop>
Language [id=0, name=null, iso_code=null, language_code=null, active=false, is_rtl=false, date_format_lite=null, date_format_full=null, ]
BUILD SUCCESSFUL (total time: 0 seconds)
As you can see the XML im getting back has an object but the print of the object is an empty object. So something is wrong.
Sorry if simular question have been asked but havent been able to find any.

Related

Deserialise object into a subtype dynamically using gson

I have a base class
public class Box<T> {
private T entity;
public T getEntity() {
return entity;
}
void setEntity(T entity) {
this.entity = entity;
}
}
It has 2 implementations.
// Class Person
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Class Machine
public class Machine {
private String macAddress;
private String type;
public Machine(String macAddress, String type) {
this.macAddress = macAddress;
this.type = type;
}
}
If I want to serialise either of classA or class B objects, I will do it like this
Type typeTokenPerson = new TypeToken< Box <Person>>() {}.getType();
String userJson = gson.toJson(boxWithPersonObject, typeTokenPerson);
But the problem here is I need to know the type at compile time. I have a use case where I don't know this at compile-time, in other words, I have a json which I want to deserialize into either Person or Animal and I want to do this at runtime based on some condition.
Is there a way to do this usig Gson ?
Example:
Lets say we have a json like this
{
"entity": {
"name": "ABC",
"age": 10
}
}
This is of type Person. I want to deserialise this into an object of type Box<Person>
Gson can do it like this.
package com.example.demo;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;
public class GsonDemo {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private <T> Box<T> parseResponse(String responseData) {
Gson gson = new Gson();
Type jsonType = new TypeToken<Box<T>>() {
}.getType();
Box<T> result = gson.fromJson(responseData, jsonType);
return result;
}
#Test
public void test() {
LocalDateTime start = LocalDateTime.now();
try {
String json = "{ \"entity\": { \"name\": \"ABC\", \"age\": 10 }}";
Box<Person> objectBox = parseResponse(json);
System.out.println(objectBox);
String json2 = "{\n \"entity\": { \"macAddress\": \"DEF\", \"type\": \"def\" }}";
Box<Machine> objectBox2 = parseResponse(json2);
System.out.println(objectBox2);
} catch (Exception e) {
logger.error("Error", e);
}
LocalDateTime end = LocalDateTime.now();
logger.info("Cost time {}", Duration.between(start, end).toMillis() + "ms");
}
public class Box<T> {
private T entity;
public T getEntity() {
return entity;
}
void setEntity(T entity) {
this.entity = entity;
}
#Override
public String toString() {
return "Box{" + "entity=" + entity + '}';
}
}
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
public class Machine {
private String macAddress;
private String type;
public Machine(String macAddress, String type) {
this.macAddress = macAddress;
this.type = type;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Machine{" + "macAddress='" + macAddress + '\'' + ", type='" + type + '\'' + '}';
}
}
}

JPA 2.2: Using find method to retrieve data from mysqlDB

I´m using JPA 2.2(Openjpa) running on OpenLiberty and mysqlVer 15.1 Distrib 10.1.21-MariaDB.
I have an object call Account where I use the entityManager.find to retrieve a given record.
The record is indeed retrieved but only this column "status" returns null.
But when I do the manual select against the DB,the value is there.
My Entity class
Account
package br.com.rsm.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
//#XmlRootElement
#Entity
#Table(name = "tb_account")
#NamedQueries({
#NamedQuery(name="Account.findByEmail", query="SELECT a FROM Account a where a.email = :email"),
#NamedQuery(name="Account.findByCpf", query="SELECT a FROM Account a where a.cpf = :cpf"),
#NamedQuery(name="Account.findByUserId", query="SELECT a FROM Account a where a.userId = :userId")
})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String fullname;
private String email;
private String birthdate;
private String cpf;
private String rg;
private String address;
private String addressNumber;
private String complement;
private String cep;
private String state;
private int city;
private String phone;
private String mobile;
private String carrier;
#Column(name = "status")
private String status;
private long leftSide;
private long rightSide;
private Timestamp created;
private String parentId;
private String parentSide;
private String networkSide;
private Timestamp activated;
private double points;
private String nickname;
private String nis;
private String whatsapp;
private long bank;
private String accountType;
private String branchNumber;
private String branchDigit;
private String accountNumber;
private String accountDigit;
private String accountOwner;
private String cpfAccountOwner;
private String facebookID;
private double career;
private double pb;
private int certID;
private String automaticRenovation;
private String emailPagamento;
#Transient
private Account rightSideAccount;
#Transient
private Account leftSideAccount;
#Transient
private boolean searchableBySignedInUser;
#Transient
private long totalCandidatosAgente;
#Transient
private long totalAgentes;
#Transient
private long totalAgentesBracoEsq;
#Transient
private long totalAgentesBracoDir;
#Transient
private long totalAnjos;
#Transient
private boolean cfaCompleto;
//#Transient
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "owner" )
List<Ticket> tickets = new ArrayList<Ticket>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("created DESC")
#JoinColumn(name = "accountId" )
private List<Score> scores = new ArrayList<Score>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("activated DESC")
#JoinColumn(name = "idAccount" )
private List<ProductAccount> productsAccount = new ArrayList<ProductAccount>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "origin" )
private List<Trade> trades = new ArrayList<Trade>();
/**
* Construtor
*/
public Account() {}
public List<Trade> getTrades() {
return trades;
}
public void setTrades(List<Trade> trades) {
this.trades = trades;
}
public List<ProductAccount> getProductsAccount() {
return productsAccount;
}
public void setProductsAccount(List<ProductAccount> productsAccount) {
this.productsAccount = productsAccount;
}
public List<Score> getScores() {
return scores;
}
public void setScores(List<Score> scores) {
this.scores = scores;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddressNumber() {
return addressNumber;
}
public void setAddressNumber(String addressNumber) {
this.addressNumber = addressNumber;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getLeftSide() {
return leftSide;
}
public void setLeftSide(long leftSide) {
this.leftSide = leftSide;
}
public long getRightSide() {
return rightSide;
}
public void setRightSide(long rightSide) {
this.rightSide = rightSide;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentSide() {
return parentSide;
}
public void setParentSide(String parentSide) {
this.parentSide = parentSide;
}
public String getNetworkSide() {
return networkSide;
}
public void setNetworkSide(String networkSide) {
this.networkSide = networkSide;
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
public Timestamp getActivated() {
return activated;
}
public void setActivated(Timestamp activated) {
this.activated = activated;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
#Transient
public String getShortName() {
if(fullname==null){
return "";
}
if (nickname == null || nickname.isEmpty() ) {
nickname = fullname;
}
if(nickname != null || !nickname.isEmpty()){
String[] arrTmp = fullname.replace("\n", " ").split(" ");
String shortName = "";
if(arrTmp.length >= 2){
shortName = arrTmp[0] + " " + arrTmp[1] ;
}else if(arrTmp.length >= 1){
shortName = arrTmp[0];
}
//Passo o limitador de tamanho para ambas situações.
if(shortName!=null){
if(shortName.length() > 20){
shortName = fullname.substring(0, 19) + "...";
}
}
return shortName;
}
return "";
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNis() {
return nis;
}
public void setNis(String nis) {
this.nis = nis;
}
public String getWhatsapp() {
return whatsapp;
}
public void setWhatsapp(String whatsapp) {
this.whatsapp = whatsapp;
}
public long getBank() {
return bank;
}
public void setBank(long bank) {
this.bank = bank;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getBranchDigit() {
return branchDigit;
}
public void setBranchDigit(String branchDigit) {
this.branchDigit = branchDigit;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountDigit() {
return accountDigit;
}
public void setAccountDigit(String accountDigit) {
this.accountDigit = accountDigit;
}
public String getAccountOwner() {
return accountOwner;
}
public void setAccountOwner(String accountOwner) {
this.accountOwner = accountOwner;
}
public String getCpfAccountOwner() {
return cpfAccountOwner;
}
public void setCpfAccountOwner(String cpfAccountOwner) {
this.cpfAccountOwner = cpfAccountOwner;
}
public String getFacebookID() {
return facebookID;
}
public void setFacebookID(String facebookID) {
this.facebookID = facebookID;
}
public double getCareer() {
return career;
}
public void setCareer(double career) {
this.career = career;
}
public double getPb() {
return pb;
}
public void setPb(double pb) {
this.pb = pb;
}
public int getCertID() {
return certID;
}
public void setCertID(int certID) {
this.certID = certID;
}
public String getAutomaticRenovation() {
return automaticRenovation;
}
public void setAutomaticRenovation(String automaticRenovation) {
this.automaticRenovation = automaticRenovation;
}
public String getEmailPagamento() {
return emailPagamento;
}
public void setEmailPagamento(String emailPagamento) {
this.emailPagamento = emailPagamento;
}
public Account getRightSideAccount() {
return rightSideAccount;
}
public void setRightSideAccount(Account rightSideAccount) {
this.rightSideAccount = rightSideAccount;
}
public Account getLeftSideAccount() {
return leftSideAccount;
}
public void setLeftSideAccount(Account leftSideAccount) {
this.leftSideAccount = leftSideAccount;
}
public boolean isSearchableBySignedInUser() {
return searchableBySignedInUser;
}
public void setSearchableBySignedInUser(boolean searchableBySignedInUser) {
this.searchableBySignedInUser = searchableBySignedInUser;
}
public long getTotalCandidatosAgente() {
return totalCandidatosAgente;
}
public void setTotalCandidatosAgente(long totalCandidatosAgente) {
this.totalCandidatosAgente = totalCandidatosAgente;
}
public long getTotalAgentes() {
return totalAgentes;
}
public void setTotalAgentes(long totalAgentes) {
this.totalAgentes = totalAgentes;
}
public long getTotalAgentesBracoEsq() {
return totalAgentesBracoEsq;
}
public void setTotalAgentesBracoEsq(long totalAgentesBracoEsq) {
this.totalAgentesBracoEsq = totalAgentesBracoEsq;
}
public long getTotalAgentesBracoDir() {
return totalAgentesBracoDir;
}
public void setTotalAgentesBracoDir(long totalAgentesBracoDir) {
this.totalAgentesBracoDir = totalAgentesBracoDir;
}
public long getTotalAnjos() {
return totalAnjos;
}
public void setTotalAnjos(long totalAnjos) {
this.totalAnjos = totalAnjos;
}
public boolean isCfaCompleto() {
return cfaCompleto;
}
public void setCfaCompleto(boolean cfaCompleto) {
this.cfaCompleto = cfaCompleto;
}
/**
* Adiciona uma nova classe Score
* #param score Score
*/
public void addScore(Score score) {
getScores().add(score);
}
public void addProductAccount(ProductAccount productAccount) {
getProductsAccount().add(productAccount);
}
public void addTrade(Trade trade) {
getTrades().add(trade);
}
#Override
public String toString() {
return "Account [id=" + id + ", userId=" + userId + ", fullname=" + fullname + ", email=" + email
+ ", birthdate=" + birthdate + ", cpf=" + cpf + ", rg=" + rg + ", address=" + address
+ ", addressNumber=" + addressNumber + ", complement=" + complement + ", cep=" + cep + ", state="
+ state + ", city=" + city + ", phone=" + phone + ", mobile=" + mobile + ", carrier=" + carrier
+ ", status=" + status + ", leftSide=" + leftSide + ", rightSide=" + rightSide + ", created=" + created
+ ", parentId=" + parentId + ", parentSide=" + parentSide + ", networkSide=" + networkSide
+ ", activated=" + activated + ", points=" + points + ", nickname=" + nickname + ", nis=" + nis
+ ", whatsapp=" + whatsapp + ", bank=" + bank + ", accountType=" + accountType + ", branchNumber="
+ branchNumber + ", branchDigit=" + branchDigit + ", accountNumber=" + accountNumber + ", accountDigit="
+ accountDigit + ", accountOwner=" + accountOwner + ", cpfAccountOwner=" + cpfAccountOwner
+ ", facebookID=" + facebookID + ", career=" + career + ", pb=" + pb + ", certID=" + certID
+ ", automaticRenovation=" + automaticRenovation + ", emailPagamento=" + emailPagamento
+ ", rightSideAccount=" + rightSideAccount + ", leftSideAccount=" + leftSideAccount
+ ", searchableBySignedInUser=" + searchableBySignedInUser + ", totalCandidatosAgente="
+ totalCandidatosAgente + ", totalAgentes=" + totalAgentes + ", totalAgentesBracoEsq="
+ totalAgentesBracoEsq + ", totalAgentesBracoDir=" + totalAgentesBracoDir + ", totalAnjos=" + totalAnjos
+ ", cfaCompleto=" + cfaCompleto + ", tickets=" + tickets + ", scores=" + scores + ", productsAccount="
+ productsAccount + ", trades=" + trades + "]";
}
}
And this is my select result( snapshot table is to big )
[
id=2111,
userId=99YWK,
fullname=PatrickRibeiroBraz,
email=null,
birthdate=null,
cpf=null,
rg=null,
address=null,
addressNumber=null,
complement=null,
cep=null,
state=null,
city=0,
phone=null,
mobile=null,
carrier=null,
status=null,
leftSide=0,
rightSide=0,
created=2018-06-1212: 09: 29.0,
parentId=999I2,
parentSide=null,
networkSide=null,
activated=null,
points=0.0,
nickname=null,
nis=null,
whatsapp=null,
bank=0,
accountType=null,
branchNumber=null,
branchDigit=null,
accountNumber=null,
accountDigit=null,
accountOwner=null,
cpfAccountOwner=null,
facebookID=null,
career=0.0,
pb=0.0,
certID=0,
automaticRenovation=null,
emailPagamento=null,
rightSideAccount=null,
leftSideAccount=null,
searchableBySignedInUser=false,
totalCandidatosAgente=0,
totalAgentes=0,
totalAgentesBracoEsq=0,
totalAgentesBracoDir=0,
totalAnjos=0,
cfaCompleto=false,
tickets={
IndirectList: notinstantiated
},
scores={
IndirectList: notinstantiated
},
productsAccount={
IndirectList: notinstantiated
},
trades={
IndirectList: notinstantiated
}
]
ID fullname status
2111 Patrick Ribeiro Braz C
Has anyone went through this before?

Can't find a codec for class , Morphia , Spring

Posting JSON towards tomcat running Spring BOOT.
Mapping requests to update Mongo via Morphia
Getting Error : "status":500,"error":"Internal Server Error","exception":"org.bson.codecs.configuration.CodecConfigurationException","message":"Can't find a codec for class se.preffo.model.ProfileAccess.
Somehow it is not knowing how to create the Object ProfileAccess
ProfileClass
package se.preffo.model;
import java.util.List;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.*;
#Entity("profiles")
public class Profile extends BaseEntity {
#Property("user_name")
private String userName;
#Property("profile_data")
private List<ProfileData> profileData;
#Property("tags")
private List<String> profileTags;
#Property("profile_name")
private String profileName;
#Embedded
#Property("access")
private List<ProfileAccess> profileAccess;
public Profile (){
this.userName = "";
}
public String getUserName(){
return this.userName;
}
public void setUserName(String userId){
this.userName = userId;
}
public List<ProfileData> getProfileData(){
return this.profileData;
}
public void setProfileData(List<ProfileData> profileData){
this.profileData = profileData;
}
public String getProfileName() {
return profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
public List<ProfileAccess> getProfileAccess() {
return profileAccess;
}
public void setProfileAccess(List<ProfileAccess> profileAccess) {
this.profileAccess = profileAccess;
}
public List<String> getProfileTags() {
return profileTags;
}
public void setProfileTags(List<String> profileTags) {
this.profileTags = profileTags;
}
public void addTag(String tag){
this.profileTags.add(tag);
}
public void removeTag(String tag){
this.profileTags.remove(tag);
}
#Override
public String toString() {
return "Profile{" +
"id=" + id +
", userName='" + userName + '\'' +
", profileData=" + profileData +
", profileTags=" + profileTags +
", profileName='" + profileName + '\'' +
", profileAccess=" + profileAccess +
'}';
}
}
ProfileAccess class:
package se.preffo.model;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Property;
#Embedded
public class ProfileAccess{
#Property("name")
private String accessName;
#Property("access_id")
private String accessId;
#Property("exp")
private String expiryTime;
#Property("type")
private String accessType;
//Constructor
public ProfileAccess() {
super();
}
#Override
public String toString() {
return "ProfileAccess{" +
"accessName='" + accessName + '\'' +
", accessId='" + accessId + '\'' +
", expiryTime='" + expiryTime + '\'' +
", accessType='" + accessType + '\'' +
'}';
}
public String getAccessName() {
return accessName;
}
public void setAccessName(String accessName) {
this.accessName = accessName;
}
public String getAccessId() {
return accessId;
}
public void setAccessId(String accessId) {
this.accessId = accessId;
}
public String getExpiryTime() {
return expiryTime;
}
public void setExpiryTime(String expiryTime) {
this.expiryTime = expiryTime;
}
public String getAccessType() {
return accessType;
}
public void setAccessType(String accessType) {
this.accessType = accessType;
}
}
ProfileController
// ---------------------- UPDATE LIST OF PROFILES
#RequestMapping(value="/profiles/batch", method=RequestMethod.POST)
public void updateProfile(#RequestBody List<Profile> profiles) {
logger.debug(profiles.get(0).toString());
profileService.updateProfiles(profiles);
}
ProfileService
public void updateProfiles(List<Profile> profiles) {
datastore = MongoDbHelper.INSTANCE.getDatastore();
for (Profile profile : profiles) {
logger.debug(profile.toString());
datastore.save(profile);
}
}
MongoDbHelper
private MongoDbHelper() {
MongoClient mongoClient = new MongoClient(new MongoClientURI("uritomongodb"));
Morphia morphia = new Morphia();
this.datastore = morphia.createDatastore(mongoClient, DATABASE_NAME);
}
public Datastore getDatastore() {
return this.datastore;
}
Posted JSON
[{"id":{"timestamp":1489743145,"machineIdentifier":13056160,"processIdentifier":3851,"counter":6420585,"time":1489743145000,"date":1489743145000,"timeSecond":1489743145},"version":14,"userName":"test#gmail.com","profileData":null,"profileTags":null,"profileName":"jonas","profileAccess":[{"accessId":"testare","expiryTime":"20170319","accessName":"testare","accessType":"shop"}]}]

Inherited method not working

I have a method that is supposed to replenish stock parts for a manufacturer. I have tried using super.Method() but its not working. There's also a class called Part if it's needed.
Main Class
package main;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestAssembledPart {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
List<AssembledPart> aparts = new ArrayList<AssembledPart>();
aparts.add(new AssembledPart("a200", "Crank & Pedal", 10, 3.5, "Crank", "Pedal"));
System.out.println("part before stock level change - start");
System.out.println(AssembledPart.toAssembledString(aparts));
for (AssembledPart apart: aparts){
if(apart!=null){
System.out.println("Please enter replenish quantity");
aparts.replenish(sc.nextInt());
}
}
System.out.println("part before stock level change - end");
System.out.println(AssembledPart.toAssembledString(aparts));
}
}
AssembledPart Class
package main;
import java.util.*;
public class AssembledPart extends Part {
private String basica;
private String basicb;
private int assembledstocklevel;
public AssembledPart(String id, String name, int stocklevel, double unitprice,
String basica, String basicb) {
super(id, name, stocklevel, unitprice);
this.basica = basica;
this.basicb = basicb;
}
public void replenish(int qty){
super.replenish(qty);
//super.stocklevel = super.stocklevel + qty;
}
public String toAssembledString() {
return super.toString() + " | " + basica + " | " + basicb;
}
public static String toAssembledString(Collection<AssembledPart> aparts){
String s = "";
for (AssembledPart apart: aparts){
s += apart.toAssembledString() + "\n";
}
return s;
}
}
PartClass
package main;
import java.util.*;
public class Part {
private String id;
private String name;
protected int stocklevel;
private double unitprice;
private int qty = 6000;
public Part(String id, String name, int stocklevel, double unitprice){
this.id = id;
this.name = name;
this.stocklevel = stocklevel;
this.unitprice = unitprice;
}
String partsAvailable()
{
//String newLine = System.getProperty("line.separator");
return (id + "\t" + name + "\t " + stocklevel + "\t\t " + unitprice);
}
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 int getStockLevel(){
return stocklevel - qty;
}
public void setStockLevel(int stocklevel){
this.stocklevel = stocklevel;
}
public double getUnitPrice(){
return unitprice;
}
public void setUnitPrice(double unitprice){
this.unitprice = unitprice;
}
public void replenish(int qty){
this.stocklevel = stocklevel + qty;
}
public double supply(int qty){
return unitprice * qty;
}
public String toString() {
return id + " | " + name + " | " + stocklevel + " | " + unitprice;
}
public static String toString(Collection<Part> parts){
String s = "";
for (Part part: parts){
s += part + "\n";
}
return s;
}
}
Replace this line :
aparts.replenish(sc.nextInt());
With the following
apart.replenish(sc.nextInt());
You were actually calling a method on the collection that contains your objects instead of the objects themself.

Springboot REST application should accept and produce both XML and JSON

I am working on Springboot REST API. My application should consume and produce both XML and JSON. I came across the Jackson json Xml dependency.
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.5.4</version>
</dependency>
I added this in my pom.xml. Now I am able to accept xml input but the values are null when mapped to Java Object. The following is my Resource class.
#Configuration
#ImportResource("/application-context.xml")
#EnableAutoConfiguration
#ResponseBody
#RequestMapping("/match")
public class MatchResource {
private static final Logger logger = LogManager.getLogger(MatchResource.class);
#Autowired
private MatchService matchService;
#RequestMapping(method = RequestMethod.POST)
#Consumes({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
#Produces({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
//#Produces( MediaType.APPLICATION_XML)
public Response matchRequest(#RequestBody MatchRequest matchRequest,
#Context HttpServletRequest headers) throws Exception {
Response resp = null;
MiniMatchResponse output = null;
// Headers are store in the "headers" object. To retrieve a specific header, please take a look at the below statement
String apiUser = headers.getHeader("Api-User");
UUID randID = UUID.randomUUID();
logger.info("Get Match for with ID: " + randID);
// Get service profile from headers via MatchConstants.SERVICE_PROFILE_HEADER
String serviceProfile = "";
try {
//TODO: MatchService should return MatchResponse Object
//Json OutPut
output = matchService.findResponse(matchRequest, serviceProfile);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
logger.debug("Match Request: " + matchRequest.toString());
} catch (ErrorException e) {
logger.error(e.getMessage(), e);
}
// Form Response
resp = Response.status(200).entity(output).build();
return resp;
}
The below is my Request Object
package com.infoconnect.api.dto.Match;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.List;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class MatchRequest implements Serializable {
// Gets or sets the RequestType of request this represents.
// Allowed values are "Company", "People" and "Any".
private String requestType;
private String name;
private String companyName;
private String streetAddress;
private String streetAddress2;
private String city;
private String stateProvince;
private String postalCode;
private String country;
private String serviceProfile;
private String resourceType;
private int limit;
private Integer confidence;
private String phone;
private Boolean includeHistorical;
private Boolean includeNonVerified;
private String requestId;
private List<String> fields;
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getStreetAddress2() {
return streetAddress2;
}
public void setStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getServiceProfile() {
return serviceProfile;
}
public void setServiceProfile(String serviceProfile) {
this.serviceProfile = serviceProfile;
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public Integer getConfidence() {
return confidence;
}
public void setConfidence(Integer confidence) {
this.confidence = confidence;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Boolean getIncludeHistorical() {
return includeHistorical;
}
public void setIncludeHistorical(Boolean includeHistorical) {
this.includeHistorical = includeHistorical;
}
public Boolean getIncludeNonVerified() {
return includeNonVerified;
}
public void setIncludeNonVerified(Boolean includeNonVerified) {
this.includeNonVerified = includeNonVerified;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public List<String> getFields() {
return fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
#Override
public String toString() {
return "MatchRequest{" +
"requestType='" + requestType + '\'' +
", name='" + name + '\'' +
", companyName='" + companyName + '\'' +
", streetAddress='" + streetAddress + '\'' +
", streetAddress2='" + streetAddress2 + '\'' +
", city='" + city + '\'' +
", stateProvince='" + stateProvince + '\'' +
", postalCode='" + postalCode + '\'' +
", country='" + country + '\'' +
", serviceProfile='" + serviceProfile + '\'' +
", resourceType='" + resourceType + '\'' +
", limit=" + limit +
", confidence=" + confidence +
", phone='" + phone + '\'' +
", includeHistorical=" + includeHistorical +
", includeNonVerified=" + includeNonVerified +
", requestId='" + requestId + '\'' +
", fields=" + fields +
'}';
}
}
JSON request and Response works fine. Can you please help me how to Include XML request and Response in my application.
Try to add a #XmlRootElement(name="myRootTag") JAXB annotation with the tag you use as the root tag to the class MatchRequest. I have had similar issues when using both XML and JSON as transport format in a REST request, but using moxy instead of Jackson. In any case, proper JAXB annotations are necessary to convert to/from XML (XML is much pickier in this respect than JSON).
Jackson XML is supposed to support JAXB annotations, and if this does not work, it has an own set of similar annotations that are incompatible to JAXB (see https://github.com/FasterXML/jackson-dataformat-xml and https://github.com/FasterXML/jackson-dataformat-xml/wiki/Jackson-XML-annotations)

Categories

Resources