How can I open an mp3 file using Java/Groovy via a URL?

Does anyone have any useful advice/links to information about working with mp3 files in Groovy. I appreciate that this is just the same as working with Java libs, but wanted a simple solution to this problem: I want to load an mp3 via a URL and interrogate it. I'd like to test whether it exists and pull out the title, artist and default image if it's there. Any help appreciated. Thanks. Matt

groovy list spreading

If you run the following Groovy code, the assertion passes def foo(a, b) { a + b } assert 'aaabbb' == foo(['aaa', 'bbb']) This suggests that if a method is called with a List parameter that contains X elements, then the List will be spread and a method with X arguments will be invoked. Of course, this will only happen if there isn't a method defined with a single parameter of type List (or ancestor thereof). I only discovered this quite recently when reading another SO Groovy answer. I'v

JUnit AssertSame fails on object.toString in groovy

I am trying to test the overridden toString() in groovy (I know it is trivial but that is what you get after reading kent beck's TDD book). I assertSame on the expected string and the actual Here is the code block: @Test void testToString(){ def study = new Study(identifier:"default-study", OID:"S_DEFAULTS1", name:"Default Study") def expected = ", name:Default Study, identifier:default-study)" assertSame "Should be equal", expe

Null Pointer Exception Groovy

I'm getting a Null Point Exception, and my Groovy shell is no longer specifying where it is happening. It was saying that there were 3 of them, the first of which occurred at the line scans.each {item -> If you dare...: use( groovy.time.TimeCategory ) { new File( 'C:\\Users\\pro-services\\Documents\\ScanEngineDetailFake.log' ).eachLine { line -> m = line =~ d log = line matcher = (log =~ /\d{2}:\d{2}:\d{2},\d{3}/) matcher.count.times { a = matcher[it] if( a ) {

Groovy creating new map with the existing list

I have a list with values as below : ["HTC Magic":"Tetris.apk", "Motorola Droid Milestone":"TheSims3.apk", "Acer C6":"TheSims3.apk"]; I would like to convert this list to a map which looks like [Tetris.apk:[HTC Magic], TheSims3.apk:[Motorola Droid Milestone, Acer C6]]

Groovy and POI: Can I read/write at the same time?

I'm new to groovy, and I've used the ExcelBuilder code referenced below to iterate through an excel spreadsheet to grab data. Is there an easy to write data as I iterate? For example, row 1 might have data like this (CSV): value1,value2 And after I iterate, I want it to look like this: value1,value2,value3

Groovy: Timeout due to proxy not being set (

I want to use a Groovy script to access a webpage. However I'm behind a proxy. Here's a test script that fails... println "Google page is..." println ''.toURL().text Here's the output... >groovy proxytester.groovy Google page is... Caught: Connection timed out: connect at How do I set proxy server information in Groovy?

Groovy , how to pass in inline variables,i.e ${variable} statement from file?

I have an interesting problem in Groovy. Hope someone can help me. Basically I am using Groovy Sql. I need to select multiple tables in different databases. My second query depends on other query's, for example: "select * from table1-in-db1 where key = ${result-of-other-query1}. Groovy works fine if I hardcode this in the function. However, my problem is the sql is defined in a xml file and after I retriev passed in into the the funciton as a string. it doesn't interperate the inline varialbe

Groovy Why is HashMap#get() in a foreach loop returning null?

For groovy -v: Groovy Version: 1.8.6 JVM: 1.6.0_26 Vendor: Sun Microsystems Inc. OS: Linux: def map = new HashMap() def keyVariable = "a" def valueVariable = "b" map.put("${keyVariable}", valueVariable) for (String key : map.keySet()) { println map.get(key) } This prints null. Could someone explain why Groovy finds the key, but can't find the corresponding value by the same key?

Howto check if first 6 position in received file match on first line or second line in Groovy

I want to check in groovy if the first 6 characters on line 1 or line 2 match the text 'ABCDEFG'. How will I do this in Groovy? def testfile = ''' FEDCBAAVM654321 ABCDEFMVA123456 ''' if ( testfile[0..6].equals("ABCDEF") ) { // First line starts with ABCDEF } if ( testfile.tokenize("\n").get(1)[0..6].equals("ABCDEF") ) { // Second line starts with ABCDEF } It should be something like above or the test may be done in one line if possible.

Groovy how to dump all gradle values used for build

we have a multi-project gradle build in android studio. every now and then we have to change something in it, and usually its only 1 or two lines of code, but its never easy knowing where to put those. I find it quite hard to know which properties exist where so I would love to have something like dump-everything where I could see all properties and their children at the point in time, this would make changes much easier I have found this def void explainMe(it){ //println "Examining $

How do I programatically alter a Groovy/Gradle file in Groovy?

My goal is to alter an Android build.gradle file programatically. I want to add a plugin on a specific line, and then a dependency in a specific dependency-section. My question is does Groovy contain a parser for its own language? How can I easily modify a build.gradle-file (or any Groovy file) programatically?

groovy way to pair each element in a list

Every element should be paired with each other but only once. Given a list A, B, C I want to make the following list of pairs: (A,B), (A,C), (B,C) Similarly for 4 elements A, B, C, D the result should be (A,B), (A,C), (A,D), (B,C), (B,D), (C,D). I tried with eachPermutation, eachCombintation but couldn't find a nice way. It would be a big help if you would tell me what's the matemathical name for this operation.

Read xml values in namespaces/SOAP response using groovy XMLParser

I'm using a groovy file where I used xmlParser to generate XML.Now, I want to get the tag values of the xml. Here is my code def rootnode = new XmlParser().parseText(responseXml); Output <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="" xmlns:SOAP-ENV="" xmlns:xsd="" xmlns:xsi="" xmlns:SOAP-ENC=

Groovy slash operator (Jenkins job-dsl)

We would like to understand a couple of legacy job-dsl scripts but don't know what "slash operator" means in this context (as it cant be division): def command = (shells.first() / command) We have tried to look it up in several Groovy books but only found the trivial solution that it means 'division'.

Getting PID for a process using Groovy

I'm trying to create a method in Groovy to get the Process ID of an application. I'm currently at this stage: String getProcessIdFor(String program) { def buffer = new StringBuffer() Process commandOne = 'ps -A'.execute() Process commandTwo = "grep -m1 '${program}'".execute() Process commandThree = "awk '{print \$1}'".execute() Process process = commandOne | commandTwo | commandThree process.waitForProcessOutput(buffer, buffer) return buffer.toString() } But thi

Groovy vs Groovyc

I am new in Groovy and I do not understand the difference between groovy and groovyc. So if I have this file, hello.groovy println "Hello World" If I run groovy hello.groovy it prints "Hello World" If I run groovyc hello.groovy it generates a .class file and if I then run groovy hello it prints "Hello World" Now coming from ruby, this confuses me. Is groovy a compiled of interpreted language?

Groovy - ActiveMQConnectionFactory ignores serverUrl

I am using Apache ActiveMQ with Groovy. I get my connection with this code: connection = new ActiveMQConnectionFactory(serverUrl).createConnection(); But the parameter serverUrl is ignored. When I use for example an Url that doesn't exists, it just connects to the local Apache MQ. Why is this so? I am using this version of the library: org.apache.activemq:activemq-core:5.7.0 Best regards, Peter

Recreating the if/else in groovy: giving multiple closures arguments to a function

While trying to reinvent the if/else syntax with closures in groovy, I couldn't manage to make it work. I think putting multiple closures outside the parenthesis is not permitted, but it could be something else. If it isn't permitted, how would you reproduce the if/else syntax? This is a thought experiment, so don't tell me about the the inefficiency of this implementation. My code: void ifx(boolean condition, Closure action){ ["${true.toString()}": action].get(condition.toString(), {})()

Groovy Terminate existing pool when all work is done

Alright, brand new to gpars so please forgive me if this has an obvious answer. Here is my scenario. We currently have a piece of our code wrapped in a Thread.start {} block. It does this so it can send messages to an message queue in the background and not block the user request. An issue we have recently ran into with this is for large blocks of work, it is possible for the users to perform another action which would cause this block to execute again. As it is threaded, it is possible for

Groovy implicit spread-dot operator

So, in Groovy, list.elementProp yields the same result as list*.elementProp. Junior members on the team seem to keep using this feature unintentionally. I can't find any reference to this behavior in the Groovy docs. Can anyone point me to such documentation? Edit: The flagged duplicate question pertains to how it works, not where it is documented.

Groovy Gradle ant build file not not available during configuration phase

I can't figure out how to execute ant target in case that ant build.xml file is not available during configuration phase. Because it's a remote resource (Maven Remote Resources Plugin). So basically first I need to get this remote resource like this: configurations { remoteResources } dependencies.remoteResources 'group:my-remote-resource:version' task getRemoteResources(type: Copy) { from(zipTree(configurations.remoteResources.first())) into("$buildDir/remote-resources") /

Groovy Gradle How to Set Output Root Path

My sources are in a folder structure like: mygitroot/myproj/module1/src/main/groovy/com/mypak/module1 mygitroot/myproj/module2/src/main/groovy/com/mypak/module2 mygitroot/myproj/module3/src/main/groovy/com/mypak/module3 Gradle builds the jars in a folder structure like: mygitroot/myproj/build/libs/module1.jar mygitroot/myproj/build/libs/module2.jar mygitroot/myproj/build/libs/module3.jar I want it to output to the default dynamic folder structure, just rooted to a different "nongitroot" fo

groovy if statement returning wrong answer

The above code sorts integers. It was a solution to a problem set for kids in CoderDojo. It correctly sorts a list of integers, however if there is 0 in the list the conditional statement returns true when n < lowest, (when n == 2 and lowest ==0). Below is the output to the console when the code is run. Caught: Assertion failed: assert sortList(odds) == [-6,0,2] | | | | [] false [-6, 2, 0] Assertion failed:

Elasticsearch How to update date field in elasticsearch

I have data in my Elastic index as below : Indexed data as: curl -XPUT 'http://localhost:9200/twitter/tweet/1' -d '{ "user" : "kimchy", "post_date" : "2009-11-15T14:12:12", "message" : "trying out Elasticsearch" }' Mapping obtained using curl -XGET localhost:9200/twitter {"twitter":{"aliases":{},"mappings":{"tweet":{"properties":{"message":{"type":"string"},"post_date":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"user":{"type":"string"}}}},"settin

Groovy get map value for item and return with parenthesis if found else blank

I want to have a lookup list that returns the found value in parenthesis if found or else return blank string. I do not want to use enum. Like this: def grt = { ['mail': 'Scanned Paper', 'digital': 'Digital Things', 'barcode': 'Some Barcode Matter'].get(it) } def s = grt('digital') ? "($grt('digital')" : '' println "Report $s" But I want to do it simpler and eliminate the 'def s' line so that there is some kind of collect on the end of get(it) and it is all on one line. I can do an elvis,

Converting Map to POJO with Jackson, Groovy complains for not having a property

I’m trying to convert a Map from a http response to POJO. The response is {_total=0} In my Pojo, I want to get rid of the underscore so I annotated the field with @JsonProperty. But Groovy complains for not having a _total property Stacktrace org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '{_total=0}' with class 'java.util.LinkedHashMap' to class 'io.toro.linkedin.response.CompanyAdminsResponse' due to: org.codehaus.groovy.runtime.metaclass.MissingPropertyE

Merging two maps with lists inside in Groovy

I am struggling to solve the following task: There are two maps with lists inside: def m1 = [ k1: [ l1: ['s1', 's2']]] def m2 = [ k1: [ l1: ['s3', 's4']]] As a result I want to have single map with lists added together. assert merge(m1, m2) == [ k1: [ l1: ['s1', 's2', 's3', 's4']]] In practice the maps are much bigger but idea is the same. Can anyone help?

How to replace string in Groovy

I have some string like C:\dev\deploy_test.log I want by means of Groovy to convert string to C:/dev/deploy_test.log I try to perform it with command Change_1 = Log_file_1.replaceAll('\','/'); It doesn't convert this string

Generating MD5 of a file inputstream in groovy

I am trying to generate md5 of a file inputstream but I'm noticing that the generated md5 is different than the one generated from running command line md5 against the file on disk. Is this correct way to generate md5? DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance('MD5')) println "MD5 generated from Groovy: " + dis.getMessageDigest().digest().encodeHex().toString()

Groovy Can't extract data from RESTClient response

I am writing my first Groovy script, where I am calling a REST API. I have the following call: def client = new RESTClient( 'http://myServer:9000/api/resources/?format=json' ) That returns: [[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]] I am trying to get the field level, like this: def level_value = client.get( path : 'msr/data/level' ) However, when I print the value of the variable obtained: println level_value.getData(

Accessing variable outside of a closure in Groovy

Is there a way, i can access a variable outside the closure. The closure here is a stage in the Jenkinsfile. So, the snippet looks like this: node('pool'){ try{ stage('init'){ def list = [] //some code to create the list } stage('deploy'){ //use the list create in the above stage/closure } } catch(err){ //some mail step } } With this code, i cannot access the list which was created in the first stage/closure. How can i set to get this newly crea

Groovy Selenide test not able to load correct element on a newly opened tab/window

I am using Selenide to open a sample input form on (found here). The test inputs a name into the form and clicks submit, which then opens a new page in a separate tab/window which displays the request params in a div. The following is my test code: import com.codeborne.selenide.Configuration import org.openqa.grid.internal.utils.configuration.StandaloneConfiguration import org.openqa.selenium.remote.server.SeleniumServer import spock.lang.Specification import static com.cod

GroovyScript Name Generator

I'm using READYAPI! for testing purposes. I'm currently at a road block. Is there a way to use a Groovy Script to Generate Random American Names? I've done some research online and I don't see anyway to do this with Groovy Script. This is the closes I've come to:

How to download a JAR file from a URL using Groovy?

I have a JAR artifact in my nexus repository and I want to download it using Groovy script. I tired this but it doesn't work: new File("/dir/to/save/app.jar").withOutputStream { out -> new URL('').eachByte { b -> out.write(b) } But the same scripts works perfectly when I download something from Maven central repository. What could be the issue? Is there any SSL certificate issue with my nexus that is causing the download to

Groovy - how to Decode a base 64 string and save it to a pdf/doc in local directory

Question I need help with decoding a base 64 string and saving it to a pdf/doc in local directory using groovy This script should work in SOAP UI The base64 string is 52854 characters long I have tried the following File f = new File("c:\\document1.doc") FileOutputStream out = null byte[] b1 = Base64.decodeBase64(base64doccontent); out = new FileOutputStream(f) try { out.write(b1) } finally { out.close() } But - it gives me below error No signature of method: static org.apache.

Groovy StreamingTemplateEngine exception MissingPropertyException

How to avoid occurrence MissingPropertyException at absence of parameters from a template in Map and to replace not found values by null? import groovy.text.StreamingTemplateEngine import groovy.text.Template class Test { private static Writable binding(Map map, String string) { Template template = new StreamingTemplateEngine().createTemplate(string) return template.make(map) } static void main(String... args) { def template = "\${test1} \${test2}"

Best way to find the required file with path list in the directory in groovy

I need to fetch the files which matches with the file name in the given directory Suggest me the best way to fetch the matched list with the actual path of the files. The result should be a list String directory = "/home/xxx/yyy" File currentDir = new File(directory) final String expectedFile = "expectedFile.txt"; currentDir.eachFileRecurse(FileType.FILES) { if( { println it } }

Read values from xlsx file using Groovy script in SoapUI

I use following script to read values from xlsx file: import; import; import java.util.Iterator; import; import; import; import; import; String filepath = "D:\\testdata\\TestData.xlsx" String sheetName = "Sheet1" FileInputStream fis = new FileInputStream(new File(filepath)) Workb

Groovy On gremlin console, why predicate 'eq' returning false inside 'is' while direct comparison returns true?

On gremlin version 3.4.0 with step is, the predicates are not working as expected. if I do the following it is returning me true gremlin> ==>true gremlin>[3].getAt(0).is(3) ==>true While the same comparisons with using predicates are not working and returns false gremlin> ==>false gremlin>[3].getAt(0).is(eq(3)) ==>false Precisely I want to check the length of the node property value and validate based on a max length. gremlin>g.V(0).values('n

Groovy SpockExecutionException: Data provider has no data

I've done a bunch of searching and, while I've found a few hits, like Why does Spock think my Data Provider has no data?, none of them seem to be very helpful. I've only done a data provider a couple of times, but it seems perfect for this. I have the following static method: static List<ContactPointType> getAddressTypes() { List<ContactPointType> result = new ArrayList<>(); for (ContactPointType cpType : ContactPointType.values()) { if (cpType.toString().end

Groovy How to use JMeter Properties in IF controller and While Controller

I am setting the JMeter properties using JSR223 outside of WHILE controller like this - if(jsonResponse.currentStatus == "Received") { props.put("pollCount", 0); def requestId =; props.put("requestId", requestId); props.put("currentStatus",jsonResponse.currentStatus); } Then I am accessing these properties within "WHILE" Controller like this- ((("${__groovy(props.get('currentStatus'))}" == "Received") || ("${__groovy(props.get('currentStatus'))}" == "Pro

loop find pattern in map - groovy

I want to loop through a map so if regex condition/pattern is met I will put the value into another map, else I will put in the map {trigger-all=true}. This is what I got so far : def patternsFunc = [ /(?s).*vee\/.*/ : "vee", /(?s).*$HelmServicesPath\/vee\/.*/ : "vee", /(?s).*rest\/.*/ : "rest", /(?s).*$HelmServicesPath\/rest\/.*/ : "rest", /(?s).*service\/.*/ : "service", /(?s).*$HelmServicesPath\/service\/.*/ : "service", ] patternsFunc

Groovy How to use siblings() and closest() in Geb test

I am trying to write a script to click an icon which is a part of the table header. Each column in the table has this icon in it (ascending order and descending order sorting icons). I am using Geb to do this. Here is how I am trying to do it: In my SortingSpec.groovy file: header.closest("div.customSortDownLabel").click() I also tried header.siblings('div.customSortDownLabel').first().click() In the SortingPage.groovy file: header { grid.$(class: 'div.customHeaderLabel', text: 'Cou

How to use multiple groupBy and max in Groovy

I am trying to use the Groovy groupBy and max methods to summarise data in my list. So far I have created a class named allowance which I use to build a list of allowances e.g. class allowance { Integer StartDate Integer EndDate String PayCode Integer CreatedOn } def lAllowances = [ new allowance(StartDate: 20200330, EndDate: 99991231, PayCode: "PC_DFB1", CreatedOn: 20200330) ,new allowance(StartDate: 20200330, EndDate: 99991231, PayCode: "PC_DFB1", CreatedOn:

  1    2   3   4   5   6  ... 下一页 最后一页 共 32 页