FAQ Database Discussion Community


java Date.parse() over a year off [closed]

java,datetime,groovy
Why does my date come out over a year off? It takes 05/20/2015 and returns the 5th of August 2016. String d="05/20/2015"; Date date=Date.parse('dd/MM/yyyy',d); //Comes out Fri Aug 05 00:00:00 EDT 2016 ...

Spock framework only one exception condition is allowed per 'then' block

groovy,spock
org.spockframework:spock-core:1.0-groovy-2.4 Gradle 2.4 Groovy 2.3.10 I am using gradle and spock framework to test my java code. However, the function I am testing can throw 3 different exceptions that I need to test for. However, in my then clause I list the 3 exceptions and if any of them are...

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

Add floats yields Double

groovy
This groovy: float a = 1; float b = 2; def r = a + b; Creates this Java code when reversed from .class with IntelliJ: float a = (float)1; float b = (float)2; Object r = null; double var7 = (double)a + (double)b; r = Double.valueOf(var7); So r contains...

Groovy - compare two JSON objects (same structure) and return ArrayList containing differences

json,groovy,compare
I have two JSON objects of the same structure - an original and one which I want to compare it to. There is only one level of information (i.e nothing has any children). I want to compare the two and remember which fields, if any, were different by storing the...

jenkins: setting root url via Groovy API

groovy,jenkins
I'm trying to update Jenkins' root URL via the Groovy API, so I can script the deployment of a Jenkins master without manual input (aside: why is a tool as popular with the build/devops/automation community as Jenkins so resistant to automation?) Based on this documentation, I believe I should be...

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

Changing and adding arguments of method before invocation

