Want to create a hashmap with a key(String) and value(Node) - java

I want to create a hashmap which is to have as 'Key' and the node as 'Value'. Can i know how do i do that using hashmap ? I will be creating two hashmaps on similar pattern, later want to compare it based on the 'Key(srv_field). Let me know how do i initialise and store the required data into hashmap.
Input xml is as below.
<?xml version="1.0" encoding="UTF-8"?>
<menu-details>
<menu name="HCOTA">
<group name="cota" type="M">
<page-details>
<page>
<name>cotacrit</name>
<field>
<field-type></field-type>
<srv-field>taChrgOffMsg.taChrgOffCrit.funcCode</srv-field>
<ui-field>funcCode</ui-field>
<label>FLT000204</label>
<mandatory>Y</mandatory>
<custom-pattern type=""></custom-pattern>
</field>
<field >
<field-type></field-type>
<srv-field>taChrgOffMsg.taChrgOffCrit.Acct.foracid</srv-field>
<ui-field>acctId</ui-field>
<label>FLT000265</label>
<mandatory>Y</mandatory>
<custom-pattern type=""></custom-pattern>
</field>
<field>
<srv-field>taChrgOffMsg.taChrgOffCrit.chargeOffType</srv-field>
<ui-field>chargeOffMode</ui-field>
<label>FLT004530</label>
<mandatory>Y</mandatory>
</field>
</page>
</page-details>
</group>
</menu>
</menu-details>
Java Object :
package com.ui.mig.menuvo;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"menu"
})
#XmlRootElement(name = "menu-details")
public class MenuDetails {
protected List<MenuDetails.Menu> menu;
public List<MenuDetails.Menu> getMenu() {
if (menu == null) {
menu = new ArrayList<MenuDetails.Menu>();
}
return this.menu;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"group"
})
public static class Menu {
protected List<MenuDetails.Menu.Group> group;
#XmlAttribute(name = "name", namespace = "http://www..com/migration/")
protected String name;
public List<MenuDetails.Menu.Group> getGroup() {
if (group == null) {
group = new ArrayList<MenuDetails.Menu.Group>();
}
return this.group;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"pageDetails"
})
public static class Group {
#XmlElement(name = "page-details", required = true)
protected MenuDetails.Menu.Group.PageDetails pageDetails;
#XmlAttribute(name = "name", namespace = "http://www..com/migration/")
protected String name;
#XmlAttribute(name = "type", namespace = "http://www./migration/")
protected String type;
public MenuDetails.Menu.Group.PageDetails getPageDetails() {
return pageDetails;
}
public void setPageDetails(MenuDetails.Menu.Group.PageDetails value) {
this.pageDetails = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"page"
})
public static class PageDetails {
protected List<MenuDetails.Menu.Group.PageDetails.Page> page;
public List<MenuDetails.Menu.Group.PageDetails.Page> getPage() {
if (page == null) {
page = new ArrayList<MenuDetails.Menu.Group.PageDetails.Page>();
}
return this.page;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"pageName",
"field"
})
public static class Page {
#XmlElement(name = "page-name", required = true)
protected String pageName;
protected List<MenuDetails.Menu.Group.PageDetails.Page.Field> field;
public String getPageName() {
return pageName;
}
public void setPageName(String value) {
this.pageName = value;
}
public List<MenuDetails.Menu.Group.PageDetails.Page.Field> getField() {
if (field == null) {
field = new ArrayList<MenuDetails.Menu.Group.PageDetails.Page.Field>();
}
return this.field;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"fieldType",
"srvField",
"uiField",
"label",
"mandatory",
"customPattern"
})
public static class Field {
#XmlElement(name = "field-type", required = true)
protected String fieldType;
#XmlElement(name = "srv-field", required = true)
protected String srvField;
#XmlElement(name = "ui-field", required = true)
protected String uiField;
#XmlElement(required = true)
protected String label;
#XmlElement(required = true)
protected String mandatory;
#XmlElement(name = "custom-pattern", required = true)
protected MenuDetails.Menu.Group.PageDetails.Page.Field.CustomPattern customPattern;
public String getFieldType() {
return fieldType;
}
public void setFieldType(String value) {
this.fieldType = value;
}
public String getSrvField() {
return srvField;
}
public void setSrvField(String value) {
this.srvField = value;
}
public String getUiField() {
return uiField;
}
public void setUiField(String value) {
this.uiField = value;
}
public String getLabel() {
return label;
}
public void setLabel(String value) {
this.label = value;
}
public String getMandatory() {
return mandatory;
}
public void setMandatory(String value) {
this.mandatory = value;
}
public MenuDetails.Menu.Group.PageDetails.Page.Field.CustomPattern getCustomPattern() {
return customPattern;
}
public void setCustomPattern(MenuDetails.Menu.Group.PageDetails.Page.Field.CustomPattern value) {
this.customPattern = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
public static class CustomPattern {
#XmlValue
protected String value;
#XmlAttribute(name = "type", namespace = "http://www.com/migration/")
protected String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
}
}
}
}
}
}
}

