groovy,closures,fluent,method-chaining , Fluent Groovy syntax using command chaining and maps


Fluent Groovy syntax using command chaining and maps

Question:

Tag: groovy,closures,fluent,method-chaining

Given the following Groovy code:

someMap = ['key':{ str -> println "SUCCESS: ${str}" }]
clos = { someMap }

All of the following are legal ways to print SUCCESS: abc:

clos(null)['key'] "abc"
clos null key "abc"
someMap['key'] "abc"

This one, however:

someMap key "abc"

throws a groovy.lang.MissingPropertyException: No such property: key for class: ConsoleScript50.

If clos(null) and someMap both resolve to java.util.LinkedHashMap, then what makes clos null key "abc" legal, but someMap key "abc" not legal?


Answer:

Groovy understands someMap key "abc" as someMap(key).getAbc(), which won't work. You really need the dot:

someMap.key "abc"

Or square brackets

someMap['key'] "abc"

Update

It seems that Groovy will always disambiguate a token like key as a call parameter (i.e. someMap(key)) if it can.

Yes, it will.

Only if that interpretation doesn't make sense does it instead interpret the token as a property (.key) or map dereference (['key']).

No, Groovy will always understand the second parameter, without dots or parens, as a call parameter. This

function parameter

Is always undertood as

function(parameter) 

It features no "precedence" over object[key]

If you keep adding stuff without dots or parenthesis to disambiguate, Groovy will keep adding parens and dots as per it's own rules. This:

gimme coffee with sugar and milk

Is understood as

gimme(coffee).with(sugar).and(milk)

Also this:

clos null key 'abc'

Will always be undertood as

clos(null).key('abc')

Related:


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


groovy,titan,gremlin
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...

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


spring,groovy,cron,spring-el
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...

Class fields as method parameters


oop,groovy
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,...

What's the difference between filter(|x|) and filter(|&x|)?


closures,rust
In the Rust Book there is an example of calling filter() on an iterator: for i in (1..100).filter(|&x| x % 2 == 0) { println!("{}", i); } There is an explanation below but I'm having trouble understanding it: This will print all of the even numbers between one and a...

Confused about the invokeMethod method in the Groovy MOP


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...

Closures vs Delegate pattern


ios,swift,delegates,closures
I'm working with network request classes and I'm concerned about crashes. For instance, working with closures is really easy as you pass a callback method to a function: // some network client func executeHttpRequest(#callback: (success: Bool) -> Void) { // http request callback(true) } // View Controller func reload() {...

Groovy TimeDuration Argument Types


date,groovy
I'm quite new to groovy (and haven't any experience with Java) - but I'm running into a problem that doesn't make sense to me. My guess is that its my misunderstanding of how objects and classes work in these languages. My question is probably very basic - any help is...

Groovy: run SQL SELECT LIKE from file with params


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

Groovy String.toURL is deprecated - why and what should we use instead?


groovy
In current groovy versions, the method DefaultGroovyMethods.toURL(String) is marked as deprecated, but without any explanation. Why is it deprecated and what should we use instead? I wanted to use it to easily get a file from HTTP like this: def xml = "http://url.to/file.xml".toURL().text ...

set an annotation attribute from an environment variable?


spring,groovy,spring-boot
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) { SpringApplication.run(Application, args) } ... } However, I get the following compile time error: Attribute 'cron' should have...

How to have an optional trailing closure?


swift,closures
I'm trying to write a function that I can call with trailing closure syntax like so: func hello( message: String, closure: (( msg: String ) -> Void)?) { println( "called hello with: \(message)" ); closure?( msg: message ); } I would expect to be able to call this function with...

How to get testStep responseAsXml in groovyScript


groovy,soapui
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...

Class declaration cannot close over value 'fulfill' defined in outer scope - Swift 2.0