groovy,metaprogramming
I want to reproduce the behavior of the default arguments by intercepting the call to some methods. The following code tries to give a default argument when the method display is called without arguments: class Thing { void display(String text) { println(text) } def invokeMethod(String name, args) { if(name ==...

Any way to make Groovydoc remove (selected) package qualifiers as per Javadoc's 'noqualifier' option?

ant,groovy,javadoc,groovydoc
I've just started generating Groovydoc for a library I'm working on. However, the preponderance of java.lang and java.util and other common package prefixes in the method signatures is obscuring the real intent of the methods. I'd like to be able to generate the Groovydoc without these. As in the (made...

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

What do you call this programming pattern? [closed]

javascript,groovy
I'm trying to figure out how to do this in JavaScript and can't seem to find the right words to Google for it. It's a fairly common pattern. someOperation(obj) { resultOfSomeOperation -> anotherOperation(resultOfSomeOperation) } Presumably someOperation is a method that takes as arguments an obj, and a function with signature...

null object error when calling code from script assertion - soapui

groovy,soapui
In a soapui groovy script test step I've this. context.setProperty("searchChange", new searchChange()); class searchChange{ def testRunner def searchChange(testRunner){ this.testRunner=testRunner } def search(a,b){ def search_TestCase = testRunner.testCase.testSuite.getTestCaseByName("Search") search_TestCase.setPropertyValue("Search_cID", a) search_TestCase.setPropertyValue("Search_sID", b) search_TestCase.run(new com.eviware.soapui.support.types.StringToObjectMap(), false) } } and in an assertion script in a different test suite I am...

need more understanding on gitblit groovy push script

java,git,groovy,repository,gitblit
I have below groovy script PushCommand push=git.push(); push.setRemote("my remote"); push.setPushAll(); //Push all branches under refs/heads/*. push.setForce(true); //Sets the force preference for push operation. push.call(); My requirement: want to push only changes from one gitinstance to other setPushAll : Is this going to push all repository data all time script executed...

Jenkins/Hudson Groovy Script Console: Flexibility

groovy,jenkins,hudson
I really like being able to run Groovy scripts in Hudson (or Jenkins, but I use Hudson). For example, see my question In Groovy, how do I get the list of parameter names for a given job? Hudson parameter names question][1] The thing is, now I'd like use these Groovy...

Throttle requests in camel not working

groovy,apache-camel,throttle,eip
Below are my 3 routes in my base groovy routes class deployed as base framework. from("jms:queue:EndPoint1?concurrentConsumers=100") .routePolicyRef("myPolicy") .transacted() .log("Recieved From Endpoint1") /*.to("log:Recieved From Endpoint1?groupSize=100")*/ .to("CommonEndpoint"); from("jms:queue:EndPoint2?concurrentConsumers=50") .rootPolicyRef("myPolicy") /*.to("log:Recieved From Endpoint2?groupSize=100")*/ .log("Recieved From Endpoint2") .to("CommonEndpoint"); from("CommonEndpoint") .delay(50)...

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

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

Cannot launch the Groovy Console

groovy,groovy-console
I have just did a fresh install of Groovy 2.4.3 in OSX 10.10.3 by means of the GVM tool. I also installed, using GVM, related libraries and tools such as groovyserv, grails and gradle. The Java version I am using is 1.8.0_25. Everything seems fine with the exception that I...

geb filtering link by its content

groovy,automation,geb
I have a page with bunch of hyperlinks. I want geb browser automation suite to filter a specific link by its display value. I could do as below and it works. def links = $("a") def a =[] links.each { if (it.text() == "blah blah blah....") { a.add(it) } }...

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

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

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

spockframework: check expected result after every feature

groovy,automated-tests,spock,geb
I am using spockframework and geb for test automation. I would like to execute after every feature a simple check to be sure that no error dialogs are shown, I have added the following cleanup() method: def cleanup() { expect: $('.myErrrorDialogClass').isEmpty() } The code is executed after every feature but...

Using “name” when Configuring Graphite with Jenkins Job DSL

groovy,jenkins-plugins,jenkins-job-dsl
I'm trying to configure the Graphite integration plugin for my jobs using Jenkins Job DSL. My block looks like this: coreJobs = [my jobs here] coreJobs.each{ a -> // some extra job config here job("$a") { project / 'publishers' / 'org.jenkinsci.plugins.graphiteIntegrator.GraphitePublisher' { selectedIp '192.123.1.456' metrics { 'org.jenkinsci.plugins.graphiteIntegrator.Metric' { queueName ".${a}.BuildFailed"...

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

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

Subtract days or years from new java.text.SimpleDateFormat

groovy,soapui
Application: SoapUI XML Resquest I could swear this worked at one time where I use the below: ${=(new java.text.SimpleDateFormat("yyyy-MM-dd")).format( new Date() )} To Subtract or Add I would add enclose the -# or +# like so: ${=${=(new java.text.SimpleDateFormat("yyyy-MM-dd")).format( new Date() )}-1 The result of the -1 is showing up as...

Groovy multiple Delegate annotation/Wrapper for list

list,groovy,delegates,annotations
I'm struggling how to use the @Delegate annotation in Groovy. What I'm trying to achieve is the following. I have two types of items (itemA & itemB). ItemB basically consists of a list of itemA's, so I used the @Delegate annotation. Furthermore, multiple itemA's are stored in a collection (collectionA),...

Junit using groovy expected exception

java,unit-testing,groovy,junit
I have Spring boot application. I use Junit+Mockito to unit test it. All the test cases were written using Java. I recently made a decision to write test cases using Groovy though the application code will remain in Java. I encountered a weird scenario while testing expected exceptions. Scenario 1:...

Maven failure to find codehaus artifact org.codehaus:codehaus-parent

java,maven,groovy,repository
So codehaus shut down (over the weekend, apparently): https://www.codehaus.org/ Now it says here that "Maven: All repositories are mirrored into Central, and our Nexus is hosted by Sonatype". If I am reading this correctly, this means that it should continue to work (and because Central is the default repository, I...

Replace '%@' with '%n$s' using groovy regex

android,regex,groovy
I have a string like some text %@ some text %@ some text where %@ is a obj-c formatting. I need to transform this string to some text %1$s some text %2$s some text , which is a android resource with formatting. How can I do it using groovy regex?...

Is declaring a variable with an empty map, and then assigning a different object to it an efficient pattern?

oop,object,grails,groovy
We are developing a Grails project and I am am a Grails/Groovy novice and I am seeing a pattern where we define a variable as an empty map in the controller, and then in a service method also defining another empty map, and populating it with key/value pairs from the...

Calling a @Canonical Groovy POGO constructor inside Java code

java,groovy
Given this Groovy domain class (for persistence in MongoDB): @Canonical class Counter { @Id String id String name long count = 0 Date createdTimestamp = new Date() Date updatedTimestamp = new Date() } Since only 'name' need be supplied when creating a new Counter, is there a way to call...

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

How to add quotes into sql where clause in Groovy script?

sql,sql-server,groovy
Collegues, please help me with sql in Groovy. In my SOAP UI groovy script i have sql query: sql.eachRow('select top 1 '+ 'Country, '+ 'from dbo.Address where UPPER(Country) = "JAPAN" ORDER BY NEWID()') Everything was fine till i work without quotes in where clause. After I add UPPER(Country) = "JAPAN"...

Getting the value of child node in xml using groovy

xml,groovy
How do I parse the value of Profile in the below xml using groovy? <Books> <Book> <Profile>Science</Profile> <Extension>.png</Extension> <Length>1920</Length> <Width>1080</Width> </Book> <Book> <Profile>English</Profile> <Extension>.png</Extension> <Length>640</Length> <Width>460</Width> </Book> </Books> I have tried: def bookxml = new XmlSlurper().parseText(bookText) def profile = bookxml.Book.findAll {...

How to pass multidimensional arrays to a method? Groovy

java,multidimensional-array,arraylist,groovy
The error I'm getting is groovy.lang.MissingMethodException: No signature of method: static utilities.dslUtilities.teamSwitch() is applicable for argument types: (java.util.ArrayList, java.util.ArrayList) values: [[[ConfigurationService, 1, Projects], ...], ...] Possible solutions: teamSwitch(java.util.ArrayList, java.util.ArrayList) I'm passing two arrayLists to the method and groovy is telling me I can't do this but I should try passing...

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

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

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

What is “all” iterator?

android,groovy
In the Android plugin for gradle, I wanted to use this method which suggests to use all iterator : /** * Returns the list of Application variants. Since the collections is built after evaluation, * it should be used with Groovy's <code>all</code> iterator to process future items. * */ public...

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

JsonSlurper returns No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (java.util.ArrayList)

json,parsing,groovy,jsonslurper
I'm trying to parse JSON file with JsonSlurper.parseText but keep getting similar problems. def jsonParse = null def http = new HTTPBuilder(url) http.auth.basic(username, password) http.request(Method.GET) { response.success = { resp, reader ->; jsonParse = new JsonSlurper().parseText(reader) } } Whenever I run my application the error message says No signature of...

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

Groovy: Is for..in significantly faster than .each?

groovy,microbenchmark
I'm curious if for..in should be preferred to .each for performance reasons.

jenkins with groovy postbuild .Not able to execute anything in groovy script field

groovy,jenkins,jenkins-plugins
I need to run set of code after the build is completed. I use groovy postbuild plugin(version2.2). I am new to jenkins and groovy. I tried simple println but it is not working. I tried something like this and its also not working. I dont even see error message if...

Token error with groovy in NetBeans

netbeans,groovy,titan
Initially, I was developing my groovy code in a simple text editor, but I set up version control via NetBeans and so moved my code over. However, I'm getting an "unexpected token" error on code that actually runs fine. class PWLoad { def conf = new BaseConfiguration() {{ setProperty("storage.backend", "cassandra")...

groovy code “(wangwang as Man).shout(10)” throws java.lang.NullPointerException

groovy
I am new to groovy. I just wrote below code public interface Man{ public void say(); public int shout(int x); } def wangwang = { println("wangwang!"); println(it) } //(wangwang as Man).say() (wangwang as Man).shout(10) I run it in groovyConsole. and here's the output wangwang! 10 Exception thrown java.lang.NullPointerException at com.sun.proxy.$Proxy18.shout(Unknown...

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

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

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

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

recursive clousure error applicable for argument types: (java.lang.String, java.util.ArrayList) groovy

recursion,groovy
I have a list: def myList = [[item1:1, values:'a'], [item2:2, values:'a'], [item2:3,values:'b']] My recursive clousure: def getList = { sep, list -> list.each{ item -> //def at = it def da = myList.findAll { it?.value == item.value } //println da if(da?.size()>1 ){ getList(',',da) } else { //println item.category+sep } }...

calculate max length of each field in csv file using groovy

csv,groovy
How can I print out the max length of each field in CSV file? Example input: foo,bar abcd,12345 def,234567 Expected output: Max length of fields: [4, 6] ...

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

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

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

Create a new dynamically named list in groovy

list,variables,dynamic,groovy
I have a list of items that looks like this items = ["a", "b", "c"] I also have a list of values that looks like this values = ["a1", "a2", "a3", "b1", "b2", "c1", "c2", "c3"] my items list is static, but my values list will change often. my code...

What is the difference between any and find in groovy?

groovy
I am trying to get the set values from closure in groovy: myList(1, 2, 3).any { it > 2 } myList(1, 2, 3).find { it > 2 } So not able to figure out, which one to use and better....

SoapUi Assertions - Use a string as a json path with groovy

json,string,groovy,soapui,assertions
I am using groovy to automate some tests on SoapUI, and I wanted to also automate assertions in a way I would get a field's name and value from a *.txt file and check if the wanted field does exist with the wanted value in the SOapUI response. Suppose I...

Variable Substitution in logback groovy

java,variables,groovy,logback,logback-groovy
I was working with the logback.xml and the variable were load in string like : <FileNamePattern>${logDirectory}/${logFileName}.%d{yyyy-MM-dd}.%i.html</FileNamePattern> where logDirectory and logFileName were set in .bat file before calling my jar. set logFileName=foobar But now, I deal with groovy. It's awesome and ridiculously more readable than xml. But the variable are no...

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

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

Setting nextFireTime of a quartz job manually in groovy

groovy,quartz-scheduler
I want to use a own errorhandling on quartz jobs. Each job has a different waiting time, when an exception occurs. For example, a job runs every 30 seconds, but when an exception occurs, the job should wait for 5 minutes. I tried this approach, but it doesn't work: SchedulerFactory...

Spring Boot vs. Groovy Templates - can't iterate over a list inside the ModelAndView

java,spring,spring-mvc,groovy
I am evaluating Spring Boot for a future application and wanted to use the Groovy templates for their sheer readable beauty. Unfortunately I am having trouble with iterating over a list of objects I am adding to the ModelAndView object returned from the controller. This is my controller: @RestController @RequestMapping("/ships")...

Adding double in groovy

groovy
I defined two doubles: double abc1 = 0.0001; double abc2 = 0.0001; now if I print them: println "Abc1 "+abc1; println "Abc2 "+abc2; it returns: Abc1 1.0E-4 Abc2 1.0E-4 While if I add them: println "Abc3 "+abc1+abc2; It returns: Abc3 1.0E-41.0E-4 rather than: Abc3 2.0E-4 Why does this happen?...

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

Groovy generated constructor missing during compile

groovy,gradle
I have a setup in which I call the generated constructor(@TupleConstructor) of a Groovy class(Product) from a java class(ProductService). The IDE shows the generated constructors and compilation used to work. But now, for unknown reasons, the compilation fails because the compiler doesnt find the parameterized constructors anymore: ProductService.java:31: error: constructor...

@CompileStatic an entire package?

groovy
I noticed that Groovy's @CompileStatic annotation allows for annotating an entire package. So I create a package-info.groovy file in the com.somepackage package which contains this: package com.somepackage So far so good. Now I add the annotation: @CompileStatic package com.somepackage import groovy.transform.CompileStatic and suddenly Eclipse flags line 2 as an error:...

null.collect() returns empty list

groovy
I was writing unit tests when I happened to find that in groovy the below is true null.collect({ //Anything }) == [] I could not find the reason for this. What part of groovy is giving this behavior? I checked NullObject but that does not have this collect method. So...

Groovy List : Group By element's count and find highest frequency elements

collections,groovy
I have a groovy list as below def certs = ['0xc1','0xc1','0xc1','0xc1','0xc2','0xc2','0xc3','0xc4','0xc4','0xc5','0xc5','0xc5','0xc5'] Am trying to find the occurance of each element and group by its count. I've tried certs.groupBy { it }.findAll { it.value.size() } but am getting the below output [0xc1:[0xc1, 0xc1, 0xc1, 0xc1], 0xc2:[0xc2, 0xc2], 0xc3:[0xc3], 0xc4:[0xc4, 0xc4], 0xc5:[0xc5,...

Groovy insert and select query together using sql server database

sql-server,sql-server-2008,groovy
I have some issues executing the sql server query in groovy code. My requirement is , I need to read data from a table ABC.customer and store the data into a temporary table test. My query is : DECLARE @throughDate datetime, @startDate datetime DECLARE @test TABLE ( test_id char(50) )...

How to split value of dict on two parts

java,groovy
I have def dict = [some_key : ['a', 'bc', 'd']] I would like to split bc to b and c, so after splitting dict will be looks like this: dict = [some_key : ['a', 'b', 'c', 'd']] Is there any way to do this with build-in methods?...

@Path annotation: abstract resource in dropwizard

java,groovy,annotations,jetty,dropwizard
I had an idea to build abstract resource class for my application: abstract class MyAbstractResource<A> { MyAbstractDao dao; public MyAbstractResource(MyAbstractDao dao) { this.dao = dao; } @Path("/") @POST @Produces(MediaType.APPLICATION_JSON) @Timed public A create(A account) { return dao.create(account); } @Path("/{id}") @PUT @Produces(MediaType.APPLICATION_JSON) @Timed public A update(A account) { return dao.change(account); }...

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

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

In Groovy, what is the precedence of the membership operator (“in”)

groovy
http://www.groovy-lang.org/operators.html#_operator_precedence does not list the "in" (membership) binary operator. What is its precedence?

spring-integration-dsl-groovy-http return null when i use httpGet method

spring,groovy,spring-integration
I use spring integration 4.1.4 and spring integration dsl groovy 1.1.0 I included spring integration core, http in dependency. When i am executing spring integration dsl groovy http sample, it throwing null value in console. I am not sure what i missed. Here is my code looks like IntegrationBuilder builder...

Groovy: Why can't the closure access itself?

groovy
I'm a Groovy newbie. When I run the following script Groovy reports "No such property: tailFactorial for class ***". Shouldn't the closure access the local variable tailFactorial? def factorial(int factorialFor) { def tailFactorial = { int number, BigInteger theFactorial = 1 -> number == 1 ? theFactorial : tailFactorial.trampoline(number -...

How to get xquery assertion value using groovy script

groovy,soapui
I have created a teststep in SOAPUI tool with two assertions namely Valid HTTP Status codes Assertion and XQuery Match Assertion Now I need to print the values contained in these assertions using groovyscript. For XQuery Assertion, I need to print the xquery expression . I tried using getToken() method....

Spring : How to configure tomcat Datasource Programatically in Groovy DAO

java,spring,spring-mvc,tomcat,groovy
I have my tomcat datasource configured in XML as below: <bean id="docDataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close" p:driverClassName="${doc.database.driver}" p:url="${doc.database.url}" p:username="${doc.database.user}" p:password="${doc.database.password}" p:validationQuery="select 1" p:testOnBorrow="true" p:minIdle="2" p:maxIdle="4" p:maxActive="6" p:defaultTransactionIsolation="1"> </bean> And my customDAO(groovy class) uses the above datasource as below import...

Groovy replace node values in xml with xpath

xml,xpath,groovy
I want to replace the node values in a xml in groovy. I have the values in xpath in a hashmap like: def param = [:] param["/Envelope/Body/GetWeather/CityName"] = "Berlin" param["/Envelope/Body/GetWeather/CountryName"] = "Germany" XML File: <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header/> <soapenv:Body> <web:GetWeather xmlns:web="http://www.webserviceX.NET"> <web:CityName>Test</web:CityName>...

InvokeDynamic for Grails

grails,groovy,invokedynamic
Is it possible to use InvokeDynamic for Grails? If so, what versions of Grails, Java, etc. are compatible? What is the procedure to set it up? If it's not possible, when might InvokeDynamic support be added to Grails 2.x and/or 3.x? I haven't found any recent information about it....

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

Run a Curl comand from a jenkins job

shell,curl,groovy,jenkins,command
can anyone tell me how we can run a curl command from jenkins. I'm on windows 7 and i'm trying to put .sh on artifactory from a job jenkins. thanks

Groovy 2d array

groovy
I want to have a collection like this [item1: [123, 123, 2321], item2: [1231,1222,1313]] I tried using a map like this [ : [] ] but this is not allowed. How can I achieve the following structure. I want to add element using a string as a key: content['item1'] <<...

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

is it possible to replace Application.java with Application.groovy?

groovy,spring-boot
I'm trying to build an executable jar using spring boot and groovy. Is it possible to replace Application.java with Application.groovy? I can only find examples of the main class written in java....

Strange behavior of ternary operator

grails,groovy
I observed strange behavior, in clean "test" application I have this simple controller: (Grails 2.5.0, Java Oracle 8u45, GNU/Linux Debian 7) package test class DiController { def ok() { double d = 0d int i = (int)d def r = [] r << i if (true) { r << i...

Groovy Postbuild do not execute scripts on Jenkins

groovy,jenkins,jenkins-plugins
I've written simple groovy script, but I don't know how to execute it on Jenkins. Look at this simple script: String jbN = System.getenv('JOB_NAME') println jbN println "Hello" I would except that I will reveived at least "Hello". Script give no return. I've just received Build step 'Groovy Postbuild' marked...

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

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

Inserting XML snippet into another XML document in Groovy

xml,groovy
The following code snippet should insert the fragment XML into body, right after elem. def body = ''' <parent> <child> <elem> <name>Test</name> </elem> </child> </parent> ''' def fragment = ''' <foo> <bar>hello!</bar> <baz/> </foo> ''' def bodyNode = new XmlParser().parseText(body) def fragmentNode = new XmlParser().parseText(fragment) bodyNode.child*.appendNode(fragmentNode) def newFileName= '/Users/xxx/out.xml' def...

Gradle createPom doesn't seem to read gradle.properties

groovy,gradle
Please note: Although I mention the ShadowJar plugin in this question, it is just for providing full context. I am confident any Gradle Guru can answer this, regardless of their knowledge level of ShadowJar. Currently my Groovy project is built with the following Gradle build invocation: gradle clean build shadowJar...

How to define an annotation for more than one target in Groovy?

groovy,annotations
In Java, to define an annotation for more than one target, the curly braces can be used: @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD}) public @interface AnnotExample { String name(); } However, this doesn't work in Groovy: $ groovyc AnnotExample.groovy org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: AnnotExample.groovy: 8: expecting '}', found ',' @ line 8, column 26....

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

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

How to merge 2 groovy configuration files which are in the form of groovy scripts?

java,groovy
I want to merge 2 groovy configuration files. Is there a way to write back to groovy's configuration file? Suppose I create a temp config file which contains only the changes (addition/modification) and then append it or alter the target configuration file (Not sure if there is a config writer...

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

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

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