Java 1.8
Maven snippet:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.11.2</version>
</dependency>
snipped.xml
<?xml version="1.0" standalone="no"?>
<ledesxml_snipped>
<lede_name>Fitzhume</lede_name>
<firm>
<lf_tax_id>999999999</lf_tax_id>
<lf_id>Cogswell Cogs</lf_id>
<lf_name>Cogswell Cogs, Inc.</lf_name>
<lf_address>
<address_info>
<address_1>404 Asteroid Drive</address_1>
<address_3>Suite 2600</address_3>
<city>Dallas</city>
<state_province>TX</state_province>
<zip_postal_code>75203</zip_postal_code>
<country>USA</country>
</address_info>
</lf_address>
<lf_billing_contact_phone>2145551212</lf_billing_contact_phone>
<lf_billing_contact_fax>2148761234</lf_billing_contact_fax>
<lf_billing_contact_email>bigcog#cogswellcogs.com</lf_billing_contact_email>
<source_app>AimPoint</source_app>
<app_version>
</app_version>
</firm>
</ledesxml_snipped>
LedesSnipped.java
package com.my.application.model;
import java.io.*;
import java.util.*;
import javax.xml.bind.annotation.*;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"ledeName",
"firm"
})
#XmlRootElement(name = "ledesxml_snipped")
public class LedesxmlSnipped {
#XmlElement(name = "lede_name", required = true)
protected String ledeName;
#XmlElement(required = true)
#JacksonXmlElementWrapper( useWrapping = false)
protected LedesxmlSnipped.Firm firm;
public String getLedeName() {
return ledeName;
}
public void setLedName( String ledeName) {
this.ledeName = ledeName;
}
public LedesxmlSnipped.Firm getFirm() {
return firm;
}
public void setFirm(LedesxmlSnipped.Firm value) {
this.firm = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"lfTaxId",
"lfId",
"lfName",
"lfAddress",
"lfBillingContactPhone",
"lfBillingContactFax",
"lfBillingContactEmail",
"sourceApp",
"appVersion"
})
public static class Firm {
#XmlElement(name = "lf_tax_id")
protected int lfTaxId;
#XmlElement(name = "lf_id", required = true)
protected String lfId;
#XmlElement(name = "lf_name", required = true)
protected String lfName;
#XmlElement(name = "lf_address", required = true)
#JacksonXmlElementWrapper( useWrapping = false)
protected Ledesxml.Firm.LfAddress lfAddress;
#XmlElement(name = "lf_billing_contact_phone")
protected long lfBillingContactPhone;
#XmlElement(name = "lf_billing_contact_fax")
protected long lfBillingContactFax;
#XmlElement(name = "lf_billing_contact_email", required = true)
protected String lfBillingContactEmail;
#XmlElement(name = "source_app", required = true)
protected String sourceApp;
#XmlElement(name = "app_version", required = true)
protected String appVersion;
public int getLfTaxId() {
return lfTaxId;
}
public void setLfTaxId(int value) {
this.lfTaxId = value;
}
public String getLfId() {
return lfId;
}
public void setLfId(String value) {
this.lfId = value;
}
public String getLfName() {
return lfName;
}
public void setLfName(String value) {
this.lfName = value;
}
public Ledesxml.Firm.LfAddress getLfAddress() {
return lfAddress;
}
public void setLfAddress(Ledesxml.Firm.LfAddress value) {
this.lfAddress = value;
}
public long getLfBillingContactPhone() {
return lfBillingContactPhone;
}
public void setLfBillingContactPhone(long value) {
this.lfBillingContactPhone = value;
}
public long getLfBillingContactFax() {
return lfBillingContactFax;
}
public void setLfBillingContactFax(long value) {
this.lfBillingContactFax = value;
}
public String getLfBillingContactEmail() {
return lfBillingContactEmail;
}
public void setLfBillingContactEmail(String value) {
this.lfBillingContactEmail = value;
}
public String getSourceApp() {
return sourceApp;
}
public void setSourceApp(String value) {
this.sourceApp = value;
}
public String getAppVersion() {
return appVersion;
}
public void setAppVersion(String value) {
this.appVersion = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"addressInfo"
})
public static class LfAddress {
#XmlElement(name = "address_info", required = true)
protected Ledesxml.Firm.LfAddress.AddressInfo addressInfo;
public Ledesxml.Firm.LfAddress.AddressInfo getAddressInfo() {
return addressInfo;
}
public void setAddressInfo(Ledesxml.Firm.LfAddress.AddressInfo value) {
this.addressInfo = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"address1",
"address3",
"city",
"stateProvince",
"zipPostalCode",
"country"
})
public static class AddressInfo {
#XmlElement(name = "address_1", required = true)
protected String address1;
#XmlElement(name = "address_3", required = true)
protected String address3;
#XmlElement(required = true)
protected String city;
#XmlElement(name = "state_province", required = true)
protected String stateProvince;
#XmlElement(name = "zip_postal_code")
protected int zipPostalCode;
#XmlElement(required = true)
protected String country;
public String getAddress1() {
return address1;
}
public void setAddress1(String value) {
this.address1 = value;
}
public String getAddress3() {
return address3;
}
public void setAddress3(String value) {
this.address3 = value;
}
public String getCity() {
return city;
}
public void setCity(String value) {
this.city = value;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String value) {
this.stateProvince = value;
}
public int getZipPostalCode() {
return zipPostalCode;
}
public void setZipPostalCode(int value) {
this.zipPostalCode = value;
}
public String getCountry() {
return country;
}
public void setCountry(String value) {
this.country = value;
}
}
}
}
}
and lastly, TryThis.java
package com.my.application;
import java.util.*;
import java.io.*;
import java.time.*;
import java.time.format.*;
import javax.xml.stream.*;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.dataformat.xml.*;
import com.my.application.model.*;
public class TryThis {
public static void main(String[] args) {
XmlMapper mapper = new XmlMapper();
mapper.enable( SerializationFeature.INDENT_OUTPUT);
mapper.disable( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
File innFile = new File("snipped.xml");
LedesxmlSnipped asfda = mapper.readValue(innFile, LedesxmlSnipped.class);
System.out.println( "ledeName=" + asfda.getFirm().getLedeName());
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the result of all this is just
ledeName=null
where I'd expect to see
ledeName=Fitzhume
No errors. So what am I missing? Some fiendishly subtle configuration? Am I defining XmlMapper in the wrong place? The many examples I've looked at span various versions of Jackson and some go back to using javax.xml.
Simply adding
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
and
mapper.registerModule( new JaxbAnnotationModule());
to TryThis.java did the trick. Fiendishly subtle configuration issue indeed!
Thx to all who read the question.
Related
Hi i am creating a service of Invoice PO to get the json reponse after verification from classes of service package.
First I have created a model package and classes according to json.
InvoiceRequest is like this--
package com.InvoicePO.newmodel;
import java.util.List;
public class InvoiceRequest {
private List<Records> records;
public List<Records> getRecords() {
return records;
}
public void setRecords(List<Records> records) {
this.records = records;
}
}
Records Class--
package com.InvoicePO.newmodel;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Records {
private String Vecv_plant;
private String DBM_Plant;
private String VECV_SO;
private String DBM_PO;
private String VBELN;
private String FKDAT;
private String LRDATE;
private String PFCHARGE;
private String OCHARGE;
private String DISC;
private String TAXTYPE;
private String TAX;
private String TAXAMT;
private String INVAMT;
private String WAERK;
private String INVCNT;
private String ODN;
private List<LineItemTable> lineItemTables;
public String getVecv_plant() {
return Vecv_plant;
}
public void setVecv_plant(String vecv_plant) {
Vecv_plant = vecv_plant;
}
public String getDBM_Plant() {
return DBM_Plant;
}
public void setDBM_Plant(String dBM_Plant) {
DBM_Plant = dBM_Plant;
}
public String getVECV_SO() {
return VECV_SO;
}
public void setVECV_SO(String vECV_SO) {
VECV_SO = vECV_SO;
}
public String getDBM_PO() {
return DBM_PO;
}
public void setDBM_PO(String dBM_PO) {
DBM_PO = dBM_PO;
}
public String getVBELN() {
return VBELN;
}
public void setVBELN(String vBELN) {
VBELN = vBELN;
}
public String getFKDAT() {
return FKDAT;
}
public void setFKDAT(String fKDAT) {
FKDAT = fKDAT;
}
public String getLRDATE() {
return LRDATE;
}
public void setLRDATE(String lRDATE) {
LRDATE = lRDATE;
}
public String getPFCHARGE() {
return PFCHARGE;
}
public void setPFCHARGE(String pFCHARGE) {
PFCHARGE = pFCHARGE;
}
public String getOCHARGE() {
return OCHARGE;
}
public void setOCHARGE(String oCHARGE) {
OCHARGE = oCHARGE;
}
public String getDISC() {
return DISC;
}
public void setDISC(String dISC) {
DISC = dISC;
}
public String getTAXTYPE() {
return TAXTYPE;
LineItemTable--
package com.InvoicePO.newmodel;
public class LineItemTable {
private String VBELN1;
private String DEALER1;
private String POSEX;
private String MATNR;
private String INVQTY;
private String RATE;
private String TOTAL;
private String DISC;
private String TAXTYPE;
private String PURCH_NO;
private String PURCH_DATE;
private String SALES_NO;
private String PGIX;
public String getVBELN1() {
return VBELN1;
}
public void setVBELN1(String vBELN1) {
VBELN1 = vBELN1;
}
public String getDEALER1() {
return DEALER1;
}
public void setDEALER1(String dEALER1) {
DEALER1 = dEALER1;
}
public String getPOSEX() {
return POSEX;
}
public void setPOSEX(String pOSEX) {
POSEX = pOSEX;
}
public String getMATNR() {
return MATNR;
}
public void setMATNR(String mATNR) {
MATNR = mATNR;
}
public String getINVQTY() {
return INVQTY;
}
public void setINVQTY(String iNVQTY) {
INVQTY = iNVQTY;
}
public String getRATE() {
return RATE;
}
public void setRATE(String rATE) {
RATE = rATE;
}
public String getTOTAL() {
return TOTAL;
}
public void setTOTAL(String tOTAL) {
TOTAL = tOTAL;
}
public String getDISC() {
return DISC;
}
public void setDISC(String dISC) {
DISC = dISC;
}
public String getTAXTYPE() {
return TAXTYPE;
}
public void setTAXTYPE(String tAXTYPE) {
TAXTYPE = tAXTYPE;
}
public String getPURCH_NO() {
return PURCH_NO;
}
public void setPURCH_NO(String pURCH_NO) {
PURCH_NO = pURCH_NO;
}
public String getPURCH_DATE() {
return PURCH_DATE;
}
public void setPURCH_DATE(String pURCH_DATE) {
PURCH_DATE = pURCH_DATE;
}
public String getSALES_NO() {
return SALES_NO;
}
public void setSALES_NO(String sALES_NO) {
SALES_NO = sALES_NO;
}
public String getPGIX() {
return PGIX;
}
public void setPGIX(String pGIX) {
PGIX = pGIX;
}
}
Invoice Controller--
package com.InvoicePO.controller;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.InvoicePO.newmodel.InvoiceRequest;
import com.InvoicePO.service.DTRECCPOVCPLINVOICE;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO.Records;
import com.InvoicePO.service.DTSVCPLINVOICETOECCPO.Records.LineItemTable;
import com.InvoicePO.service.SISVCPLINVOICETOECCPO;
import com.InvoicePO.service.SISVCPLINVOICETOECCPOService;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
#RestController
public class InvoiceController {
public static String getJsonFromObject(Object obj) {
ObjectMapper Obj = new ObjectMapper();
Obj.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
Writer strWriter = new StringWriter();
try {
Obj.writeValue(strWriter,obj);
return strWriter.toString();
} catch (Exception e) {
return "";
}
}
#RequestMapping(value = "/invoicepo", method=RequestMethod.POST)
public #ResponseBody DTRECCPOVCPLINVOICE VerficationDetails(#RequestBody InvoiceRequest data) {
System.out.println("/Data Recieved" + getJsonFromObject(data));
DTRECCPOVCPLINVOICE response = null;
DTSVCPLINVOICETOECCPO soapobj = new DTSVCPLINVOICETOECCPO();
List<Records> objc = new ArrayList<>();
for(com.InvoicePO.newmodel.Records records : data.getRecords())
{
// RECORD records = data;
Records rec = new Records();
rec.setVecvPlant(records.getVecv_plant());
rec.setDBMPlant(records.getDBM_Plant());
rec.setVECVSO(records.getVECV_SO());
rec.setDBMPO(records.getDBM_PO());
rec.setVBELN(records.getVBELN());
rec.setFKDAT(records.getFKDAT());
rec.setLRDATE(records.getLRDATE());
rec.setPFCHARGE(records.getPFCHARGE());
rec.setOCHARGE(records.getOCHARGE());
rec.setDISC(records.getDISC());
rec.setTAXTYPE(records.getTAXTYPE());
rec.setTAX(records.getTAX());
rec.setTAXAMT(records.getTAXAMT());
rec.setINVAMT(records.getINVAMT());
rec.setWAERK(records.getWAERK());
rec.setINVCNT(records.getINVCNT());
rec.setODN(records.getODN());
List<LineItemTable> line = new ArrayList<>();
for(com.InvoicePO.newmodel.LineItemTable table : records.getLineItemTables()) {
// LineItemTable table = data;
LineItemTable lin = new LineItemTable();
lin.setDEALER1(table.getDEALER1());
lin.setPOSEX(table.getPOSEX());
lin.setMATNR(table.getMATNR());
lin.setINVQTY(table.getINVQTY());
lin.setRATE(table.getRATE());
lin.setTOTAL(table.getTOTAL());
lin.setDISC(table.getDISC());
lin.setTAXTYPE(table.getTAXTYPE());
lin.setPURCHNO(table.getPURCH_NO());
lin.setPURCHDATE(table.getPURCH_DATE());
lin.setSALESNO(table.getSALES_NO());
lin.setPGIX(table.getPGIX());
line.add(lin);
}
rec.setLineItemTable(line);
rec.setLineItemTable(line);
objc.add(rec);
}
System.out.println("\nRequest for PI:" +getJsonFromObject(soapobj));
SISVCPLINVOICETOECCPOService sisservice= new SISVCPLINVOICETOECCPOService();
SISVCPLINVOICETOECCPO port = sisservice.getHTTPSPort();
// DTSVCPLINVOICETOECCPO eccpo = new DTSVCPLINVOICETOECCPO();
// eccpo.setRecords(objc);
BindingProvider provider = (BindingProvider)port;
provider.getRequestContext().put("javax.xml.ws.security.auth.username", "pisuper");
provider.getRequestContext().put("javax.xml.ws.security.auth.password", "Xidvecv#123");
response = port.siSVCPLINVOICETOECCPO(soapobj);
System.out.println("\nResponse for PI:" +getJsonFromObject(soapobj));
return response ;
}
}
The json i am hitting in Postman --
{
"Records": {
"Vecv_plant": 1110,
"DBM_Plant": "C001",
"VECV_SO": 5110000139,
"DBM_PO": "5900000069",
"VBELN": 91297393,
"FKDAT": 20221208,
"LRDATE": 0,
"PFCHARGE": 0,
"OCHARGE": 0,
"DISC": 0,
"TAXTYPE": "IGST",
"TAX": 0,
"TAXAMT": 364.04,
"INVAMT": 2386.46,
"WAERK": "INR",
"INVCNT": 0,
"ODN": "IN9220800004",
"LineItemTable": [
{
"VBELN1": 91297393,
"DEALER1": "C001",
"POSEX": 10,
"MATNR": "IM300124L",
"INVQTY": 9,
"RATE": 2022,
"TOTAL": 2386,
"DISC": "",
"TAXTYPE": "IGST",
"PURCH_NO": 3000041178,
"PURCH_DATE": 20221121,
"SALES_NO": 1050022,
"PGIX": ""
},
{
"VBELN1": 91297393,
"DEALER1": "C001",
"POSEX": 20,
"MATNR": "IM300262L",
"INVQTY": 8,
"RATE": 1030,
"TOTAL": 1386,
"DISC": "",
"TAXTYPE": "IGST",
"PURCH_NO": 3000041178,
"PURCH_DATE": 20221121,
"SALES_NO": 1050022,
"PGIX": ""
}
]
}
}
The error I am getting = Cannot invoke java.util.List.iterator() because the return value of com.InvoicePO.newmodel.InvoiceRequest.getRecords() is null
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)
Need help when trying to save through this method, my hibernate debug doesn't show any error, no one error catch in this method
it is not committed, already try everything includes saveAndFlush() from JPARepositiry, all possible annotation, check whole my algorithm and logic. I thought it's related to my PostgreSQL configuration or my bidirectional relationship between related entities. But still, nothing showed up on my table in the database
#RequestMapping(value = "/save-pegawai-status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePlanningPegawaiStatus(#Valid #RequestBody PlanningPegawaiStatusVO vo,
HttpServletRequest request) {
try {
Map<String, Object> result = servicePermohonanStatus.savePlanningPegawaiStatus(vo);
if (CommonUtil.isNotNullOrEmpty(result.get("noRec"))) {
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
} else {
return RestUtil.getJsonResponse(result, HttpStatus.OK);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
} catch (Exception exp) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", exp.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, exp.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
package com.jasamedika.medifirst2000.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.jasamedika.medifirst2000.base.BaseTransaction;
import com.jasamedika.medifirst2000.helper.Caption;
#Entity
#Table(name="ListTanggalCuti_T")
public class ListTanggalCuti extends BaseTransaction{
#Caption(value="tgl")
#Column(name="tgl", nullable=true)
private Date tgl;
#Caption(value="Approval Status")
#Column(name="ApprovalStatus", nullable=true)
private Boolean approvalStatus;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Planning Pegawai Status")
#JoinColumn(name="ObjectPlanningPegawaiStatusFK")
private PlanningPegawaiStatus planningPegawaiStatus;
#Column(name="ObjectPlanningPegawaiStatusFK", insertable=false, updatable=false)
private String planningPegawaiStatusId;
public Date getTgl() {
return tgl;
}
public void setTgl(Date tgl) {
this.tgl = tgl;
}
public Boolean getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(Boolean approvalStatus) {
this.approvalStatus = approvalStatus;
}
public PlanningPegawaiStatus getPlanningPegawaiStatus() {
return planningPegawaiStatus;
}
public void setPlanningPegawaiStatus(PlanningPegawaiStatus planningPegawaiStatus) {
this.planningPegawaiStatus = planningPegawaiStatus;
}
public String getPlanningPegawaiStatusId() {
return planningPegawaiStatusId;
}
public void setPlanningPegawaiStatusId(String planningPegawaiStatusId) {
this.planningPegawaiStatusId = planningPegawaiStatusId;
}
}
package com.jasamedika.medifirst2000.entities;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.jasamedika.medifirst2000.base.BaseTransaction;
import com.jasamedika.medifirst2000.helper.Caption;
#Entity
#Table(name="PlanningPegawaiStatus_T")
public class PlanningPegawaiStatus extends BaseTransaction{
#Caption(value="No Planning")
#Column(name="NoPlanning", length=15, nullable=true)
private String noPlanning;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Pegawai")
#JoinColumn(name="ObjectPegawaiFk")
private Pegawai pegawai;
// #ManyToOne(fetch=FetchType.LAZY)
// #Caption(value="Object Jabatan Cuti")
// #JoinColumn(name="ObjectJabatanCutiFk")
// private Jabatan jabatanCuti;
#Column(name="ObjectPegawaiFk", nullable=true, insertable=false, updatable=false)
private Integer pegawaiId;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Status Pegawai Plan")
#JoinColumn(name="ObjectStatusPegawaiPlanFk")
private StatusPegawai statusPegawaiPlan;
#Column(name="ObjectStatusPegawaiPlanFk", nullable=true, insertable=false, updatable=false)
private Integer statusPegawaiPlanId;
#OneToMany(cascade=CascadeType.ALL,fetch = FetchType.LAZY, mappedBy = "planningPegawaiStatus", orphanRemoval=true)
private Set<ListTanggalCuti> listTanggal = new HashSet<ListTanggalCuti>();
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Departemen")
#JoinColumn(name="ObjectDepartemenFk")
private Departemen departemen;
#Column(name="ObjectDepartemenFk", nullable=true, insertable=false, updatable=false)
private Integer departemenId;
#Caption(value="Deskripsi Status Pegawai Plan")
#Column(name="DeskripsiStatusPegawaiPlan", length=1000, nullable=true)
private String deskripsiStatusPegawaiPlan;
#Caption(value="Keterangan Lainya Plan")
#Column(name="KeteranganLainyaPlan", length=1000, nullable=true)
private String keteranganLainyaPlan;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object No SK")
#JoinColumn(name="ObjectNoSkFk")
private SuratKeputusan noSk;
#Column(name="ObjectNoSkFk", nullable=true, insertable=false, updatable=false)
private Integer noSkId;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Status Pegawai Exec")
#JoinColumn(name="ObjectStatusPegawaiExecFk")
private StatusPegawai statusPegawaiExec;
#Column(name="ObjectStatusPegawaiExecFk", nullable=true, insertable=false, updatable=false)
private Integer statusPegawaiExecId;
#Caption(value="Deskripsi Status Pegawai Exec")
#Column(name="DeskripsiStatusPegawaiExec", length=1000, nullable=true)
private String deskripsiStatusPegawaiExec;
#Caption(value="Keterangan Lainya Exec")
#Column(name="KeteranganLainyaExec", length=1000, nullable=true)
private String keteranganLainyaExec;
#Caption(value="Tgl Pengajuan")
#Column(name="TglPengajuan", nullable=true)
private Date tglPengajuan;
#Caption(value="Tgl Keputusan")
#Column(name="TglKeputusan", nullable=true)
private Date tglKeputusan;
#Caption(value="Approval Status")
#Column(name="ApprovalStatus", nullable=true)
private Integer approvalStatus;
#Caption(value="jumlahHari")
#Column(name="jumlahHari", nullable=true)
private Integer jumlahHari;
// #Caption(value="keterangan")
// #Column(name="keterangan", nullable=true)
// private String keterangan;
#Caption(value="Jenis Perawatan")
#Column(name="jenisPerawatan", nullable=true)
private Integer jenisPerawatan;
#Caption(value="Alamat Selama Cuti")
#Column(name="alamatCuti", nullable=true)
private String alamatCuti;
#Caption(value="Nomor Telepon")
#Column(name="nomorTelepon", nullable=true)
private String nomorTelepon;
#Caption(value="Nomor Surat Tugas")
#Column(name="noSuratTugas", nullable=true)
private String noSuratTugas;
#Caption(value="Nomor Nota Dinas")
#Column(name="noNotaDinas", nullable=true)
private String noNotaDinas;
#Caption(value="Tgl Nota Dinas")
#Column(name="TglNotaDinas", nullable=true)
private Date tglNotaDinas;
#Caption(value="Alamat Tugas Dinas")
#Column(name="alamatTugas", nullable=true)
private String alamatTugas;
#ManyToOne(optional=true,fetch=FetchType.LAZY)
#Caption(value="Object Jabatan Pemberi Nota Dinas")
#JoinColumn(name="ObjectJabatanPemberiNotaDinasFk", nullable=true)
private Jabatan jabatanPemberiNotaDinas;
#Column(name="ObjectJabatanPemberiNotaDinasFk", nullable=true, insertable=false, updatable=false)
private Integer jabatanIdPemberiNotaDinas;
#Caption(value="is Cuti Luar Negeri")
#Column(name="isCutiLuarNegeri", nullable=true)
private Boolean isCutiLuarNegeri;
public String getNoPlanning() {
return noPlanning;
}
public void setNoPlanning(String noPlanning) {
this.noPlanning = noPlanning;
}
public Pegawai getPegawai() {
return pegawai;
}
public void setPegawai(Pegawai pegawai) {
this.pegawai = pegawai;
}
public Integer getPegawaiId() {
return pegawaiId;
}
public void setPegawaiId(Integer pegawaiId) {
this.pegawaiId = pegawaiId;
}
// public Jabatan getJabatanCuti() {
// return jabatanCuti;
// }
// public void setJabatanCuti(Jabatan jabatanCuti) {
// this.jabatanCuti = jabatanCuti;
// }
public StatusPegawai getStatusPegawaiPlan() {
return statusPegawaiPlan;
}
public void setStatusPegawaiPlan(StatusPegawai statusPegawaiPlan) {
this.statusPegawaiPlan = statusPegawaiPlan;
}
public Integer getStatusPegawaiPlanId() {
return statusPegawaiPlanId;
}
public void setStatusPegawaiPlanId(Integer statusPegawaiPlanId) {
this.statusPegawaiPlanId = statusPegawaiPlanId;
}
public Departemen getDepartemen() {
return departemen;
}
public void setDepartemen(Departemen departemen) {
this.departemen = departemen;
}
public Integer getDepartemenId() {
return departemenId;
}
public void setDepartemenId(Integer departemenId) {
this.departemenId = departemenId;
}
public String getDeskripsiStatusPegawaiPlan() {
return deskripsiStatusPegawaiPlan;
}
public void setDeskripsiStatusPegawaiPlan(String deskripsiStatusPegawaiPlan) {
this.deskripsiStatusPegawaiPlan = deskripsiStatusPegawaiPlan;
}
public String getKeteranganLainyaPlan() {
return keteranganLainyaPlan;
}
public void setKeteranganLainyaPlan(String keteranganLainyaPlan) {
this.keteranganLainyaPlan = keteranganLainyaPlan;
}
public SuratKeputusan getNoSk() {
return noSk;
}
public void setNoSk(SuratKeputusan noSk) {
this.noSk = noSk;
}
public Integer getNoSkId() {
return noSkId;
}
public void setNoSkId(Integer noSkId) {
this.noSkId = noSkId;
}
public StatusPegawai getStatusPegawaiExec() {
return statusPegawaiExec;
}
public void setStatusPegawaiExec(StatusPegawai statusPegawaiExec) {
this.statusPegawaiExec = statusPegawaiExec;
}
public Integer getStatusPegawaiExecId() {
return statusPegawaiExecId;
}
public void setStatusPegawaiExecId(Integer statusPegawaiExecId) {
this.statusPegawaiExecId = statusPegawaiExecId;
}
public String getDeskripsiStatusPegawaiExec() {
return deskripsiStatusPegawaiExec;
}
public void setDeskripsiStatusPegawaiExec(String deskripsiStatusPegawaiExec) {
this.deskripsiStatusPegawaiExec = deskripsiStatusPegawaiExec;
}
public String getKeteranganLainyaExec() {
return keteranganLainyaExec;
}
public void setKeteranganLainyaExec(String keteranganLainyaExec) {
this.keteranganLainyaExec = keteranganLainyaExec;
}
public Date getTglPengajuan() {
return tglPengajuan;
}
public void setTglPengajuan(Date tglPengajuan) {
this.tglPengajuan = tglPengajuan;
}
public Date getTglKeputusan() {
return tglKeputusan;
}
public void setTglKeputusan(Date tglKeputusan) {
this.tglKeputusan = tglKeputusan;
}
public Integer getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(Integer approvalStatus) {
this.approvalStatus = approvalStatus;
}
public Integer getJumlahHari() {
return jumlahHari;
}
public void setJumlahHari(Integer jumlahHari) {
this.jumlahHari = jumlahHari;
}
public Set<ListTanggalCuti> getListTanggal() {
return listTanggal;
}
public void setListTanggal(Set<ListTanggalCuti> listTanggal) {
this.listTanggal = listTanggal;
}
// public String getKeterangan() {
// return keterangan;
// }
// public void setKeterangan(String keterangan) {
// this.keterangan = keterangan;
// }
public Integer getJenisPerawatan() {
return jenisPerawatan;
}
public void setJenisPerawatan(Integer jenisPerawatan) {
this.jenisPerawatan = jenisPerawatan;
}
public String getAlamatCuti() {
return alamatCuti;
}
public void setAlamatCuti(String alamatCuti) {
this.alamatCuti = alamatCuti;
}
public String getNomorTelepon() {
return nomorTelepon;
}
public void setNomorTelepon(String nomorTelepon) {
this.nomorTelepon = nomorTelepon;
}
public String getNoSuratTugas() {
return noSuratTugas;
}
public void setNoSuratTugas(String noSuratTugas) {
this.noSuratTugas = noSuratTugas;
}
public String getNoNotaDinas() {
return noNotaDinas;
}
public void setNoNotaDinas(String noNotaDinas) {
this.noNotaDinas = noNotaDinas;
}
public Date getTglNotaDinas() {
return tglNotaDinas;
}
public void setTglNotaDinas(Date tglNotaDinas) {
this.tglNotaDinas = tglNotaDinas;
}
public String getAlamatTugas() {
return alamatTugas;
}
public void setAlamatTugas(String alamatTugas) {
this.alamatTugas = alamatTugas;
}
public Jabatan getJabatanPemberiNotaDinas() {
return jabatanPemberiNotaDinas;
}
public void setJabatanPemberiNotaDinas(Jabatan jabatanPemberiNotaDinas) {
this.jabatanPemberiNotaDinas = jabatanPemberiNotaDinas;
}
public Integer getJabatanIdPemberiNotaDinas() {
return jabatanIdPemberiNotaDinas;
}
public void setJabatanIdPemberiNotaDinas(Integer jabatanIdPemberiNotaDinas) {
this.jabatanIdPemberiNotaDinas = jabatanIdPemberiNotaDinas;
}
public Boolean getIsCutiLuarNegeri() {
return isCutiLuarNegeri;
}
public void setIsCutiLuarNegeri(Boolean isCutiLuarNegeri) {
this.isCutiLuarNegeri = isCutiLuarNegeri;
}
}
#Override
#Transactional
public Map<String, Object> savePlanningPegawaiStatus(PlanningPegawaiStatusVO vo) {
Map<String, Object> result = new HashMap<>();
boolean statusTanggalPermohonan = validateTanggalPermohonan(vo.getListTanggal(), vo.getPegawai().getId());
if (CommonUtil.isNotNullOrEmpty(statusTanggalPermohonan) && !statusTanggalPermohonan) {
result.put("bisaCuti", statusTanggalPermohonan);
result.put("status", "Tanggal Permohonan sudah pernah diajukan!"); //Validasi tanggal permohonan yang sudah diajukan
return result;
} else {
Integer day = 0;
if (CommonUtil.isNotNullOrEmpty(vo)) {
PlanningPegawaiStatus planningPegawaiStatus = planningPegawaiStatusConverter.transferVOToModel(vo,
new PlanningPegawaiStatus());
String noPlanning = noUsulan().get("noUsulan").toString();
if (CommonUtil.isNotNullOrEmpty(noPlanning)) {
planningPegawaiStatus.setNoPlanning(noPlanning);
planningPegawaiStatus.setStatusEnabled(true);
if (CommonUtil.isNotNullOrEmpty(vo.getStatusPegawaiPlan())) {
planningPegawaiStatus.setStatusPegawaiPlan(
statusPegawaiConverter.transferVOToModel(vo.getStatusPegawaiPlan(), new StatusPegawai()));
}
if (CommonUtil.isNotNullOrEmpty(vo.getJabatanPemberiNotaDinas())) {
planningPegawaiStatus.setJabatanPemberiNotaDinas(
jabatanConverter.transferVOToModel(vo.getJabatanPemberiNotaDinas(), new Jabatan()));
}
planningPegawaiStatus.setApprovalStatus(0);
if (CommonUtil.isNotNullOrEmpty(vo.getPegawai())) {
planningPegawaiStatus
.setPegawai(pegawaiConverter.transferVOToModel(vo.getPegawai(), new Pegawai()));
}
Set<ListTanggalCuti> listTanggal = new HashSet<ListTanggalCuti>();
for (ListTanggalCutiVO date : vo.getListTanggal()) {
day++;
ListTanggalCuti tanggal = listTanggalConverter.transferVOToModel(date, new ListTanggalCuti());
tanggal.setPlanningPegawaiStatus(planningPegawaiStatus);
tanggal.setStatusEnabled(true);
listTanggal.add(tanggal);
}
planningPegawaiStatus.setJumlahHari(day);
planningPegawaiStatus.setListTanggal(listTanggal);
if (CommonUtil.isNotNullOrEmpty(vo.getDeskripsiStatusPegawaiPlan())) {
planningPegawaiStatus.setDeskripsiStatusPegawaiPlan(vo.getDeskripsiStatusPegawaiPlan());
}
if (CommonUtil.isNotNullOrEmpty(vo.getKeteranganLainyaPlan())) {
planningPegawaiStatus.setKeteranganLainyaPlan(vo.getKeteranganLainyaPlan());
}
//Set Alamat Cuti dan No Telepon
planningPegawaiStatus.setAlamatCuti(vo.getAlamatCuti());
planningPegawaiStatus.setNomorTelepon(vo.getNomorTelepon());
if (CommonUtil.isNotNullOrEmpty(vo.getAlamatTugas())) {
planningPegawaiStatus.setAlamatTugas(vo.getAlamatTugas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getNoSuratTugas())) {
planningPegawaiStatus.setNoSuratTugas(vo.getNoSuratTugas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getNoNotaDinas())) {
planningPegawaiStatus.setNoNotaDinas(vo.getNoNotaDinas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getTglNotaDinas())) {
planningPegawaiStatus.setTglNotaDinas(vo.getTglNotaDinas());
}
planningPegawaiStatus.setIsCutiLuarNegeri(vo.getIsCutiLuarNegeri());
if (CommonUtil.isNotNullOrEmpty(planningPegawaiStatus)) {
List<String> listTgl = new ArrayList<>();
planningPegawaiStatus.setStatusEnabled(true);
PlanningPegawaiStatus planningPegawaiStatusResult = planningPegawaiStatusDao
.save(planningPegawaiStatus);
for (ListTanggalCuti listTanggalCuti : planningPegawaiStatusResult.getListTanggal()) {
listTgl.add(listTanggalCuti.getNoRec());
}
result.put("listTgl", listTgl);
result.put("noRec", planningPegawaiStatusResult.getNoRec());
result.put("bisaCuti", statusTanggalPermohonan);
}
}
}
return result;
}
}
PlanningPegawaiStatusVO and ListTanggalCutiVO just related value object class, transferVOToModel() is a method for data access from value object class to model
I'm finally realized that sometimes its commit and sometimes it isn't. And then when it isn't inserted to the database, also return with HttpStatus.CREATED an ERROR_MESSAGE like could not extract ResultSet from GenericJDBCException but it does not come from catch
I am trying to unmarshal XML to java class as follows:-
My xml file as follows:-
<Features_res>
<StartWeek>202017</StartWeek>
<EndWeek>202035</EndWeek>
<Pno12>ABCDEEB</Pno12>
<FeatureList>
<Feature>
<Code>T002</Code>
</Feature>
<Feature>
<Code>T002</Code>
</Feature>
</FeatureList>
</Features_res>
Java InteriorResponse:-
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int sWeek;
#XmlElement(name = "EndWeek")
private int eWeek;
#XmlElement(name = "Pno12")
private String p12;
List<Feature> featureList;
public InteriorResponse() {
}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.sWeek = startWeek;
this.eWeek = endWeek;
this.p12 = pno12;
}
public int getStartWeek() {
return sWeek;
}
public void setStartWeek(int startWeek) {
this.sWeek = startWeek;
}
public int getEndWeek() {
return eWeek;
}
public void setEndWeek(int endWeek) {
this.eWeek = endWeek;
}
public String getPno12() {
return p12;
}
public void setPno12(String pno12) {
this.p12 = pno12;
}
public List<Feature> getFeatureList() {
return featureList;
}
#XmlElement(name = "FeatureList")
public void setFeatureList(List<Feature> featureList) {
this.featureList = featureList;
}
}
Another Java Feature:-
#XmlRootElement(name = "Feature")
public class Feature {
//#XmlElement(name = "Feature")
private String feature_;
#XmlElement(name = "code")
private String code_;
public String getCode() {
return code_;
}
public void setCode(String code) {
this.code_ = code;
}
public String getFeature_() {
return feature_;
}
public void setFeature_(String feature_) {
this.feature_ = feature_;
}
}
I am using above class as :-
public static void xmlToInterior() {
File file = new File("minxml.xml");
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(InteriorResponse.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
InteriorResponse interiorFeatures = (InteriorResponse) unmarshaller.unmarshal(file);
List<Feature> list_feat = interiorFeatures.getFeatureList();
for(Feature ft : list_feat) {
System.out.println(ft.getCode());
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
Output I have as:-
list_feat
code_ null
feature_ null
And list_feat has size 1. It should 2.
Also I have to name class member sWeek instead of startWeek. Otherwise, jaxbContext = JAXBContext.newInstance(InteriorResponse.class) throws exception like 2 element exist with same name.
XML additional part
I thought I could do the reaming part of the XML. I was trying part by part. But I couldn't do it. I really need to find some good tutorial or book about JXB. All I find a short overview of JXB. Any suggestion about where to read in details?
<Features_res>
<StartWeek>202017</StartWeek>
<EndWeek>202035</EndWeek>
<Pno12>ABCDEEB</Pno12>
<FeatureList>
<Feature>
<Code>T002</Code>
</Feature>
<Feature>
<Code>T002</Code>
</Feature>
</FeatureList>
<OptionList>
<Option>001048</Option>
<Option>000050</Option>
<Option>000790</Option>
</OptionList>
</Features_res>
So I made new class as:-
public class OptionList {
private List<Option> options;
#XmlElement(name = "Option")
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
Another class as :-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class Option {
#XmlElement(name = "Option")
private String option_;
public String getOption() {
return option_;
}
public void setOption(String option) {
this.option_ = option;
}
}
And updated for InteriorResponse class as:-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int sWeek;
#XmlElement(name = "EndWeek")
private int eWeek;
#XmlElement(name = "Pno12")
private String p12;
private FeatureList featureList;
private OptionList optionList;
public InteriorResponse() {}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.sWeek = startWeek;
this.eWeek = endWeek;
this.p12 = pno12;
}
public int getStartWeek() {
return sWeek;
}
public void setStartWeek(int startWeek) {
this.sWeek = startWeek;
}
public int getEndWeek() {
return eWeek;
}
public void setEndWeek(int endWeek) {
this.eWeek = endWeek;
}
public String getPno12() {
return p12;
}
public void setPno12(String pno12) {
this.p12 = pno12;
}
#XmlElement(name = "FeatureList")
public FeatureList getFeatureList() {
return featureList;
}
public void setFeatureList(FeatureList featureList) {
this.featureList = featureList;
}
#XmlElement(name = "OptionList")
public OptionList getOptionList() {
return optionList;
}
public void setOptionList(OptionList optionList) {
this.optionList = optionList;
}
#Override
public String toString() {
return "InteriorResponse{"
+ "sWeek="
+ sWeek
+ ", eWeek="
+ eWeek
+ ", p12='"
+ p12
+ '\''
+ ", featureList="
+ featureList
+ '}';
}
}
I couldn't get the Option.
option null
The total xml is really huge. I still would like to try the remaing parts by myself part by part.
You need to design your classes according to XML structure. Find below the classes.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int sWeek;
#XmlElement(name = "EndWeek")
private int eWeek;
#XmlElement(name = "Pno12")
private String p12;
private FeatureList featureList;
private OptionList optionList;
public InteriorResponse() {}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.sWeek = startWeek;
this.eWeek = endWeek;
this.p12 = pno12;
}
public int getStartWeek() {
return sWeek;
}
public void setStartWeek(int startWeek) {
this.sWeek = startWeek;
}
public int getEndWeek() {
return eWeek;
}
public void setEndWeek(int endWeek) {
this.eWeek = endWeek;
}
public String getPno12() {
return p12;
}
public void setPno12(String pno12) {
this.p12 = pno12;
}
#XmlElement(name = "FeatureList")
public FeatureList getFeatureList() {
return featureList;
}
public void setFeatureList(FeatureList featureList) {
this.featureList = featureList;
}
#XmlElement(name = "OptionList")
public OptionList getOptionList() {
return optionList;
}
public void setOptionList(OptionList optionList) {
this.optionList = optionList;
}
#Override
public String toString() {
return "InteriorResponse{"
+ "sWeek="
+ sWeek
+ ", eWeek="
+ eWeek
+ ", p12='"
+ p12
+ '\''
+ ", featureList="
+ featureList
+ ", optionList="
+ optionList
+ '}';
}
}
Class for Feature object
import javax.xml.bind.annotation.XmlElement;
public class Feature {
#XmlElement(name = "Code")
private String code_;
public String getCode() {
return code_;
}
public void setCode(String code) {
this.code_ = code;
}
#Override
public String toString() {
return "Feature{" + "code_='" + code_ + '\'' + '}';
}
}
Class for FeatureList
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
public class FeatureList {
private List<Feature> features;
#XmlElement(name = "Feature")
public List<Feature> getFeatures() {
return features;
}
public void setFeatures(List<Feature> features) {
this.features = features;
}
}
Class for OptionList
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
public class OptionList {
private List<String> option;
#XmlElement(name = "Option")
public List<String> getOption() {
return option;
}
public void setOption(List<String> option) {
this.option = option;
}
}
For testing and simplicity, I have written a small java test program below.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.List;
public class Test {
public static void main(String[] args) {
File file =
new File("E:\\so\\xml\\minxml.xml");
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(InteriorResponse.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
InteriorResponse interiorFeatures = (InteriorResponse) unmarshaller.unmarshal(file);
List<Feature> list_feat = interiorFeatures.getFeatureList().getFeatures();
List<String> optionList = interiorFeatures.getOptionList().getOption();
for (String option : optionList) {
System.out.println("Option Value : " + option);
}
for (Feature ft : list_feat) {
System.out.println(ft.getCode());
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
I also provide the sample xml structure below.
<Features_res>
<StartWeek>202017</StartWeek>
<EndWeek>202035</EndWeek>
<Pno12>ABCDEEB</Pno12>
<FeatureList>
<Feature>
<Code>T002</Code>
</Feature>
<Feature>
<Code>T002</Code>
</Feature>
</FeatureList>
<OptionList>
<Option>001048</Option>
<Option>000050</Option>
<Option>000790</Option>
</OptionList>
</Features_res>
I knew very little about JAXB stuff. I have learned a lot from Sambit who helped a lot and gave me the way to start with this JAXB. Later I have implemented my version with less number of Java class and more smart use of JAXB annotations.
My version of InteriorResponse class:-
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int startWeek;
#XmlElement(name = "EndWeek")
private int endWeek;
#XmlElement(name = "Pno12")
private String pno12;
#XmlElementWrapper(name = "FeatureList")
#XmlElement(name = "Feature")
private List<Feature> featureList;
#XmlElementWrapper(name = "OptionList")
#XmlElement(name = "Option")
private List<String> optionList;
public InteriorResponse() {
}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.startWeek = startWeek;
this.endWeek = endWeek;
this.pno12 = pno12;
}
#XmlTransient
public int getStartWeek() {
return startWeek;
}
public void setStartWeek(int startWeek) {
this.startWeek = startWeek;
}
#XmlTransient
public int getEndWeek() {
return endWeek;
}
public void setEndWeek(int endWeek) {
this.endWeek = endWeek;
}
#XmlTransient
public String getPno12() {
return pno12;
}
public void setPno12(String pno12) {
this.pno12 = pno12;
}
#XmlTransient
public List<Feature> getFeatureList() {
return featureList;
}
public void setFeatureList(List<Feature> featureList) {
this.featureList = featureList;
}
#XmlTransient
public List<String> getOptionList() {
return optionList;
}
public void setOptionList(List<String> optionList) {
this.optionList = optionList;
}
#Override
public String toString() {
return "InteriorResponse{" + "sWeek=" + startWeek + ", eWeek=" + endWeek + ", pno12='" + pno12 + '\'' + ", featureList=" + featureList + ", optionList="
+ optionList + '}';
}
}
My version of Feature class:-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class Feature {
#XmlElement(name = "Code")
private String code;
#XmlTransient
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#Override
public String toString() {
return "Feature{" + "code_='" + code + '\'' + '}';
}
}
Note that I don't need any extra wrapper class for FeatuerList and OptionList. It can be done by the JAXB annotation #XmlElementWrapper(name = "FeatureList"). Also, a very important lesson learned. We have to mark all the property's getter method as #XmlTransient. Otherwise, JAXB throws an exception 2 properties found with the same name. Because our class all properties is visible to the JAXB. So we have to mark one as #XmlTransient.
In my opion, it is a better solution than the accepted answer. I gave all the credit to Sambit. I hove this will help others.
I'm trying to unmarshall XML to POJO VmML class to pass it throught our system. The POJO classes was created from dtd file using jaxb2 maven plugin. When I use feature camel-jaxb in karaf I was able to unmarshall XML file into object of class VmML without any problem, but for some reasons I have to pull back this approach, and finally I end up with camel-jacksonxml.
In the route now I'm using unmarshall tag as below.
<dataFormats>
<jacksonxml id="jack" unmarshalTypeName="com.company.generated.VmML"/>
</dataFormats>
<rest path="/service"
consumes="application/xml"
produces="text/plain">
<post uri="/requestXmlCfg"
type="com.company.generated.VmML"
outType="java.lang.String">
<route>
<unmarshal ref="jack"/>
<to uri="bean:messageProcessot?method=process"/>
</route>
</post>
</rest>
I want to emphasize that it works earlier without unmarshaling tag, when I use simple camel-jaxb feature.
Now I get the exception which appears here often, but in my case the solutions are not proper because the data is provided and I don't want to skip anything. The error is:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ReportType" (class com.company.generated.CarrierReport), not marked as ignorable (3 known properties: "CarrierReportSnapshot", "CarrierReportHeader", "CarrierReportPeriod"])
at [Source: org.apache.camel.component.netty4.http.NettyChannelBufferStreamCache#612e834b; line: 6, column: 42] (through reference chain: com.company.generated.VmML["CarrierReport"]->java.util.ArrayList[0]->com.company.generated.CarrierReport["ReportType"])
POJO classes was created bas on: http://www.vmml.org/spec/VmML_v0.1.dtd
And the XML is filled properly
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE VmML SYSTEM "http://www.vmml.org/spec/VmML_v0.1.dtd">
<VmML Version="0.1">
<CarrierReport>
<CarrierReportHeader>
<ReportType SystemReference="aa">VMML</ReportType>
<ReportTimestamp Timezone="0" TimeFormat="RFC822">Tue, 07 May 2013 15:21:14 %2B0000</ReportTimestamp>
<SenderId SystemReference="aa">aa</SenderId>
<ReceiverId SystemReference="aa">aa</ReceiverId>
<SystemSource>aa</SystemSource>
<SystemDestination>aa</SystemDestination>
</CarrierReportHeader>
<CarrierReportSnapshot>
<Event>
<EventHeader>
<EventTimestamp Timezone="0" TimeFormat="RFC822">Tue, 07 May 2013 15:21:14 %2B0000</EventTimestamp>
<EventCode SystemReference="aa">aa</EventCode>
<EventText>aa</EventText>
</EventHeader>
</Event>
</CarrierReportSnapshot>
</CarrierReport>
</VmML>
VMML class:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"carrierReport"
})
#XmlRootElement(name = "VmML")
public class VmML {
#XmlAttribute(name = "Version", required = true)
#XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String version;
#XmlAttribute(name = "id")
#XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String id;
#XmlElement(name = "CarrierReport", required = true)
protected List<CarrierReport> carrierReport;
public String getVersion() {
return version;
}
public void setVersion(String value) {
this.version = value;
}
public String getId() {
return id;
}
public void setId(String value) {
this.id = value;
}
public List<CarrierReport> getCarrierReport() {
if (carrierReport == null) {
carrierReport = new ArrayList<CarrierReport>();
}
return this.carrierReport;
}
}
CarrierReport class:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"carrierReportHeader",
"carrierReportSnapshot",
"carrierReportPeriod"
})
#XmlRootElement(name = "CarrierReport")
public class CarrierReport {
#XmlElement(name = "CarrierReportHeader", required = true)
protected CarrierReportHeader carrierReportHeader;
#XmlElement(name = "CarrierReportSnapshot")
protected CarrierReportSnapshot carrierReportSnapshot;
#XmlElement(name = "CarrierReportPeriod")
protected CarrierReportPeriod carrierReportPeriod;
public CarrierReportHeader getCarrierReportHeader() {
return carrierReportHeader;
}
public void setCarrierReportHeader(CarrierReportHeader value) {
this.carrierReportHeader = value;
}
public CarrierReportSnapshot getCarrierReportSnapshot() {
return carrierReportSnapshot;
}
public void setCarrierReportSnapshot(CarrierReportSnapshot value) {
this.carrierReportSnapshot = value;
}
public CarrierReportPeriod getCarrierReportPeriod() {
return carrierReportPeriod;
}
public void setCarrierReportPeriod(CarrierReportPeriod value) {
this.carrierReportPeriod = value;
}
}
ReportType
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
#XmlRootElement(name = "ReportType")
public class ReportType {
#XmlAttribute(name = "SystemReference")
#XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String systemReference;
#XmlValue
protected String value;
public String getSystemReference() {
return systemReference;
}
public void setSystemReference(String value) {
this.systemReference = value;
}
public String getvalue() {
return value;
}
public void setvalue(String value) {
this.value = value;
}
}
Vmml > Carier Report > Carier Report Header > ReportType class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"reportType",
"reportTimestamp",
"senderId",
"receiverId",
"systemSource",
"systemDestination",
"missionId",
"missionName"
})
#XmlRootElement(name = "CarrierReportHeader")
public class CarrierReportHeader {
#XmlElement(name = "ReportType", required = true)
protected ReportType reportType;
#XmlElement(name = "ReportTimestamp", required = true)
protected ReportTimestamp reportTimestamp;
#XmlElement(name = "SenderId", required = true)
protected SenderId senderId;
#XmlElement(name = "ReceiverId")
protected ReceiverId receiverId;
#XmlElement(name = "SystemSource", required = true)
protected String systemSource;
#XmlElement(name = "SystemDestination")
protected String systemDestination;
#XmlElement(name = "MissionId")
protected MissionId missionId;
#XmlElement(name = "MissionName")
protected String missionName;
public ReportType getReportType() {
return reportType;
}
public void setReportType(ReportType value) {
this.reportType = value;
}
public ReportTimestamp getReportTimestamp() {
return reportTimestamp;
}
public void setReportTimestamp(ReportTimestamp value) {
this.reportTimestamp = value;
}
public SenderId getSenderId() {
return senderId;
}
public void setSenderId(SenderId value) {
this.senderId = value;
}
public ReceiverId getReceiverId() {
return receiverId;
}
public void setReceiverId(ReceiverId value) {
this.receiverId = value;
}
public String getSystemSource() {
return systemSource;
}
public void setSystemSource(String value) {
this.systemSource = value;
}
public String getSystemDestination() {
return systemDestination;
}
public void setSystemDestination(String value) {
this.systemDestination = value;
}
public MissionId getMissionId() {
return missionId;
}
public void setMissionId(MissionId value) {
this.missionId = value;
}
public String getMissionName() {
return missionName;
}
public void setMissionName(String value) {
this.missionName = value;
}
}