xcode,swift,closures,promise
I'm trying to convert my app from Swift 1.2 to Swift 2.0 and I'm encountering the following error: class B { func test() -> Promise<A> { return Promise<A> { (fulfill, reject) -> Void in anotherPromise.then { _ -> Void in return fulfill(A()) // Class declaration cannot close over value 'fulfill'...

list of test step results in groovy script


groovy,automated-tests,soapui
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 { log.info (it.name) } Now I'm not sure how to move on...

Generic fn, channel, and thread spawn


closures,rust,lifetime
I have this code here: (Playground link) use std::thread; use std::sync::mpsc::channel; fn run<T: Send>(task: fn() -> T) -> T { let (tx, rx) = channel(); thread::spawn(move || { tx.send(task()); }); rx.recv().unwrap() } fn main() { let task = || 1 + 2; let result = run(task); println!("{}", result); } But...

Java syntax to Groovy syntax


java,groovy,syntax
I am not really sure how to translate this to groovy syntax. Have checked this differences with java page already. Thanks! TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String...

Using map on NSDictionary


swift,closures,nsdictionary
SETUP I am loading data from my server by using my API The returned data is in JSON The JSON provided by the API is pictured below I use ALAMOFIRE to receive the data from the API and parse the JSON response JSON { data: [ { owner: "FREDL", street:...

Get nth child node without knowing node name Groovy


xml,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...

Elasticsearch : _score always 0 in Groovy script


groovy,elasticsearch
I have this kind of Groovy script: def multiplier = doc['data'].value if (multiplier <= 0) { multiplier = 1 } multiplier * _score I use it as a script_score, and my score is always 0. It seems like _score is always 0. With a mvel script, it works. mvel script...

How to use multiple classes in multiple files in scripts?


groovy,scripting
I need to make a standalone Groovy script that does not require compilation and runs without Groovy installed. It works well, but it fails to recognize any other script than the main script. My folder structure is the following: libs\ groovy-all-2.4.3.jar ivy-2.4.0.jar src\ makeRelease.groovy ReleaseHelper.groovy I am launching the script...

Special Groovy magic re property access and collections / iterables?


groovy
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? [].class.methods.name => [add, add, remove, remove, get, ... I'd have expected that to be interpreted as...

Why isn't split working here?


regex,groovy
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...

sonar maven analysis only picks .java file


maven,groovy,sonarqube,sonarqube-5.0
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...

Parse RSS with groovy


parsing,groovy,rss,xmlslurper
I am trying to parse RSS feeds with groovy. I just wanted to extract the title and description tags' value. I used following code snippet to achieve this: rss = new XmlSlurper().parse(url) rss.channel.item.each { titleList.add(it.title) descriptionList.add(it.description) } After this, I am accessing these values in my JSP page. What is...

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


mysql,jdbc,groovy,groovy-console
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...

groovy/XML: Replace a node by another one


xml,groovy,xml-parsing,xmlslurper
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>...

Timeout with bind, call & apply methods


javascript,closures,this,settimeout,iife
Up until now, I've always used var self = this before creating a function that would need access to its parent. However the bind() method seems like a more appropriate way to do so and I'm exploring that option, along with the apply() and call() methods. This is what I...

NSTimer questions (closure, @objc, and etc.)


ios,swift,closures,nstimer
I'm pretty new to swift and I have some questions about swift and even just basic OOP (so if you can, please be specific with your answers, thanks a lot!) So I am making an app that has a timer component and the follow code snippets are from that timer...

Javascript Calling a nested function from within itself


javascript,function,methods,nested,closures
If I run the following... function outer(){ function inner(){ } inner(); } inner will run the first time as expected. If I then try to run the following... function outer(){ function inner(){ inner(); } inner(); } inner will again run the first time as expected, but then fails at any...

AngularJS Set Value to $scope from Nested Function


javascript,angularjs,scope,angularjs-scope,closures
I'm trying to get a value from a function inside a function: Controller $scope.vm = {}; function myFunc(){ $scope.vm.hello = 'Hello'; function myFunction(){ $scope.vm.world = 'world'; } } myFunc(); View <p>{{vm.hello}} {{vm.world}}</p> Here's my Plunk. How can I get this to display "Hello world"?...

Model to LazyMap


dictionary,groovy,deserialization
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...

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


grails,groovy,jax-rs
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...

Spock Framework: problems with spying


java,unit-testing,groovy,spock,spock-spy
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...

create email list of all users


groovy,jenkins,jenkins-scriptler
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...

Match string beginning with ([*>@]|--) ending with one of these


regex,groovy
I do have a String like *Task @Context >Delegation --Date and I'd like to extract the strings between the separators *@> and --. *Task @Context >Delegation --Date should yield the four strings Task, Context, Delegation and Date and *Task 9-5 @Co-ntext >Dele-gation --Date 12-5 Task 9-5, Co-ntext, Dele-gation and Date...

Write Spock test cases for Spring boot application


java,spring,groovy,spock
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...

Groovy's @CompileStatic and map constructors


groovy
I'm using @CompileStatic for the first time, and confused as to how Groovy's map constructors work in this situation. @CompileStatic class SomeClass { Long id String name public static void main(String[] args) { Map map = new HashMap() map.put("id", 123L) map.put("name", "test file") SomeClass someClass1 = new SomeClass(map) // Does...

Swift closures [weak self] and async tasks


ios,swift,asynchronous,closures
Imagine a situation, when you want to asynchronously load some text from the server and display the result in the ViewController's UITextField. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { //... some long running async operation if let textResponse = responseFromServer { dispatch_async(dispatch_get_main_queue(), { [weak self] () in self?.textField.text = textResponse }) } }) A.)...

Chaining Null-Safe Operator


groovy,nullpointerexception
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...

state retention for classes and closures


python,closures
source: Learning python by mark lutz area of content:page #503 classes versus closures: It states that " classes may seem better at state retention because they make their memory more explicit with attribute assignments. closure functions often provide a lighter-weight and viable alternative when retaining state is the only goal....

How does the Groovy compiler work?


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

Groovy - timestamp from minutes


oracle,grails,groovy,timestamp
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?...

What is the correct way to wrap Angularjs code in a closure?


javascript,angularjs,closures
I have a simple application outlined in this question: Angular scope not affecting ng-show as expected Which exposes my application via global variables, this is obviously not ideal. I have tried wrapping the Angularjs code in a closure but I get errors in the browser telling me that the objects...

Restrict allowed httpMethods using enum


rest,groovy,enums
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....

Fixing a closure within a loop


javascript,closures
I'm going through JavaScript: The Definitive Guide by David Flanagan and I am stuck at the following example: window.onload = function() { var elements = document.getElementsByClassName("reveal"); for(var i = 0; i < elements.length; i++) { var elt = elements[i]; var title = elt.getElementsByClassName("handle")[0]; title.onclick = function() { if(elt.className == "reveal")...

using classes in jenkins job dsl


groovy,jenkins,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...

Spock's @Narrative and @Title annotations


groovy,spock
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...

Get just content of soap response in Groovy


xml,soap,groovy
I have following soap response: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <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...

Why is the variable returned from a closure always one step behind


ios,swift,closures
In the following code the closure accesses a REST API to call a function on an embedded uC, then read a value from the uC. The problem is that the value returned to the variable "result" below, is always one step behind. Meaning, when I turn on the LED and...

Decode base64 image in Grails [duplicate]


grails,groovy
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...