Map<String,Node> map = new HashMap<String,Node>();
// or new HashMap<>();
map.put("asdf", new Node());
To get a value:
Node n = map.get("asdf");
You can compare values by getting Nodes from two Maps and comparing them, possibly with .equals().
There are other Map methods, which are detailed in the documentation.

Related

unable to convert xml to pojo using jaxb

I am trying to convert xml to pojo.
These pojo are generated from a xsd using jaxb eclipse plugin.
Xml is :
<?xml version="1.0"?>
<NIServicesResponse>
  <header>
    <version>1.0</version>
    <msg_id>12345</msg_id>
    <msg_type>ENQUIRY</msg_type>
    <msg_function>REP_CREDIT_CARD_BALANCE_ENQUIRY</msg_function>
    <src_application>MIB</src_application>
    <target_application>VISIONPLUS</target_application>
    <timestamp>2019-01-28T14:11:15.927+04:00</timestamp>
    <tracking_id>2213695</tracking_id>
    <bank_id>ADCB</bank_id>
  </header>
  <body>
    <srv_rep>
      <exception_details>
        <application_name>NITIB_TCC_BRK_ADCB_SS</application_name>
        <date_time>2019-01-28T14:11:15.927+04:00</date_time>
        <status>S</status>
        <error_code>000</error_code>
        <error_description>Success</error_description>
        <transaction_ref_id>2213695</transaction_ref_id>
      </exception_details>
      <rep_credit_card_balance_enquiry>
        <balance_enquiry>
          <card_no>5261XXXXXXXX5793</card_no>
          <card_brand>MASTERCARD</card_brand>
          <card_currency>AED</card_currency>
          <card_limit>40000.00</card_limit>
          <available_credit>42456.00</available_credit>
          <cash_limit>24000.00</cash_limit>
          <available_cash>25200.00</available_cash>
          <outstanding_balance>-456.00</outstanding_balance>
          <expiry_date>01/01/2021</expiry_date>
          <overlimit_flag>N</overlimit_flag>
          <overlimit_amount>0.00</overlimit_amount>
          <min_payment>0.00</min_payment>
          <due_date>09/11/2018</due_date>
          <unbilled_amount>0.00</unbilled_amount>
          <past_due_flag>N</past_due_flag>
          <past_due_amount>0.00</past_due_amount>
        </balance_enquiry>
      </rep_credit_card_balance_enquiry>
    </srv_rep>
  </body>
