Java - get convert xml string (soap) to java object - java

I am using Spring Boot and Java 11.
The following SAOP Response has a list of HotelStays. How do I get the list of HotelStay object?
XML
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:awsse="http://xml.xxxx.com/2010/06/Session_v3" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<soap:Header>
<wsa:To>http://www.w3.org/2005/08/addressing/anonymous</wsa:To>
<wsa:From>
<wsa:Address>https://nodeD2.production.webservices.xxxx.com/XXXX</wsa:Address>
</wsa:From>
<wsa:Action>http://webservices.xxxx.com/Hotel_MultiSingleAvailability_10.0</wsa:Action>
<wsa:MessageID>urn:uuid:xxxx</wsa:MessageID>
<wsa:RelatesTo RelationshipType="http://www.w3.org/2005/08/addressing/reply">XXXX</wsa:RelatesTo>
<awsse:Session TransactionStatusCode="End">
<awsse:SessionId>xxxx</awsse:SessionId>
<awsse:SequenceNumber>1</awsse:SequenceNumber>
<awsse:SecurityToken>XXXX</awsse:SecurityToken>
</awsse:Session>
</soap:Header>
<soap:Body>
<OTA_HotelAvailRS xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05 OTA_HotelAvailRS.xsd" EchoToken="MultiSingle" Version="6.001" PrimaryLangID="EN">
<Success />
<Warnings>
<Warning Type="3" Status="PRV.40" Tag="CLS" />
<Warning Type="3" Status="PRV.56" Tag="OK" />
</Warnings>
<HotelStays>
<HotelStay RoomStayRPH="0 1 2 3 4 5 6">
<BasicPropertyInfo ChainCode="BK" HotelCode="BKDURB3H" HotelCityCode="DUR" HotelName="BAYSIDE HOTEL & SELF CATERING 110 WEST S" HotelCodeContext="1A" ChainName="BOOKING.COM" AreaID="4" HotelSegmentCategoryCode="16" SupplierIntegrationLevel="3">
<Position Latitude="-2985829" Longitude="3102385" />
<Address>
<AddressLine>110 DOCTOR PIXLEY KASEME STREET (WEST STREET)STREET</AddressLine>
<CityName>DURBAN</CityName>
<PostalCode>4001</PostalCode>
<CountryName Code="ZA" />
</Address>
<Award Provider="LSR" Rating="2" />
<RelativePosition Direction="E" Distance="0.2" UnitOfMeasureCode="2">
<Transportations>
<Transportation TransportationCode="20" />
</Transportations>
</RelativePosition>
</BasicPropertyInfo>
</HotelStay>
<HotelStay RoomStayRPH="7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28">
<BasicPropertyInfo ChainCode="BK" HotelCode="BKDURB34" HotelCityCode="DUR" HotelName="DURBAN MANOR HOTEL AND CONFERENCE CENTRE" HotelCodeContext="1A" ChainName="BOOKING.COM" AreaID="4" HotelSegmentCategoryCode="16" SupplierIntegrationLevel="3">
<Position Latitude="-2986047" Longitude="3102419" />
<Address>
<AddressLine>1 DURBAN CLUB PLACE</AddressLine>
<CityName>DURBAN</CityName>
<PostalCode>4000</PostalCode>
<CountryName Code="ZA" />
</Address>
<Award Provider="LSR" Rating="3" />
<RelativePosition Direction="E" Distance="0.3" UnitOfMeasureCode="2">
<Transportations>
<Transportation TransportationCode="20" />
</Transportations>
</RelativePosition>
</BasicPropertyInfo>
</HotelStay>
</HotelStays>
</OTA_HotelAvailRS>
</soap:Body>
</soap:Envelope>
When I try create a Document it is always empty ([#document: null]):
public static Document getDocument(final String soapMessage) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(soapMessage));
Document doc = db.parse(is);
return doc;
}

Related

Finding a substring that is enclosed withing double quotes in java

