groovy,xml-parsing , Read specific content of POM xml file through groovy xmlSurper and download dependecy

Read specific content of POM xml file through groovy xmlSurper and download dependecy


Tag: groovy,xml-parsing

I have a below POM file.I want to use xmlSlurper groovy code to read the specific content of the POM file Can someone tell me how to write the code to read the specific content through groovy xmlSlurper.I want to read the groupid artifact id,classifier and type of those whose scope is runtime in below POM file.

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="" xmlns=""
  <description>Configuration Management Gradle Plugin</description>


Below is the script which I am using to read the contents of POM file and download the dependency whose scope is runtime from the artifactory.

apply plugin: 'java'

// ------ Tell the script to get dependencies from artifactory ------
    repositories {
         maven {
        url ""

    buildscript {
    repositories {
      maven {
        url ""
    // ------ Tell the script to get dependencies from artifactory ------
    dependencies {
    classpath ([ "" ])

apply plugin: ''

 * The folloing -D parameters are required to run this task
 *  - deployLayer = one of acceptance, latest, production, test
// Read the properties file and take the value as per the environment.
if(! throw new Exception ("deployLayer must be set")
def thePropFile = file("config/${}.properties")
if(!thePropFile.exists()) throw new Exception("Cannot load the specified environment properties from ${thePropFile}")
println "Deploying ${}.${} to ${}"

// load the deploy properties from the file
def deployProperties = new Properties()
thePropFile.withInputStream { 
    stream -> deployProperties.load(stream) 
// set them in the build environment
project.ext {
  deployProps = deployProperties
  deployRoot = deployProperties["${}.deployroot"]
  deploydir = deployProperties["${}.deploydir"]
  deployFolder = deployProperties["${}.foldername"]
  deployPostInstallSteps = deployProperties["${}.postInstallSteps"]

task deleteGraphicsAssets(type: Delete, dependsOn: deploy) {
    def dirName = "${deployRoot}"
    delete dirName

    doLast {

task downloaddependecies(dependsOn: deleteGraphicsAssets) << {
  def pomFile = file("${buildDir}/artifacts").listFiles().find { 'pom' }
  def pomXml = new XmlSlurper().parse(pomFile.absolutePath)
  def pomDependencies = pomXml.dependencies.dependency
  Configuration configuration = project.configurations.detachedConfiguration()
  configuration.transitive = false
  pomDependencies.each { dependency ->
    if(dependency.scope == 'runtime') {
    def dependencySpec = dependencies.create("${dependency.groupId}:${dependency.artifactId}:${dependency.version}:${dependency.classifier}@${dependency.type}")
      println "Found Runtime Dependency: ${dependencySpec}"
                println "RESOLVED THE FOLLOWING"
                configuration.resolvedConfiguration.firstLevelModuleDependencies.each { println it }
                copy {
                  from configuration
    into ( "${buildDir}/artifacts" )

task copyartifactZip << {
    copy {
        from "${deployRoot}"
        into "${deploydir}/"

task copyLicenseZip << {
    copy {
        from "${deployRoot}"
        into "${deploydir}/${deployFolder}"

task myCustomTask(dependsOn: downloaddependecies) << {
    copy {
        from 'deploymentfiles'
        into "${deployRoot}"
task unzipArtifact(dependsOn: myCustomTask) << {
  def theZip = file("${buildDir}/artifacts").listFiles().find {'.zip') }
  println "Unzipping ${theZip} the artifact to: ${deployRoot}"
  ant.unzip(src: theZip, dest: "${deployRoot}", overwrite: true)

task setPerms(type:Exec, dependsOn: unzipArtifact) {
  workingDir "${deployRoot}"
  executable "bash"
  args "-c", "chmod -fR 755 *"

def dirName = "${deploydir}/${deployFolder}"
task zipDeployment(type: GradleBuild, dependsOn: setPerms) { GradleBuild gBuild ->
    def env = System.getenv()
    def jobName=env['jobName']
if (jobName.equals("LicenseGenerator")) {
    delete dirName
    gBuild.tasks = ['copyLicenseZip']
    } else {
   gBuild.tasks = ['copyartifactZip']

task deployAll(dependsOn: zipDeployment){}


Spock Framework: problems with spying

I have an issue with using Spy in Spock, it either doesn't work as it should or my understanding is wrong so I'm trying to clarify this. Consider this code (Java): public class CallingClass { public String functionOne() { //does stuff return "one"; } public String functionTwo() { String one...

Get attibuteDict of a subclass Xml parsing - Swift

I want to get attribute of a subclass of my item : <pdv id="1000002" latitude="4621842" longitude="522767" cp="01000" pop="R"> <adresse>16 Avenue de Marboz</adresse> <ville>BOURG-EN-BRESSE</ville> <ouverture debut="01:00" fin="01:00" saufjour=""/> <services> <service>Automate CB</service> <service>Vente de gaz domestique</service> </services> <prix nom="Gazole" id="1" maj="2015-05-30 11:30:17" valeur="1206"/> <prix nom="SP95" id="2" maj="2015-05-30 11:30:17"...

Selecting inner text of XML nodes and adding to list

I have the following XML file called file.xml: <?xml version="1.0"?> <cache-config xmlns:xsi="" xmlns=""> <defaults> <serializer>pof</serializer> </defaults> <caching-scheme-mapping> <cache-mapping> <cache-name>broadcast-data|position</cache-name> <scheme-name>broadcast</scheme-name> </cache-mapping> <cache-mapping>...

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)

I'm trying to set a cron Scheduled annotation as follows: @Scheduled(cron = "#{systemEnvironment['db_cron']}") def void schedule() { } Next set the environment variable as: export db_cron="0 19 21 * * *" However, I get the runtime error: Cron expression must consist of 6 fields (found 1 in "#{systemEnvironment['db_cron']}") What can...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types

While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

Parsing a xml file in afnetworking and retrieve data doesn't work

With this url I tried but it doesn't work. Can someone help me to give simple xml parsing code and retrive data from this url? I tried but only reached at NSData * data1 = (NSData *)responseObject; NSString *fetchedXML = [NSString stringWithUTF8String:[data1 bytes]]; NSLog(@" xml data :: %@", fetchedXML);...

String parsing with batch scripting

I have a file called pictures.xml and it contains some pictures information like: <ResourcePicture Name="a.jpg"> <GeneratedPicture Name="b.jpg"/> <GeneratedPicture Name="c.jpg"/> </ResourcePicture> <ResourcePicture Name="z1.jpg"> <GeneratedPicture Name="z2.jpg"/> <GeneratedPicture Name="z3.jpg"/> <GeneratedPicture Name="z4.jpg"/> </ResourcePicture> What I want do do is to get each line in for loop and print the names of the pictures. Sample...

Chaining Null-Safe Operator

My project has code like the following: params.stringValue?.trim().replaceAll('aa', 'a') We expected that if params.stringValue was null, that both trim() and replaceAll() would not be called. However we were getting a NullPointerException on this line saying that replaceAll() cannot be called on a null Object. We had to change the code...

Get just content of soap response in Groovy

I have following soap response: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="" xmlns:xsi="" xmlns:xsd=""> <soap:Body> <GetHTMLResponse xmlns="http://www.webserviceX.NET"> <GetHTMLResult> TEST </GetHTMLResult> </GetHTMLResponse> </soap:Body> </soap:Envelope> Now I want a method which deliverys me this xml: <root> <GetHTMLResponse...

Model to LazyMap

How do I convert/deserialize these models public class AccessCredentials { String userName = '' String password = '' LoginOptions loginOptions = new LoginOptions() } public class LoginOptions { String partnerId = '' String applicationId = '' } into a LazyMap like : [ userName : userName, password : password, loginOptions...

Unable to construct Document object from xml string

I have xml string coming to my appliaction like follows <?xml version="1.0" encoding="UTF-8"?><loc:getLocation xmlns:loc=""> <loc:address>tel:+919420161525</loc:address> <loc:requestedAccuracy>500</loc:requestedAccuracy> <loc:acceptableAccuracy>500</loc:acceptableAccuracy> </loc:getLocation> I want to construct Document object from this so that using XPath, I can retrieve required data. I tried following code...

list of test step results in groovy script

I'm trying to figure out a way to get a list of (names) of just the failed test steps, currently the below code is giving me all the names def TestCase = testRunner.getTestCase() def StepList = TestCase.getTestStepList() StepList.each { ( } Now I'm not sure how to move on...

using classes in jenkins job dsl

Hi all I have a problem and I can't seem to figure it out. So I'm creating some helper classes for my dsl to use, but it just does not seem to execute any method within these classes. I have created a job with the following dsl in it: class...

Why is getElementsByTagName() not working for me?

I am trying to get info from the OMDb API. I found some code but it's not working right: $loc = ''.$lookup_title.'&r=xml'; $dom = new DOMDocument(); $dom->load($loc); foreach ($dom->getElementsByTagName('movie') as $e) { $imdb = $e->getElementsByTagName('imdbID')->item(0)->textContent; $year = $e->getElementsByTagName('year')->item(0)->textContent; $plot = $e->getElementsByTagName('plot')->item(0)->textContent; $poster =...

Why does DriverManager.getConnection() lookup fail in GroovyConsole?

The following Groovy script works correctly from the command line. (I successfully get a Connection.) // ---- jdbc_test.groovy import java.sql.* Class.forName("com.mysql.jdbc.Driver") def con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "password") println con > groovy -cp lib\mysql-connector-java-5.1.25-bin.jar script\jdbc_test.groovy [email protected] But if the same script is loaded into GroovyConsole (2.4.3) and run - after...

Spock's @Narrative and @Title annotations

Spock provides @Narrative and @Title annotations that you can use to provide a class-level description of your test, e.g. @Narrative('description of spec') @Title('title of spec') class ExampleSpec extends Specification { // tests omitted } What is the difference between these two? In other words, why do we need both of...

How to populate a treeview from a XML file with multiple child nodes?

I´m trying to populate a TreeView component in VB.NET from a XML file. It´s a large XML file and I chopped it up in order to give you guys an idea about how it is structured. I´m new to VB.NET so I´m having a hard time to figure this out....

Groovy - timestamp from minutes

I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

Why isn't split working here?

I'm trying to take a filename that's being passed from a tsv and split it into an array, like so: new File("filenames.tsv").eachLine( { String file_iter -> println file_iter def details = file_iter.split(".") println details }) The output of the printlns: stad.all.16jan15.TP.pwpv [] Why is the array empty? I'm sure I'm...

comparing a string from an xml file how?

I am new to this and breaking my head about it, well I got an XML file like : <?xml version="1.0" encoding="utf-8"?> <configuration> <Client> <add key="City" value="Amsterdam" /> <add key="Street" value="CoolSingel" /> <add key="PostalNr" value="1012AA" /> <add key="CountryCode" value="NL" /> I'm trying to read and compare a value from an...

XElement.Value is stripping XML tags from content

I have the following XML: <Message> <Identification>c387e36a-0d79-405a-745c-7fc3e1aa8160</Identification> <SerializedContent> {"Identification":"81d090ca-b913-4f15-854d-059055cc49ff","LogType":0,"LogContent":"{\"EntitiesChanges\":\" <audit> <username>acfc</username> <date>2015-06-04T15:15:34.7979485-03:00</date> <entities> <entity> <properties> <property> <name>DepId</name> <current>2</current> </property>...

Groovy: run SQL SELECT LIKE from file with params

The groovy code is import groovy.sql.* dbUrl = 'jdbc:sqlserver://server' dbUser = 'username' dbPassword = 'password' dbDriver = '' sql = Sql.newInstance(dbUrl, dbUser, dbPassword, dbDriver) def sqlfromfile = new SqlFromFile() sqlfromfile.sql_filename='select_query.sql' try{ def result = sql.rows(sqlfromfile.result,[id:'01']) println result }catch(e){ println e } class SqlFromFile { def sql_filename def read(){ result=...

How does the Groovy compiler work?

Can anyone explain the Groovy compiler works? Does it compile: Groovy code -> Java code -> Bytecode Groovy code -> Bytecode Some other method ...

sonar maven analysis only picks .java file

I am trying to run a sonar maven analysis on my multilanguage project which contains many languages like *.java, *.groovy, *.js etc. I have installed all the languages plugin in my sonar and configured my pom sonar.sources parameter as src/main,src/test but still it picks up only java files. In the...

Error:(1) Error parsing XML: not well-formed (invalid token)

On right clicking the error "Error:(1) Error parsing XML: not well-formed (invalid token)" and then jump to source it opens the following activity_main.xml. I am not able to figure the error out <FrameLayout xmlns:android="" xmlns:tools="" android:id="@+id/container" tools:context="" android:layout_width="match_parent" android:layout_height="match_parent" tools:ignore="MergeRootFrame"/> Andoridmanifest.xml <?xml...

PHP: Converting xml to array

I have an xml string. That xml string has to be converted into PHP array in order to be processed by other parts of software my team is working on. For xml -> array conversion i'm using something like this: if(get_class($xmlString) != 'SimpleXMLElement') { $xml = simplexml_load_string($xmlString); } if(!$xml) {...

Selection skipping node on missing childnode

Here is my XML file: <?xml version="1.0" encoding="iso-8859-1" ?> <data> <metadata> <sector>weather</sector> <title>sourceTitle</title> </metadata> <weather> <countries> <country code="AU" name="Australia" region="Oceania"> <location type="APLOC" code="6700" name="Addington" state="VIC" postcode="3352"> <point_forecasts type="TWC"> <related_location type="TWCID" code="9508" name="Ballarat" state="VIC"> </related_location> <point_forecast...

groovy/XML: Replace a node by another one

I try to replace an XML node by another one by using XmlSlurper (or XmlParser). The original XML: <myXml> ... <myNode> <Name>name1</Name> <Name>name2</Name> <Name>name3</Name> </myNode> ... </myXml> The list that contains the items to build my new node def namelist = ['name4','name5','name6','name7'] What I want to have <myXml> ... <myNode>...

Get nth child node without knowing node name Groovy

I have xml like this: <node1> <node2> <node3> <node4> <node5> <node6> </node6> <node7> </node7> </node5> </node4> </node3> </node2> </node1> How can I get the name of the 6th node - assuming I don't know the node's name is "node6"? I currently have: def text = <xml from above> def list...

Create XML file by iterating over lists in python

I have checked this link but it doesnt solved my problem. I have 2 lists: a = [['txt','stxt','pi','min','max'],['txt1','stxt1','pi1','min1','max1']] b = [[0.45,1.23],[[0.75,1.53]] for l1 in a: for l2 in b: root = ET.Element("Class ",name = l1[0]) doc = ET.SubElement(root, "subclass" , name = l1[1]) ET.SubElement(doc, l1[4], min = str(l2 [0]),max =...

Call function from a custom file with parameters

How to call a function from a custom external file and also to be able to have parameters? The external file is an XML file. The tags looks like this: <menu name="bar"> <option func="boo">Execute Me</option> <option func="foo" params="a, b, c, d">I want parameters</option> </menu> I want execute a function defined...

Confused about the invokeMethod method in the Groovy MOP

First look at the following Groovy code: class Car { def check() { System.out.println "check called..." } def start() { System.out.println "start called..." } } Car.metaClass.invokeMethod = { String name, args -> System.out.print("Call to $name intercepted... ") if (name != 'check') { System.out.print("running filter... ") Car.metaClass.getMetaMethod('check').invoke(delegate, null) } def validMethod...

passing base64 image string in xml tag

I tried this code, but it is not working. Any suggestions or any solutions for above issue for sending base64 string in xml tag. I have searching lot of about base64 string passing to java server using this xml tags(i.e. xml parsing) but not get any results. function fileSelectedForLogo() {...

set an annotation attribute from an environment variable?

I'm trying to set an annotation value from an environment variable: @Configuration @ComponentScan @EnableAutoConfiguration @EnableScheduling class Application { @Scheduled(cron = "${DB_CRON}") def void schedule() { ... } public static void main(String... args) {, args) } ... } However, I get the following compile time error: Attribute 'cron' should have...

How to merge two different paths in a XML file?

This is my xml file: <File> <Paths> <Path> <Node> <NodeName>Initial_Node</NodeName> <InnerNode> <Signal>Test_sig</Signal> <InnerNode> <Signal>Test_sig_1</Signal> <NodeRef>Ref0</NodeRef> </InnerNode> </InnerNode> </Node> </Path> <Path> <Node> <NodeName>Name1</NodeName> <InnerNode> <Signal>Test_sig_0</Signal> <InnerNode> <Signal>Test_sig_2</Signal>...

How to get testStep responseAsXml in groovyScript

Concerning soapUI and groovy, I'm trying to get assertion (working) and response both in XML into a variable. I get the error groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep.getResponseAsXml() is applicable for argument types: () values: [] error at line: 6 I have tried adding import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep but still cant figure...

create email list of all users

On occasion I need to email all Jenkins users, for example warning them Jenkins will be offline for maintenance. The script below gives me email addresses for all people that Jenkins knows about, but it includes people that don’t have accounts, these are people that have committed changes that triggered...

Decode base64 image in Grails [duplicate]

This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

Parse XML with Linq with multiple child elements

This is my first question on SO, please let me know if I am doing anything wrong! I am trying to parse an XML similar to this: <LiveUpdate> <CityID>F0A21EA2</CityID> <CityName>CityTown</CityName> <UserName>john</UserName> <ApplicationDetails> <ApplicationDetail Application="AC" Licensed="true" Version="2015.2" Patch="0001" /> <ApplicationDetail Application="AP" Licensed="true" Version="2015.2" Patch="0002" /> </ApplicationDetails> </LiveUpdate> I have classes that...

How to parse comment from XML with XMLEventReader?

I am parsing an incoming XML file with an XMLInputFactory like the following. How do I get the text out of an XML comment? I know how to detect it, but, not get the text out XMLInputFactory inputFactory = XMLInputFactory.newInstance(); FileInputStream fis = new FileInputStream(incomingFile); XMLEventReader eventReader = inputFactory.createXMLEventReader(fis); while...

xml parsing error (xpath, HTMLagilitypack)

I am trying to parse an xml. All nodes have opening and closing tags except one node that in some lines in only has this tag: <persons/> In most of the time it appears like this: <persons> ... </persons> I cannot get values from the xml when this node is...

Special Groovy magic re property access and collections / iterables?

I understand what is happening here with the spread operator *. in Groovy (2.4.3): [].class.methods*.name => [add, add, remove, remove, get, ... But why does the leaving the * out produce the same results? [] => [add, add, remove, remove, get, ... I'd have expected that to be interpreted as...

How to print a result from multiple root elements in XML using Perl

I'm starting out with Perl and doing all the bad things you can with the language. This program is using XML::Simple and Regular Expressions which the internet says do not do unless you hate yourself. Ok, the plan is to read an XML file from a website and read off...

Restrict allowed httpMethods using enum

I am creating connectors for REST API methods. Some methods has the same method name but performs different HTTP methods. For example, createEntity( HttpMethod httpMethod, CreateEntity model ) can perform POST and GET only. What I want is to have an error when httpMethod is supplied with PUT or DELETE....

Python XPath include missing elements

<tree> <item> <element1>somedata</element1> <element2>moredata</element2> <element3>data?</element3> <optional_element>data!</optional_element> </item> <item> <element1>somedata</element1> <element2>moredata</element2> <element3>data?</element3> </item> <item> <element1>somedata</element1> <element2>moredata</element2> <element3>data?</element3>...

Parsing android resources from xml

I am facing some problems with parsing a XML-file for my Android App. I need some layout ids and color ids from my XML file. I have no problems in reading string values but I dont know how to convert the XML layout reference to a layout id? Thanks for...

gremlin outputs different from as seen on the internet, I think in bytes

How to get gremlin output normal indices along with v Currently it outputs something like this gremlin> g.V WARN com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx - Query requires iterating over all vertices [()]. For better performance, use indexes gremlin> juno = g.addVertex(null); ==>v[128824] gremlin> june = g.addVertex(null); ==>v[128828] gremlin> jape = g.addVertex(null); ==>v[128832] But as...

Write Spock test cases for Spring boot application

I am working on spring boot application. I have to write test cases for it. I haven't written test cases before, so someone suggested using spock framework for it. I explored spock and i think it is more related to groovy language. Can i write spock test cases for my...

Class fields as method parameters

My method needs to be strictly typed. If possible, I wanted to save some line of codes, setting the model properties from the parameter input by putting the model properties setter directly at the function definition. The current working code: class Connector { static def entityQuery( String httpMethod, String typeName,...