</NIServicesResponse>
Pojo is :
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"header",
"body"
})
#XmlRootElement(name = "NIServicesResponse", namespace = "http://adcb.com/poc/wiremock")
public class NIServicesResponse {
#XmlElement(required = true)
protected NIServicesResponse.Header header;
#XmlElement(required = true)
protected NIServicesResponse.Body body;
public NIServicesResponse.Header getHeader() {
return header;
}
public void setHeader(NIServicesResponse.Header value) {
this.header = value;
}
public NIServicesResponse.Body getBody() {
return body;
}
public void setBody(NIServicesResponse.Body value) {
this.body = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"srvRep"
})
public static class Body {
#XmlElement(name = "srv_rep", required = true)
protected NIServicesResponse.Body.SrvRep srvRep;
public NIServicesResponse.Body.SrvRep getSrvRep() {
return srvRep;
}
public void setSrvRep(NIServicesResponse.Body.SrvRep value) {
this.srvRep = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"exceptionDetails",
"repCreditCardBalanceEnquiry"
})
public static class SrvRep {
#XmlElement(name = "exception_details", required = true)
protected NIServicesResponse.Body.SrvRep.ExceptionDetails exceptionDetails;
#XmlElement(name = "rep_credit_card_balance_enquiry", required = true)
protected NIServicesResponse.Body.SrvRep.RepCreditCardBalanceEnquiry repCreditCardBalanceEnquiry;
public NIServicesResponse.Body.SrvRep.ExceptionDetails getExceptionDetails() {
return exceptionDetails;
}
public void setExceptionDetails(NIServicesResponse.Body.SrvRep.ExceptionDetails value) {
this.exceptionDetails = value;
}
public NIServicesResponse.Body.SrvRep.RepCreditCardBalanceEnquiry getRepCreditCardBalanceEnquiry() {
return repCreditCardBalanceEnquiry;
}
public void setRepCreditCardBalanceEnquiry(NIServicesResponse.Body.SrvRep.RepCreditCardBalanceEnquiry value) {
this.repCreditCardBalanceEnquiry = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"applicationName",
"dateTime",
"status",
"errorCode",
"errorDescription",
"transactionRefId"
})
public static class ExceptionDetails {
#XmlElement(name = "application_name", required = true)
protected String applicationName;
#XmlElement(name = "date_time", required = true)
protected String dateTime;
#XmlElement(required = true)
protected String status;
#XmlElement(name = "error_code")
protected int errorCode;
#XmlElement(name = "error_description", required = true)
protected String errorDescription;
#XmlElement(name = "transaction_ref_id")
protected int transactionRefId;
/**
* Gets the value of the applicationName property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String value) {
this.applicationName = value;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String value) {
this.dateTime = value;
}
public String getStatus() {
return status;
}
public void setStatus(String value) {
this.status = value;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int value) {
this.errorCode = value;
}
public String getErrorDescription() {
return errorDescription;
}
public void setErrorDescription(String value) {
this.errorDescription = value;
}
public int getTransactionRefId() {
return transactionRefId;
}
public void setTransactionRefId(int value) {
this.transactionRefId = value;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"balanceEnquiry"
})
public static class RepCreditCardBalanceEnquiry {
#XmlElement(name = "balance_enquiry", required = true)
protected NIServicesResponse.Body.SrvRep.RepCreditCardBalanceEnquiry.BalanceEnquiry balanceEnquiry;
public NIServicesResponse.Body.SrvRep.RepCreditCardBalanceEnquiry.BalanceEnquiry getBalanceEnquiry() {
return balanceEnquiry;
}
public void setBalanceEnquiry(NIServicesResponse.Body.SrvRep.RepCreditCardBalanceEnquiry.BalanceEnquiry value) {
this.balanceEnquiry = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"cardNo",
"cardBrand",
"cardCurrency",
"cardLimit",
"availableCredit",
"cashLimit",
"availableCash",
"outstandingBalance",
"expiryDate",
"overlimitFlag",
"overlimitAmount",
"minPayment",
"dueDate",
"unbilledAmount",
"pastDueFlag",
"pastDueAmount"
})
public static class BalanceEnquiry {
#XmlElement(name = "card_no", required = true)
protected String cardNo;
#XmlElement(name = "card_brand", required = true)
protected String cardBrand;
#XmlElement(name = "card_currency", required = true)
protected String cardCurrency;
#XmlElement(name = "card_limit")
protected int cardLimit;
#XmlElement(name = "available_credit")
protected int availableCredit;
#XmlElement(name = "cash_limit")
protected int cashLimit;
#XmlElement(name = "available_cash")
protected int availableCash;
#XmlElement(name = "outstanding_balance")
protected int outstandingBalance;
#XmlElement(name = "expiry_date", required = true)
protected String expiryDate;
#XmlElement(name = "overlimit_flag", required = true)
protected String overlimitFlag;
#XmlElement(name = "overlimit_amount")
protected int overlimitAmount;
#XmlElement(name = "min_payment")
protected int minPayment;
#XmlElement(name = "due_date", required = true)
protected String dueDate;
#XmlElement(name = "unbilled_amount")
protected int unbilledAmount;
#XmlElement(name = "past_due_flag", required = true)
protected String pastDueFlag;
#XmlElement(name = "past_due_amount")
protected int pastDueAmount;
public String getCardNo() {
return cardNo;
}
public void setCardNo(String value) {
this.cardNo = value;
}
public String getCardBrand() {
return cardBrand;
}
public void setCardBrand(String value) {
this.cardBrand = value;
}
public String getCardCurrency() {
return cardCurrency;
}
public void setCardCurrency(String value) {
this.cardCurrency = value;
}
public int getCardLimit() {
return cardLimit;
}
public void setCardLimit(int value) {
this.cardLimit = value;
}
public int getAvailableCredit() {
return availableCredit;
}
public void setAvailableCredit(int value) {
this.availableCredit = value;
}
public int getCashLimit() {
return cashLimit;
}
public void setCashLimit(int value) {
this.cashLimit = value;
}
public int getAvailableCash() {
return availableCash;
}
public void setAvailableCash(int value) {
this.availableCash = value;
}
public int getOutstandingBalance() {
return outstandingBalance;
}
public void setOutstandingBalance(int value) {
this.outstandingBalance = value;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String value) {
this.expiryDate = value;
}
public String getOverlimitFlag() {
return overlimitFlag;
}
public void setOverlimitFlag(String value) {
this.overlimitFlag = value;
}
public int getOverlimitAmount() {
return overlimitAmount;
}
public void setOverlimitAmount(int value) {
this.overlimitAmount = value;
}
public int getMinPayment() {
return minPayment;
}
public void setMinPayment(int value) {
this.minPayment = value;
}
public String getDueDate() {
return dueDate;
}
public void setDueDate(String value) {
this.dueDate = value;
}
public int getUnbilledAmount() {
return unbilledAmount;
}
public void setUnbilledAmount(int value) {
this.unbilledAmount = value;
}
public String getPastDueFlag() {
return pastDueFlag;
}
public void setPastDueFlag(String value) {
this.pastDueFlag = value;
}
public int getPastDueAmount() {
return pastDueAmount;
}
public void setPastDueAmount(int value) {
this.pastDueAmount = value;
}
}
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"version",
"msgId",
"msgType",
"msgFunction",
"srcApplication",
"targetApplication",
"timestamp",
"trackingId",
"bankId"
})
public static class Header {
#XmlElement(required = true)
protected String version;
#XmlElement(name = "msg_id")
protected long msgId;
#XmlElement(name = "msg_type", required = true)
protected String msgType;
#XmlElement(name = "msg_function", required = true)
protected String msgFunction;
#XmlElement(name = "src_application", required = true)
protected String srcApplication;
#XmlElement(name = "target_application", required = true)
protected String targetApplication;
#XmlElement(required = true)
protected String timestamp;
#XmlElement(name = "tracking_id")
protected long trackingId;
#XmlElement(name = "bank_id", required = true)
protected String bankId;
public String getVersion() {
return version;
}
public void setVersion(String value) {
this.version = value;
}
public long getMsgId() {
return msgId;
}
public void setMsgId(long value) {
this.msgId = value;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String value) {
this.msgType = value;
}
public String getMsgFunction() {
return msgFunction;
}
public void setMsgFunction(String value) {
this.msgFunction = value;
}
public String getSrcApplication() {
return srcApplication;
}
public void setSrcApplication(String value) {
this.srcApplication = value;
}
public String getTargetApplication() {
return targetApplication;
}
public void setTargetApplication(String value) {
this.targetApplication = value;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String value) {
this.timestamp = value;
}
public long getTrackingId() {
return trackingId;
}
public void setTrackingId(long value) {
this.trackingId = value;
}
public String getBankId() {
return bankId;
}
public void setBankId(String value) {
this.bankId = value;
}
}
}
using following codeto unmarshall it :
JAXBContext jaxbContext = JAXBContext.newInstance(NIServicesResponse.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
NIServicesResponse niServicesResponse = (NIServicesResponse)unmarshaller.unmarshal(httpResponse.getEntity().getContent());
While converting it is giving error ;
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"NIServicesResponse"). Expected elements are <{http://adcb.com/poc/wiremock}NIServicesResponse>
I have tried to convert simple xml to pojo but that worked. But unable to find out what is problem with my pojo.
You don't need to use namespace = "http://adcb.com/poc/wiremock"
If there is no xmlns="http://adcb.com/poc/wiremock" inside

Specifying root and child nodes with JAXB

Staying within JAXB how would I refactor MyNote so that it conforms to:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Which is well formed but not valid, to my understanding. Current output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MyNotes>
<Note>
<note>XY3Z1RGEO9W79LALCS</note>
<to>LJAY9RNMUGGENGNND9</to>
<from>GOVSHVZ3GJWC864L7X</from>
<heading>EX6LGVE5LGY4A6B9SK</heading>
<body>L95WYQNMEU1MFDRBG4</body>
</Note>
</MyNotes>
which is too flat, rather than nested as the example.
I believe this makes note the root element, with other elements being children nodes to note if I'm using correct terminology.
The MyNote class:
package net.bounceme.dur.jaxb.hello.world;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlType(propOrder = {"note", "to", "from", "heading", "body"})
#XmlRootElement(name = "note")
public class MyNote {
private String note;
private String to;
private String from;
private String heading;
private String body;
public String getNote() {
return note;
}
#XmlElement(name = "note")
public void setNote(String note) {
this.note = note;
}
public String getTo() {
return to;
}
#XmlElement(name = "to")
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
return from;
}
#XmlElement(name = "from")
public void setFrom(String from) {
this.from = from;
}
public String getHeading() {
return heading;
}
#XmlElement(name = "heading")
public void setHeading(String heading) {
this.heading = heading;
}
public String getBody() {
return body;
}
#XmlElement(name = "body")
public void setBody(String body) {
this.body = body;
}
#Override
public String toString() {
return note + to + from + heading + body;
}
}
The MyNotes class:
package net.bounceme.dur.jaxb.hello.world;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "MyNotes")
public class MyNotes {
private static final Logger LOG = Logger.getLogger(MyNotes.class.getName());
private List<MyNote> myNotes = new ArrayList<>();
public MyNotes() {
}
public List<MyNote> getMyNotes() {
LOG.info(myNotes.toString());
return myNotes;
}
#XmlElement(name = "Note")
public void setMyNotes(List<MyNote> myNotes) {
LOG.info(myNotes.toString());
this.myNotes = myNotes;
}
public void add(MyNote myNote) {
LOG.info(myNote.toString());
myNotes.add(myNote);
}
#Override
public String toString() {
StringBuffer str = new StringBuffer();
for (MyNote note : this.myNotes) {
str.append(note.toString());
}
return str.toString();
}
}
exercising the MyNote and MyNotes classes:
public MyNotes unmarshallMyNotesFromFile(URI uri) throws Exception {
File file = new File(uri);
JAXBContext jaxbContext = JAXBContext.newInstance(MyNotes.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
MyNotes myNotes = (MyNotes) jaxbUnmarshaller.unmarshal(file);
return myNotes;
}
public void marshallMyNotesAndWriteToFile(MyNotes notes, URI uri) throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance(MyNotes.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(notes, new File(uri));
jaxbMarshaller.marshal(notes, System.out);
}
I'm looking to grab this xml through the web; first need to match the structure to the example.
You are very close. You need to change how you name your xmlElement for myNotes in MyNotes class. Also MyNote should not have a note field itself (according to your desired xml). Your edited classes would look like this (I also removed the logging statements for my convenience):
#XmlType(propOrder = { "to", "from", "heading", "body"})
#XmlRootElement(name = "note")
public class MyNote {
private String to;
private String from;
private String heading;
private String body;
public String getTo() {
return to;
}
#XmlElement(name = "to")
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
return from;
}
#XmlElement(name = "from")
public void setFrom(String from) {
this.from = from;
}
public String getHeading() {
return heading;
}
#XmlElement(name = "heading")
public void setHeading(String heading) {
this.heading = heading;
}
public String getBody() {
return body;
}
#XmlElement(name = "body")
public void setBody(String body) {
this.body = body;
}
#Override
public String toString() {
return to + from + heading + body;
}
}
and MyNotes:
#XmlRootElement(name = "MyNotes")
public class MyNotes {
private List<MyNote> myNotes = new ArrayList<>();
public MyNotes() {
}
public List<MyNote> getMyNotes() {
return myNotes;
}
#XmlElement(name = "note")
public void setMyNotes(List<MyNote> myNotes) {
this.myNotes = myNotes;
}
public void add(MyNote myNote) {
myNotes.add(myNote);
}
#Override
public String toString() {
StringBuffer str = new StringBuffer();
for (MyNote note : this.myNotes) {
str.append(note.toString());
}
return str.toString();
}
}

How do I reference a JAXB POJO in a mule flow

I have successfully unmarshalled an XML document into a JAXB object but now, I would like to reference the object in the flow and insert the value of it's properties into a database table.
The flow is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="10009" basePath="/ipay/bra" doc:name="HTTP Listener Configuration"/>
<mulexml:jaxb-context name="JAXB_Context" packageNames="com.dhg.api" doc:name="JAXB Context"/>
<flow name="transaction_initiation_testFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/transaction" doc:name="HTTP">
<http:response-builder>
<http:header headerName="Content-Type" value="text/xml"/>
</http:response-builder>
</http:listener>
<mulexml:jaxb-xml-to-object-transformer returnClass="com.dhg.api.PAYMENTS" jaxbContext-ref="JAXB_Context" doc:name="XML to JAXB Object"/>
<logger message="#[payload.transaction.email]" level="INFO" doc:name="Logger"/>
<echo-component doc:name="Echo"/>
</flow>
</mule>
The object is as follows:
package com.dhg.api;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {"transaction"})
#XmlRootElement(name = "PAYMENTS")
public class PAYMENTS {
#XmlElement(name = "TRANSACTION", required = true)
protected PAYMENTS.TRANSACTION transaction;
public PAYMENTS.TRANSACTION getTRANSACTION() {
return transaction;
}
public void setTRANSACTION(PAYMENTS.TRANSACTION value) {
this.transaction = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"entity",
"useraddress1",
"useraddress2",
"useraddress3",
"usercountry",
"userparish",
"totalamount",
"payer",
"status",
"ipaynumber",
"email"
})
public static class TRANSACTION {
#XmlElement(name = "ENTITY", required = true)
protected PAYMENTS.TRANSACTION.ENTITY entity;
#XmlElement(name = "USERADDRESS1", required = true)
protected String useraddress1;
#XmlElement(name = "USERADDRESS2", required = true)
protected String useraddress2;
#XmlElement(name = "USERADDRESS3", required = true)
protected String useraddress3;
#XmlElement(name = "USERCOUNTRY", required = true)
protected String usercountry;
#XmlElement(name = "USERPARISH", required = true)
protected String userparish;
#XmlElement(name = "TOTALAMOUNT")
protected float totalamount;
#XmlElement(name = "PAYER", required = true)
protected String payer;
#XmlElement(name = "STATUS", required = true)
protected String status;
#XmlElement(name = "IPAYNUMBER")
protected int ipaynumber;
#XmlElement(name = "EMAIL", required = true)
protected String email;
#XmlAttribute(name = "txdate")
protected String txdate;
#XmlAttribute(name = "txno")
protected String txno;
public PAYMENTS.TRANSACTION.ENTITY getENTITY() {
return entity;
}
public void setENTITY(PAYMENTS.TRANSACTION.ENTITY value) {
this.entity = value;
}
public String getUSERADDRESS1() {
return useraddress1;
}
public void setUSERADDRESS1(String value) {
this.useraddress1 = value;
}
public String getUSERADDRESS2() {
return useraddress2;
}
public void setUSERADDRESS2(String value) {
this.useraddress2 = value;
}
public String getUSERADDRESS3() {
return useraddress3;
}
public void setUSERADDRESS3(String value) {
this.useraddress3 = value;
}
public String getUSERCOUNTRY() {
return usercountry;
}
public void setUSERCOUNTRY(String value) {
this.usercountry = value;
}
public String getUSERPARISH() {
return userparish;
}
public void setUSERPARISH(String value) {
this.userparish = value;
}
public float getTOTALAMOUNT() {
return totalamount;
}
public void setTOTALAMOUNT(float value) {
this.totalamount = value;
}
public String getPAYER() {
return payer;
}
public void setPAYER(String value) {
this.payer = value;
}
public String getSTATUS() {
return status;
}
public void setSTATUS(String value) {
this.status = value;
}
public int getIPAYNUMBER() {
return ipaynumber;
}
public void setIPAYNUMBER(int value) {
this.ipaynumber = value;
}
public String getEMAIL() {
return email;
}
public void setEMAIL(String value) {
this.email = value;
}
public String getTxdate() {
return txdate;
}
public void setTxdate(String value) {
this.txdate = value;
}
public String getTxno() {
return txno;
}
public void setTxno(String value) {
this.txno = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"account"
})
public static class ENTITY {
#XmlElement(name = "ACCOUNT", required = true)
protected PAYMENTS.TRANSACTION.ENTITY.ACCOUNT account;
#XmlAttribute(name = "biller")
protected String biller;
public PAYMENTS.TRANSACTION.ENTITY.ACCOUNT getACCOUNT() {
return account;
}
public void setACCOUNT(PAYMENTS.TRANSACTION.ENTITY.ACCOUNT value) {
this.account = value;
}
public String getBiller() {
return biller;
}
public void setBiller(String value) {
this.biller = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"details"
})
public static class ACCOUNT {
#XmlElement(name = "DETAILS", required = true)
protected PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS details;
#XmlAttribute(name = "bpnumber")
protected Integer bpnumber;
public PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS getDETAILS(){
return details;
}
public void setDETAILS(PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS value) {
this.details = value;
}
public Integer getBpnumber() {
return bpnumber;
}
public void setBpnumber(Integer value) {
this.bpnumber = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"dockey"
})
public static class DETAILS {
#XmlElement(name = "DOCKEY")
protected List<PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS.DOCKEY> dockey;
public List<PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS.DOCKEY> getDOCKEY() {
if (dockey == null) {
dockey = new ArrayList<PAYMENTS.TRANSACTION.ENTITY.ACCOUNT.DETAILS.DOCKEY>();
}
return this.dockey;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
public static class DOCKEY {
#XmlValue
protected String value;
#XmlAttribute(name = "payment")
protected Float payment;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Float getPayment() {
return payment;
}
public void setPayment(Float value) {
this.payment = value;
}
}
}
}
}
}
}
After unmarshalling, the object is instantiated as com.dhg.api.PAYMENTS#some_random_string, which makes it difficult to reference. So my question is simply, how can I refer to this object and be able to access the values for use elsewhere in the flow.
Thanks for your help.
Your setter/getter is not compliant with property names in :
public PAYMENTS.TRANSACTION getTRANSACTION() {
return transaction;
}
public void setTRANSACTION(PAYMENTS.TRANSACTION value) {
this.transaction = value;
}
So in <logger message="#[payload.transaction.email]" level="INFO" doc:name="Logger"/> the transaction part is null.
The correct getter name is getTransaction and is the same for setter. Change them please

convert xml to java object using JAXB

I have the following XML and want to convert it into Java object.
<?xml version="1.0" encoding="UTF-8"?>
<datasources xmlns="http://www.jboss.org/ironjacamar/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd">
<datasource jndi-name="java:jboss/datasources/FDMS_DemoDS" pool-name="FDMS_DemoDS">
<connection-url>jdbc:mysql://localhost:3306/demo?zeroDateTimeBehavior=convertToNull</connection-url>
<driver>com.mysql</driver>
<pool>
<max-pool-size>60</max-pool-size>
</pool>
<security>
<user-name>fduser</user-name>
<password>fdms!</password>
</security>
</datasource>
</datasources>
I am not sure what will be my corresponding java class when I use JAXB to convert it.
This is what I have tried so far based on my understanding:
#XmlRootElement
public class Datasources {
String connectionUrl;
String maxPoolSize;
String driver;
public String getConnectionUrl() {
return connectionUrl;
}
#XmlElement
public void setConnectionUrl(String connectionUrl) {
this.connectionUrl = connectionUrl;
}
public String getMaxPoolSize() {
return maxPoolSize;
}
#XmlElement
public void setMaxPoolSize(String maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public String getDriver() {
return driver;
}
#XmlElement
public void setDriver(String driver) {
this.driver = driver;
}
}
Here's the Java classes with the JAXB annotation.
This is not 100% accurate but it may help you.
Datasources.java
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"datasource"
})
public class Datasources {
#XmlElement(name = "datasource")
private List<Datasource> datasources;
public List<Datasource> getDatasources() {
if (datasource == null) {
datasources = new ArrayList<Datasource>();
}
return datasources
}
}
Datasource.java
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"connection-url",
"driver",
"pool",
"security"
})
public class Datasource {
#XmlElement(name = "connection-url")
private String connectionUrl;
#XmlElement(name = "driver")
private String driver;
#XmlElement(name = "pool")
private Pool pool;
#XmlElement(name = "security")
private Security security;
public String getConnectionUrl() {
return connectionUrl;
}
public void setConnectionUrl(String value) {
this.connectionUrl = value;
}
public String getDriver() {
return driver;
}
public void setDriver(String value) {
this.driver = value;
}
public Pool getPool() {
return pool;
}
public void setPool(Pool value) {
this.pool = value;
}
public Security getSecurity() {
return security;
}
public void setSecurity(Security value) {
this.security = value;
}
}
Pool.java
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"max-pool-size"
})
public class Pool {
#XmlElement(name = "max-pool-size")
private String maxPoolSize;
public String getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(String value) {
this.maxPoolSize = value;
}
}
Security.java
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"user-name",
"password"
})
public class Security {
#XmlElement(name = "user-name")
private String username;
#XmlElement(name = "password")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String value) {
this.username = value;
}
public String getPassword() {
return password;
}
public void setPassword(String value) {
this.password = value;
}
}

Parsing XML data into string objects using JAXB

I have to parse a xml into string objects in JAXB. But how to creates objects for this xml
Country.xml
<?xml version="1.0" encoding="UTF-8"?>
<Country>
<name>India</name>
<capital>New Delhi</capital>
<population>120crores</population>
.
.
.
.
.
<states>
<state>
<name>Maharastra</name>
<pincode>xyzzzz</pincode>
<capital>Mumbai</capital>
<\state>
<state>
.
.
.
</state>
</states>
<\Country>
And to parse this xml I have created class to map the objects which creates the objects and print it in the console. But Don't know what I am doing wrong.
#XmlElementWrapper(name="Country")
public void setCountry(String Countryv) {
Country= Countryv;
}
#XmlElement (name = "name")
public void setname(String namev) {
name= namev;
}
#XmlElement (name = "capital")
public void setcapital(String capitalv) {
capital= capitalv;
}
#XmlElement (name = "population")
public void setpopulation(String populationv) {
population= populationv;
}
#XmlElementWrapper(name="states")
public void setType(String statesv) {
states = statesv;
}
#XmlElementWrapper(name="state")
public void setType(String statev) {
state = statev;
}
#XmlElement (name = "name")
public void setpopulation(String namev) {
name= namev;
}
#XmlElement (name = "pincode")
public void setpopulation(String pincodev) {
pincode= pincodev;
}
#XmlElement (name = "capital")
public void setpopulation(String capitalv) {
capital= capitalv;
}
when I run the program I m getting the
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
counts of IllegalAnnotationExceptions
How to add wrapper anotations to wrapping the elements under separate headers and headers inside other headers.
Try this class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"capital",
"population",
"states"
})
#XmlRootElement(name = "Country")
public class Country {
#XmlElement(required = true)
protected String name;
#XmlElement(required = true)
protected String capital;
#XmlElement(required = true)
protected String population;
#XmlElement(required = true)
protected Country.States states;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getCapital() {
return capital;
}
public void setCapital(String value) {
this.capital = value;
}
public String getPopulation() {
return population;
}
public void setPopulation(String value) {
this.population = value;
}
public Country.States getStates() {
return states;
}
public void setStates(Country.States value) {
this.states = value;
}
This worked for me
class Country {
#XmlElement
String name;
//...
#XmlElementWrapper(name="states")
List<State> state;
}
class State {
#XmlElement
String name;
//..
}

Categories