My code :
String content = '<?xml version="1.0" encoding="UTF-8"?>
<svg width="16px" height="16px" viewBox="0 0 16 16" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 64 (93537) - https://sketch.com -->
<title>Group 36 Copy 4</title>
<desc>Created with Sketch.</desc>
<g id="Portal" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Group-36-Copy-4" fill="#FFFFFF">
<path d="M0,7.162 L6,8.877 L6.00036056,9 C6.00036056,10.0543618 6.81623835,10.9181651 7.85109822,10.9945143 L8.00036056,11 C9.10493006,11 10.0003606,10.1045695 10.0003606,9 L10.0003606,9 L10.0003606,8.98076197 L16,7.266 L16.0003606,14 C16.0003606,15.1045695 15.1049301,16 14.0003606,16 L2.00036056,16 C0.895791064,16 0.000360563943,15.1045695 0.000360563943,14 L0,7.162 Z M14.0003606,4 C15.1049301,4 16.0003606,4.8954305 16.0003606,6 L16,6.226 L9.99950581,7.94095939 C9.96827529,6.8636983 9.0851817,6 8.00036056,6 C6.94978154,6 6.08839609,6.81003398 6.00669844,7.83960773 L0,6.122 L0.000360563943,6 C0.000360563943,4.8954305 0.895791064,4 2.00036056,4 L14.0003606,4 Z" id="Combined-Shape"></path>
<rect id="Rectangle" x="7.00036056" y="7" width="2" height="3" rx="1"></rect>
<path d="M10.0003606,0 C11.0547224,0 11.9185257,0.815877791 11.9948748,1.85073766 L12.0003606,2 L12.0003606,4 L10.0003606,4 L10.0003606,2 L6.00036056,2 L6.00036056,4 L4.00036056,4 L4.00036056,2 C4.00036056,0.945638205 4.81623835,0.0818348781 5.85109822,0.00548573643 L6.00036056,0 L10.0003606,0 Z" id="Path-21" fill-rule="nonzero"></path>
</g>
</g>
</svg>'
I have a string named "content" in java which holds any svg file's content that the user uploads. Now my task is to replace the value that is inside this attribute fill="#FFFFFF" with the input that my user has given.
Example : user input : ff0000
so now content string must replace this line <g id="Group-36-Copy-4" fill="#FFFFFF"> as <g id="Group-36-Copy-4" fill="#ff0000">
I am stucked. Please help.
if the fill you mention in the content never change, you can use the replace function.
content = content.replace("#FFFFFF",input)
Reference : https://www.javatpoint.com/java-string-replace
First, your code is not compilable, because you are using single quote which is for character type, you need to use double quotes for your String and escape all internal double quotes:
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg width=\"16px\" height=\"16px\" viewBox=\"0 0 16 16\" version=\"1.1\"xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><!-- Generator: Sketch 64 (93537) - https://sketch.com --><title>Group 36 Copy 4</title><desc>Created with Sketch.</desc><g id=\"Portal\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\"><g id=\"Group-36-Copy-4\" fill=\"#FFFFFF\"><path d=\"M0,7.162 L6,8.877 L6.00036056,9 C6.00036056,10.0543618 6.81623835,10.9181651 7.85109822,10.9945143 L8.00036056,11 C9.10493006,11 10.0003606,10.1045695 10.0003606,9 L10.0003606,9 L10.0003606,8.98076197 L16,7.266 L16.0003606,14 C16.0003606,15.1045695 15.1049301,16 14.0003606,16 L2.00036056,16 C0.895791064,16 0.000360563943,15.1045695 0.000360563943,14 L0,7.162 Z M14.0003606,4 C15.1049301,4 16.0003606,4.8954305 16.0003606,6 L16,6.226 L9.99950581,7.94095939 C9.96827529,6.8636983 9.0851817,6 8.00036056,6 C6.94978154,6 6.08839609,6.81003398 6.00669844,7.83960773 L0,6.122 L0.000360563943,6 C0.000360563943,4.8954305 0.895791064,4 2.00036056,4 L14.0003606,4 Z\" id=\"Combined-Shape\"></path><rect id=\"Rectangle\" x=\"7.00036056\" y=\"7\" width=\"2\" height=\"3\" rx=\"1\"></rect><path d=\"M10.0003606,0 C11.0547224,0 11.9185257,0.815877791 11.9948748,1.85073766 L12.0003606,2 L12.0003606,4 L10.0003606,4 L10.0003606,2 L6.00036056,2 L6.00036056,4 L4.00036056,4 L4.00036056,2 C4.00036056,0.945638205 4.81623835,0.0818348781 5.85109822,0.00548573643 L6.00036056,0 L10.0003606,0 Z\" id=\"Path-21\" fill-rule=\"nonzero\"></path></g></g></svg>";
then you can use String's replace:
content = content.replace("fill=\"#FFFFFF\"", String.format("fill=\"%s\"", replacement));
this, in case you want to replace in the same variable, use a different one otherwise.

Read specific data from XML using Java (DOM)

