I first save a txt file using http.get:
http.get(path: path,
contentType: TEXT,
query: [id:dapId, instance:alias, format:'xml', file:portalFile]) {resp, reader ->
println "response status: ${resp.statusLine}"
println 'Headers: -----------'
resp.headers.each { h ->
println " ${h.name} : ${h.value}"
}
new File(outputFileName).withWriter{out -> out << reader}
}
And then use the newly created file in outputFileName in XmlSlurper().parse, as below:
def inputFile = new File(outputFileName)
def domain = new XmlSlurper().parse(inputFile)
But I get an error when doing new XmlSlurper().parse(inputFile):
Caught: org.xml.sax.SAXParseException: White spaces are required between publicId and systemId.
I noticed that the textfile outputFileName which is being created with http.get seems to be an HTML file and not an XML file. So I copied and pasted the XML code which it is supposed to contain into outputFileName, skipped the first part of the code and only ran the XmlSlurper().parse() bit and it worked.
Is outputFileName supposed to be an xml file? It has lots of HTML tags.
Thanks in advance! :D
HTML != XML. Your HTML file probably is not valid XML. Therefore, the XML parser fails during parsing. Are you sure that the file created from the http GET is a valid XML file?
Related
I have a requirement of reading multiple tags in an XML recursively. I have written this code in ODI in Groovy, which does not give any errors but also does not give any output. It is supposed to insert 2 rows into my db looking at the xml, but it does no inserts. Seems like a problem with the hierarchy of tags. Please help me out here.
xml file:
enter image description here
groovy code:
File SFDCResponseFile = new File("/drxe2o/admin/Integration/odi/reference_data/sfdc/copy_center/Sample.xml")
if (!SFDCResponseFile?.exists()) {
throw new RuntimeException("No SFDC Query Response file ${SFDCResponseFile.absolutePath}")
}
def myCon = odiRef.getJDBCConnection("SRC")
def myStmt = myCon.createStatement()
def slurper = new XmlSlurper().parse(SFDCResponseFile)
slurper.queryResponse.result.records.each
{
myStmt.executeUpdate("INSERT INTO <%=odiRef.getSchemaNameDefaultPSchema("LS_ODI_WORK","D")%>.RX_ODI_TAGVALUE_TEMP " +
"(EVENT_CODE,EVENT_EDITION,ORDER_SUMMARY_NUMBER) " +
"VALUES ('${it.Event_Code__c.text()}','${it.Event_Edition__c.text()}','${it.Order_Summary_Number__c.text()}')")
}
In extension to this question.
Is it possible to read a file into a string without knowing the path to the file? - I only have the file as a 'def'/type-less parameter, which is why I can't just do a .getAbsolutePath()
To elaborate on this, this is how I import the file (which is from a temporary .jar file)
def getExportInfo(path) {
def zipFile = new java.util.zip.ZipFile(new File(path))
zipFile.entries().each { entry ->
def name = entry.name
if (!entry.directory && name == "ExportInfo") {
return entry
}
}
}
A ZipEntry is not a file, but a ZipEntry.
Those have almost nothing in common.
With def is = zipFile.getInputStream(entry) you get the input stream to the zip entry contents.
Then you can use is.text to get the contents as String in the default platform encoding or is.getText('<theFilesEncoding>') to get the contents as String in the specified encoding, exactly the same as you can do on a File object.
There is no problem to save response sheet to file. Smth like
def xmlFile = "C:/.../Try.xml"
def response = context.expand( '${Request#Response}' )
def f = new File(xmlFile)
f.write(response, "UTF-8")
BUT.
I re-run my request in groovy script with new parameters (using while), and I need to ADD info to result file, not to re-write it. Now it's just re-writing each time:(. File created outside the cycle.
Thanks in advance,
Dmitry
straight from the ref-doc
new File('TestFile1.txt').withWriterAppend( 'UTF-8' ){ w->
w << 'abcdefghij'
}
Hi I need to create a XML file in groovy using MarkupBuilder class, the xml file should have encoding utf-8 without BOM.
This is my code that generate a markupbuilder and add a encoding
def textXML = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(textXML)
builder.setDoubleQuotes(false)
builder.setOmitNullAttributes(true)
builder.setOmitEmptyAttributes(true)
builder.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
//some more code
This code creates the xml file
def file = new File("fileXml.xml")
file << textXML
But the generate xml is always with encoding utf-8 with BOM
How solve this?
Thanks!
the UTF-8 BOM (Byte Order Marker) is always the first three bytes of the file. You can simply remove them.
I would do something like this:
def textXML = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(textXML)
builder.setDoubleQuotes(false)
builder.setOmitNullAttributes(true)
builder.setOmitEmptyAttributes(true)
builder.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
def xmlbytes = textXML.toString().getBytes().flatten()
xmlbytes.remove(0)
xmlbytes.remove(0)
xmlbytes.remove(0)
def file = new File("fileXml.xml")
file << xmlbytes
That's how I'd do it. Pardon the java-ness of my Groovy -- old habits die hard.
So my situation is slightly different. I'm trying to write an XML using MarkupBuilder and have the BOM appear (new customer requirement). So far, everything I try yields just a plain text XML file with no BOM. Here's my sample code:
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def xml = new MarkupBuilder( writer )
xml.setDoubleQuotes(false)
xml.setOmitNullAttributes(true)
xml.setOmitEmptyAttributes(true)
xml.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
xml.quote() {
xml.quote_details() {
xml.detail() {
xml.quoteId('Q1339', type:'FCL')
}
}
}
new FileOutputStream('UTF_test.xml').withWriter('UTF-8') { w ->
w.write('ABC')
w << writer
}
The "ABC" will show up in the file, but no BOM. My backup plan is to just export the characters myself, but this seems less elegant.
I am new to Groovy and I am trying to parse both a valid rest resource and an invalid one.
For example:
this code works fine -
def entity = new XmlSlurper().parse('http://api.twitter.com/1/users/show/slashdot.xml')
println entity.name()
println entity.screen_name.text()
when I run it, I get output:
user
slashdot
but when I pass an invalid url to xmlSlurper, like this
def entity = new XmlSlurper().parse('http://api.twitter.com/1/users/show/slashdotabc.xml')
println entity.name()
println entity.screen_name.text(
)
I get this error message:
Caught: java.io.FileNotFoundException: http://api.twitter.com/1/users/show/slashdotabc.xml
at xmltest.run(xmltest.groovy:1)
Although the url returns an hash code (like below) with an error message which I would like to parse and display it.
<hash>
<request>/1/users/show/slashdotabc.xml</request>
<error>Not found</error>
</hash>
How can I parse a url which returns a 404 but with error information?
Any help will be appreciated.
--
Thanks & Regards,
Frank Covert
The response you want to see is available on the URL connection's errorStream instead of the inputStream. Fortunately, given the InputStream, XmlSlurper.parse can read an InputStream as well.
Here's a sample to switch to reading the errorStream when you don't get a 200 status:
def con = new URL("http://api.twitter.com/1/users/show/slashdotaxxxbc.xml").openConnection()
def xml = new XmlSlurper().parse(con.responseCode == 200 ? con.inputStream : con.errorStream)