Springboot REST application should accept and produce both XML and JSON - java

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)

Related

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?

My app crashed and I didn't get any response from server. But I got a response using postman

I am sending the PatientInfo() class object to the server but I didn't get any response from the server. The "response.body()" is getting null. But I am getting the JSON format in my logcat .
My patientInfo() model class---
public class PatientInfo implements Serializable {
#SerializedName("id")
#Expose
private String id;
#SerializedName("patient_id")
#Expose
private String patientId;
#SerializedName("firstname")
#Expose
private String firstname;
#SerializedName("lastname")
#Expose
private String lastname;
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("address")
#Expose
private String address;
#SerializedName("sex")
#Expose
private String sex;
#SerializedName("blood_group")
#Expose
private String bloodGroup;
#SerializedName("date_of_birth")
#Expose
private String dateOfBirth;
#SerializedName("affliate")
#Expose
private Object affliate;
#SerializedName("picture")
#Expose
private String picture;
#SerializedName("created_by")
#Expose
private String createdBy;
#SerializedName("create_date")
#Expose
private String createDate;
#SerializedName("status")
#Expose
private String status;
#SerializedName("user_role")
#Expose
private String userRole;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPatientId() {
return patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBloodGroup() {
return bloodGroup;
}
public void setBloodGroup(String bloodGroup) {
this.bloodGroup = bloodGroup;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Object getAffliate() {
return affliate;
}
public void setAffliate(Object affliate) {
this.affliate = affliate;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
#Override
public String toString() {
return "PatientInfo{" +
"id='" + id + '\'' +
", patientId='" + patientId + '\'' +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mobile='" + mobile + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", bloodGroup='" + bloodGroup + '\'' +
", dateOfBirth='" + dateOfBirth + '\'' +
", affliate=" + affliate +
", picture='" + picture + '\'' +
", createdBy='" + createdBy + '\'' +
", createDate='" + createDate + '\'' +
", status='" + status + '\'' +
", userRole='" + userRole + '\'' +
'}';
}
}
My RegResponse() class--
public class RegResponse implements Serializable {
#SerializedName("status")
#Expose
private String status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("user_data")
#Expose
private List<PatientInfo> patientInfoList;
public List<PatientInfo> getPatientInfoList() {
return patientInfoList;
}
public void setPatientInfoList(List<PatientInfo> patientInfoList) {
this.patientInfoList = patientInfoList;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#Override
public String toString() {
return "RegResponse{" +
"status='" + status + '\'' +
", message='" + message + '\'' +
", patientInfoList=" + patientInfoList +
'}';
}
}
My RegSuccessResponse() class----
public class RegSuccessResponse implements Serializable {
#SerializedName("response")
#Expose
private RegResponse response;
public RegResponse getResponse() {
return response;
}
public void setResponse(RegResponse response) {
this.response = response;
}
#Override
public String toString() {
return "RegSuccessResponse{" +
"response=" + response +
'}';
}
}
here is my Api interface ---
public interface HMSAPIService {#POST("auth/registration")
Call<RegSuccessResponse> doReg(#Body PatientInfo patientInfo);}
and finaly here is my RegistrationActivity() code--
String firstName = metFirstName.getText().toString().trim();
String lastName = metLastName.getText().toString().trim();
String email = metregEmail.getText().toString().trim();
String password = metRegPassword.getText().toString().trim();
String phoneNumber = metPhoneNumber.getText().toString().trim();
String mobileNumber = metMobileNumber.getText().toString().trim();
String bloodGroup = spBloodGroup.getSelectedItem().toString().trim();
String gender = spGender.getSelectedItem().toString().trim();
String dob = metDob.getText().toString().trim();
String path = tvPicName.getText().toString().trim();
String address = metAddress.getText().toString().trim();
patientInfo.setFirstname(firstName);
patientInfo.setLastname(lastName);
patientInfo.setEmail(email);
patientInfo.setPassword(password);
patientInfo.setPhone(phoneNumber);
patientInfo.setMobile(mobileNumber);a
if(spBloodGroup.getSelectedItem().toString().equals("-Select One-")){
patientInfo.setBloodGroup(null);
} else {
patientInfo.setBloodGroup(bloodGroup);
}
if(spGender.getSelectedItem().toString().equals("-Select One-")){
patientInfo.setSex(null);
} else {
patientInfo.setSex(gender);
}
patientInfo.setDateOfBirth(dob);
patientInfo.setPicture(path);
patientInfo.setAddress(address);
if (regSuccessResponse.getResponse() != null) {
if (regSuccessResponse.getResponse().getPatientInfoList() != null) {
regSuccessResponse.getResponse().getPatientInfoList().add(patientInfo);
}
}
Gson gson = new Gson();
String patientInfoobjectstring = gson.toJson(patientInfo);
Log.e(TAG, patientInfoobjectstring);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SharedPref.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
hmsapiService = retrofit.create(HMSAPIService.class);
Call<RegSuccessResponse> call = hmsapiService.doReg(patientInfo);
call.enqueue(new Callback<RegSuccessResponse>() {
#Override
public void onResponse(Call<RegSuccessResponse> call, Response<RegSuccessResponse> response) {
regSuccessResponse = response.body();
if (response.body() != null){
if (response.body().getResponse().getStatus().equals("ok")) {
Toast.makeText(RegistrationActivity.this, "Registration successful!!!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class).putExtra("go_to", "patient_info"));
progressDialog.dismiss();
Log.d(TAG, regSuccessResponse.getResponse().getMessage());
finish();
} else {
Toast.makeText(RegistrationActivity.this, "Status not found.......", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(RegistrationActivity.this, "Check your connection!!!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<RegSuccessResponse> call, Throwable t) {
Log.d(TAG, "onFailure: ");
}
});
}
else {
Snackbar.make(findViewById(R.id.reg_linear_layout), R.string.all_data_providing_message, Snackbar.LENGTH_LONG).show();
}
});
//my server response will be like
{"status":"error","message":"There have no data!"}
my logcat shows---
2018-11-29 17:53:30.329 23861-23861/com.example.bdtask.bdtaskhms E/RegistrationActivity:{"address":"Dhaka","blood_group":"O+","date_of_birth":"29/11/2018","email":"shaon054#gmail.com","firstname":"Shaon","lastname":"acharjee","mobile":"494518","password":"sgshsuvs","phone":"4728151","picture":"/storage/emulated/0/demonuts/1543492405451.jpg","sex":"Male"}2018-11-29 17:53:39.194 23861-23861/com.example.bdtask.bdtaskhms E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bdtask.bdtaskhms, PID: 23861
java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.bdtask.bdtaskhms.models.RegResponse com.example.bdtask.bdtaskhms.responses.RegSuccessResponse.getResponse()' on a null object reference
at com.example.bdtask.bdtaskhms.activities.RegistrationActivity.lambda$onCreate$0(RegistrationActivity.java:259)
at com.example.bdtask.bdtaskhms.activities.-$$Lambda$RegistrationActivity$CvYkDzuJ5whfAnUqX8zPIFxXXqo.onClick(lambda)
at android.view.View.performClick(View.java:6261)
at android.widget.TextView.performClick(TextView.java:11159)
at android.view.View$PerformClick.run(View.java:23752)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

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"}]}]

How to handle Json object in java web service coming from android side

I am implementing web service using Jersey javax web services. I am sending json object from Postman rest client to my web service but i am not able to handle that json in my web service.
#POST
#Path("/login")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Person login(Person person) throws ClassNotFoundException, SQLException {
Person todo = new Person();
todo.setValid_user(true);
return todo;
}
and i am sending json to above function from postman rest client as given below.
http://localhost:8080/RestWebService/rest/person/login
in raw i am writing my json input as
{"Person":[
"valid_user":"true"
"userId":"1",
"UserName":"parag",
"userPassword":"parag123",
"userLocation":"asd",
"userTime":"asda",
"message":"asdasd"
]}
but i am getting 500 and 415 error.
Hel me out please.
Person class:
package com.avilyne.rest.model;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
#XmlRootElement
public class Person {
#JsonProperty("userId")
private String userId;
#JsonProperty("UserName")
private String UserName;
#JsonProperty("userPassword")
private String userPassword;
#JsonProperty("userLocation")
private String userLocation;
#JsonProperty("userTime")
private String userTime;
#JsonProperty("message")
private String message;
#JsonProperty("valid_user")
private String valid_user;
public String isValid_user() {
return valid_user;
}
public void setValid_user(String valid_user) {
this.valid_user = valid_user;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserLocation() {
return userLocation;
}
public void setUserLocation(String userLocation) {
this.userLocation = userLocation;
}
public String getUserTime() {
return userTime;
}
public void setUserTime(String userTime) {
this.userTime = userTime;
}
#Override
public String toString() {
return "Person [userId=" + userId + ", UserName=" + UserName + ", userPassword=" + userPassword
+ ", userLocation=" + userLocation + ", userTime=" + userTime + "]";
}
}
Your JSON is invalid (check it using JSONLint):
A valid JSON to consume in your service would be:
{
"valid_user": true,
"userId": "1",
"UserName": "parag",
"userPassword": "parag123",
"userLocation": "asd",
"userTime": "asda",
"message": "asdasd"
}
Mind the , after "valid_user":"true" and {} instead of [].
You won't need { "Person": {...} }.
Use Jackson mapper, it will automatically convert json to your 'Person' object and vice-versa.
You just need to update your 'Person' bean and add #JsonProperty and #JsonCreator annotation (go through link below) and jackson will take care of the rest.
https://github.com/FasterXML/jackson-annotations
The valid json should be:
{
"valid_user":"true",
"userId":"1",
"userName":"parag",
"userPassword":"parag123",
"userLocation":"asd",
"userTime":"asda",
"message":"asdasd"
}
Edit:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
#JsonProperty("userId")
private String userId;
#JsonProperty("userName")
private String userName;
#JsonProperty("userPassword")
private String userPassword;
#JsonProperty("userLocation")
private String userLocation;
#JsonProperty("userTime")
private String userTime;
#JsonProperty("message")
private String message;
#JsonProperty("valid_user")
private boolean valid_user;
#JsonCreator
public Person(#JsonProperty("userId") String userId,
#JsonProperty("userName") String userName,
#JsonProperty("userPassword") String userPassword,
#JsonProperty("userLocation") String userLocation,
#JsonProperty("userTime") String userTime,
#JsonProperty("message") String message,
#JsonProperty("valid_user") boolean valid_user) {
this.userId = userId;
this.userName = userName;
this.userPassword = userPassword;
this.userLocation = userLocation;
this.userTime = userTime;
this.message = message;
this.valid_user = valid_user;
}
public String getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String getUserPassword() {
return userPassword;
}
public String getUserLocation() {
return userLocation;
}
public String getUserTime() {
return userTime;
}
public String getMessage() {
return message;
}
public boolean isValid_user() {
return valid_user;
}
#Override
public String toString() {
return "Person{" +
"userId='" + userId + '\'' +
", userName='" + userName + '\'' +
", userPassword='" + userPassword + '\'' +
", userLocation='" + userLocation + '\'' +
", userTime='" + userTime + '\'' +
", message='" + message + '\'' +
", valid_user=" + valid_user +
'}';
}
}
I updated the above json, you missed ',' after valid_user and also I changed "UserName" to "userName" (change it if you want).
Please test it out and let me know if it's working.

Rest client using Jersey returns empty object

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.

Categories

Resources