I want to extrat some data from an invoice (XML) using Java. I'm using the example on this link (https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/)
The problem is my XML doesn't look like the one in the example, here is mine:
<?xml version="1.0" encoding="UTF-8"?>
<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:bfa2="http://www.buzonfiscal.com/ns/addenda/bf/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" NumCtaPago="4007" LugarExpedicion="CUAJIMALPA DE MORELOS,CIUDAD DE MEXICO" metodoDePago="99" tipoDeComprobante="ingreso" total="2490" subTotal="2146.55" fecha="2016-12-14T10:23:08" folio="57318" serie="BT" version="3.2" xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd http://www.buzonfiscal.com/ns/addenda/bf/2 http://www.buzonfiscal.com/schema/xsd/Addenda_BF_v20.xsd">
<cfdi:Emisor nombre="BEST BUY STORES S. DE R.L. DE C.V." rfc="BBS070606D33">
<cfdi:DomicilioFiscal codigoPostal="05348" pais="MEXICO" estado="CIUDAD DE MEXICO" municipio="CUAJIMALPA DE MORELOS" referencia="EDIFICIO CENTURY PLAZA" colonia="SANTA FE CUAJIMALPA" noInterior="PISO 2 OFNA 202 Y 203 P3 Y P4" noExterior="440" calle="AV. SANTA FE" />
<cfdi:ExpedidoEn codigoPostal="05348" pais="MEXICO" estado="CIUDAD DE MEXICO" municipio="CUAJIMALPA DE MORELOS" colonia="SANTA FE" calle="AVENIDA SANTA FE NO. 440 PISO 2 (OFICINA 203 Y 204),PISO 3 Y PISO 4" />
<cfdi:RegimenFiscal Regimen="Regimen General de Ley Personas Morales" />
</cfdi:Emisor>
<cfdi:Receptor nombre="VIALCOMA S.A DE C.V" rfc="VIA8011248W0">
<cfdi:Domicilio codigoPostal="54080" pais="México" estado="Estado de México" municipio="Tlalnepantla de Baz" referencia="VIALCOMA S.A. de C.V." localidad="Tlalnepantla de Baz" colonia="EL MIRADOR" noExterior="107" calle="AV. GUSTAVO BAZ " />
</cfdi:Receptor>
<cfdi:Conceptos>
<cfdi:Concepto importe="2146.55" valorUnitario="2146.55" descripcion="PANASONIC PHONE KX-PRD260MEB" noIdentificacion="000000001000189023" unidad="PZA" cantidad="1" />
</cfdi:Conceptos>
<cfdi:Impuestos totalImpuestosTrasladados="343.45">
<cfdi:Traslados>
<cfdi:Traslado importe="343.45" tasa="16.0" impuesto="IVA" />
</cfdi:Traslados>
</cfdi:Impuestos>
<cfdi:Complemento>
<tfd:TimbreFiscalDigital xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" xsi:schemaLocation="http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigital.xsd" UUID="2e36935c-4948-4f7b-9b29-477546aa2922" version="1.0" />
</cfdi:Complemento>
<cfdi:Addenda>
<bfa2:AddendaBuzonFiscal version="2.0">
<bfa2:Receptor email="" />
<bfa2:TipoDocumento descripcion="Factura" nombreCorto="FAC" />
<bfa2:CFD totalConLetra="Dos mil cuatrocientos noventa pesos 00/100 M.N." fechaEnvio="2016-12-12T10:42:15-06:00" />
<bfa2:Extra valor="02028001014520161212" atributo="numTicket" />
</bfa2:AddendaBuzonFiscal>
</cfdi:Addenda>
</cfdi:Comprobante>
I want to get (print on console) the data on "folio" "serie" and "UUID"
Can someone help me please?
The following should give your desire output.This example is based on DOM parser as you have provide.
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("cfdi:Comprobante");
org.w3c.dom.Node nNode = nList.item(0);
System.out.println("folio: " + ((Element) nNode).getAttribute("folio"));
System.out.println("serie: " + ((Element) nNode).getAttribute("serie"));
NodeList list = doc.getElementsByTagName("cfdi:Complemento");
for (int i = 0; i < 1; i++) {
NodeList child = list.item(i).getChildNodes();
for (int j = 0; j < child.getLength(); j++) {
if (child.item(j).getNodeName().equals("tfd:TimbreFiscalDigital")) {
String uuid = ((Element)(child.item(j))).getAttribute("UUID");
System.out.println("UUID : " + uuid);
}
}
}
console output:
Root element :cfdi:Comprobante
----------------------------
folio: 57318
serie: BT
UUID : 2e36935c-4948-4f7b-9b29-477546aa2922

Remove certain recurring elements in xml

I have a xml and want to remove certain elements from the xml document. Initially I wanted to remove the control characters coming in these elements or completely remove the data in these elements.
My sample payload is as below. I wanted to remove resume/content and comments.
<Jobs>
<candidates>
<address2/>
<application>
<comments><BR />Test emp1711 Newberg St. #4 Oregon, CA 97229 444-123-9752 testcandidate#gmail.com<BR />authorName: Test 1
comment content: <b>To: test test (test.test#yahoo.com)</b><br /><br />From: abc Recruitment Team (test#abc.com)<br /><br />Subject: Tester at abc<br /><br /><TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Verdana" SIZE="12" COLOR="#353A3F" LETTERSPACING="0" KERNING="0">Hello test,</FONT></P></TEXTFORMAT><TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Verdana" SIZE="12" COLOR="#353A3F" LETTERSPACING="0" KERNING="0"></FONT></P></TEXTFORMAT><TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Verdana" SIZE="12" COLOR="#353A3F" LETTERSPACING="0" KERNING="0">Thank you for your interest in our abc opening. </FONT></P></comments>
<disposition>tesr Skills match</disposition>
<eId>xyz</eId>
<gender>Male</gender>
<lastUpdatedDate>1340687163</lastUpdatedDate>
<race>Undefined</race>
<resume>
<content>Test<BR />Human Resources Manager / Business Partner <BR /> portland, Oregon; 4454; <BR /> Phone 020 444456;Mobile 088768999;E-mail test#yahoo.com <BR /></content>
<format>Text</format>
</resume>
<sentDate>1789993473</sentDate>
<source>Linkedin</source>
<sourceType>Import</sourceType>
<veteranStatus>Undefined</veteranStatus>
<workflowState>Offer Accepted</workflowState>
<city>portland</city>
<companyName/>
<country>US</country>
<eId>xyz</eId>
</application>
</candidates>
<candidates>
<address2/>
<application>
<comments><BR />Test emp2711 Newberg St. #4 Oregon, CA 97229 444-123-9752 testcandidate2#gmail.com<BR />authorName: Test 2
</comments>
<disposition>Skills match</disposition>
<eId>xyz</eId>
<gender>female</gender>
<lastUpdatedDate>1340687163</lastUpdatedDate>
<race>Undefined</race>
<resume>
<content>Test<BR />Program Manager / Business Partner <BR /> portland, Oregon; 4454; <BR /> Phone 020 444456;Mobile 088768999;E-mail test#yahoo.com <BR /></content>
<format>Text</format>
</resume>
<sentDate>178444473</sentDate>
<source>Linkedin</source>
<sourceType>Import</sourceType>
<veteranStatus>Undefined</veteranStatus>
<workflowState>Offer Accepted</workflowState>
<city>portland</city>
<companyName/>
<country>US</country>
<eId>xyzabc</eId>`enter code here`
</application>
</candidates>
</Jobs>
Build the XML into a Document using DocumentBuilderFactory and pass it to a function like below: (nodeName would be "comments" etc.)
removeAllNodes(Document doc, String nodeName){
DocumentTraversal t = (DocumentTraversal) doc;
Node root = doc.getDocumentElement();
NodeIterator iterator =
t.createNodeIterator(root, NodeFilter.SHOW_ELEMENT, null, true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
Element e = (Element) n;
if (nodeName.equals(e.getTagName()))
root.removeChild(e);
}
}

Jersey JAXB POST adds a linebreak

I'm trying to post an entity to a webservice, here the code:
EmptyTagWrapper wrap = webResource.get(EmptyTagWrapper.class);
client = Client.create();
client.addFilter(new LoggingFilter(System.out));
webResource = client.resource(MyWebservice.CREATETAGS.getUrl());
ClientResponse clientResponse = webResource.post(ClientResponse.class, wrap);
System.out.println(clientResponse);
If I try to do this manually it works:
http://www.mysite.de/api/tags/?xml=<?xml version="1.0" encoding="UTF-8"?><prestashop xmlns:xlink="http://www.w3.org/1999/xlink"><tag><name>Testtag</name><id_lang>1</id_lang></tag></prestashop>
but if I run my program, I get this error:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<errors>
<error>
<code><![CDATA[127]]></code>
<message><![CDATA[XML error : String could not be parsed as XML
XML length : 0
Original XML : ]]></message>
</error>
</errors>
</prestashop>
I think the reason is the linebreak that is appendet between the URL and the marshaled entity, here the sysout of the post-request:
1 * Client out-bound request
1 > POST http://www.mysite.de/api/tags/?xml=
<?xml version="1.0" encoding="UTF-8"?><prestashop xmlns:xlink="http://www.w3.org/1999/xlink"><tag><name>Testtag</name><id_lang>1</id_lang></tag></prestashop>
1 * Client in-bound response
1 < 500
1 < Execution-Time: 0.006
1 < Server: Apache
1 < Access-Time: 1404134558
1 < Connection: close
1 < Vary: Host
1 < PSWS-Version: 1.5.4.1
1 < Content-Length: 282
1 < Date: Mon, 30 Jun 2014 13:22:38 GMT
1 < Content-Type: text/xml;charset=utf-8
1 < X-Powered-By: PrestaShop Webservice
1 <
Any Ideas how to solve this?
Background
I've got different services and fields which are constructed depending on the entity and the service:
public enum PrestaWebservice {
PRODUCTLINKS("Key1","products"),
FULLPRODUCTLIST("Key1","products?display=["+PrestaProduct.FIELDS+"]"),
CATEGORIESLIST("Key1","categories?display=["+PrestaCategory.FIELDS+"]"),
CUSTOMERSLIST("Key2","customers?display=["+PrestaCustomer.FIELDS+"]"),
TAGSLIST("Key2","tags?display=full"),
EMPTYTAG("Key2","tags?schema=synopsis"),
CREATETAGS("Key2","tags/?xml=");
private final String SHOPADDRESS="http://www.mySite.de/api";
private String key;
private String url;
private PrestaWebservice(String key, String url){
this.key = key;
this.url = url;
}
public String getKey(){
return key;
}
public String getUrl(){
return SHOPADDRESS+"/"+url;
}
}
In your question the URL is being constructed in your own code. You need to example in the following area why the carriage return is being added.
MyWebservice.CREATETAGS.getUrl()
Is there a reason you are send the XML as the value of a query parameter instead of in the body of the HTTP request?

How to get information from nmap XML String(IP,Ports) with parser in java

i'm new in coding , i tried to get informations from XML String generated by NMAP4j
<?xml version="1.0"?>
<?xml-stylesheet href="file:///usr/local/share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 6.01 scan initiated Mon Jan 14 13:56:47 2013 as: /usr/local/bin/nmap --datadir /usr/local/share/nmap -T4 -oX - 192.168.1.1 -->
<nmaprun scanner="nmap" args="/usr/local/bin/nmap --datadir /usr/local/share/nmap -T4 -oX - 192.168.1.1" start="1358168207" startstr="Mon Jan 14 13:56:47 2013" version="6.01" xmloutputversion="1.04">
<scaninfo type="syn" protocol="tcp" numservices="1000" services="1,3-4,..."/>
<verbose level="0"/>
<debugging level="0"/>
<host starttime="1358168207" endtime="1358168209"><status state="up" reason="arp-response"/>
<address addr="192.168.1.1" addrtype="ipv4"/>
<address addr="xxx" addrtype="mac" vendor="yyy"/>
<hostnames>
</hostnames>
<ports><extraports state="closed" count="996">
<extrareasons reason="resets" count="996"/>
</extraports>
<port protocol="tcp" portid="21"><state state="open" reason="syn-ack" reason_ttl="64"/><service name="ftp" method="table" conf="3"/></port>
<port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="64"/><service name="ssh" method="table" conf="3"/></port>
</ports>
<times srtt="36813" rttvar="25229" to="137729"/>
</host>
<runstats><finished time="1358168209" timestr="Mon Jan 14 13:56:49 2013" elapsed="2.48" summary="Nmap done at Mon Jan 14 13:56:49 2013; 1 IP address (1 host up) scanned in 2.48 seconds" exit="success"/><hosts up="1" down="0" total="1"/>
</runstats>
</nmaprun>
i tried this code :
String nmapRun = nmap4j.getOutput() ;
OnePassParser opp = new OnePassParser() ;
NMapRun nmapRun1 = opp.parse( nmapRun, OnePassParser.STRING_INPUT ) ;
but i can't get a solution to have objects and manipulating these obects to get all informations
plz help me to get all working with a simple exemple of code so all can understand
Are you trying to parse an existing file ? If so:
OnePassParser opp = new OnePassParser() ;
NMapRun nmapRun = opp.parse( fileName, OnePassParser.FILE_NAME_INPUT ) ;

Categories