Menu
  • HOME
  • TAGS

Strange behavior of ternary operator

grails,groovy

I believe that's because Groovy tries to find a common ground for incompatible types. This is an example of various ternary operators uses: println ((true ? (0 as Integer) : (0.0 as Float)).class) println ((true ? (0 as Float) : (0.0 as Double)).class) println ((true ? (0 as Integer) :...

need more understanding on gitblit groovy push script

java,git,groovy,repository,gitblit

Got answer what I want to know As in comment Git only pushes what is not in the target setForce(true) will override references in the target repo with the references in the source repo. For your situation this is probably what you want. – James Moger setPushAll will push all...

Inserting XML snippet into another XML document in Groovy

xml,groovy

Reason: use of appendNode() instead of append(). Try this instead: bodyNode.child*.append(fragmentNode) Alternatively This is one way to achieve the correct output using XmlSlurper: def body = ''' <parent> <child> <elem> <name>Test</name> </elem> </child> </parent> ''' def fragment = ''' <foo> <bar>hello!</bar> <baz/> </foo> ''' def slurper = new XmlSlurper( false,...

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

groovy

I found the answer in the source code of the Groovy parser itself: https://github.com/groovy/groovy-core/blob/master/src/main/org/codehaus/groovy/antlr/groovy.g#L2337: ( 7) < <= > >= instanceof as in So, the "in" operator has the same precedence as "instanceof", "as", etc....

Gradle createPom doesn't seem to read gradle.properties

groovy,gradle

THe lines: groupId ${group} artifactId 'myapp' version ${version} Are not valid groovy, and should probably be: groupId "${group}" artifactId 'myapp' version "${version}" ...

Spock's @Narrative and @Title annotations

groovy,spock

Title is expected to be a single line (short description) Narrative should be full paragraphs (using a Groovy multi-line string) They are mostly used in big projects where Narrative text could be read by business analysts, project managers e.t.c. As Opal said these will be more useful once some reporting...

set an annotation attribute from an environment variable?

spring,groovy,spring-boot

You can not use GStrings in java annotations in groovy. You have to use "proper" Strings. E.g. @Scheduled(cron = '${DB_CRON}') Note the single quotes here. If groovy sees a $ in "-quoted string, it will turn it into a GString. This can not be done with java annotations and you...

Subtract days or years from new java.text.SimpleDateFormat

groovy,soapui

You have the brackets misplaced! Let me break it down for you: def yesterday = new Date() - 1 def sdf = new java.text.SimpleDateFormat("yyyy-MM-dd") def yesterdayFormatted = sdf.format(yesterday) If you want it in a SoapUI property one liner: ${=new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date() - 1)} Note that you can achieve the exact...

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

json,groovy,compare

You are comparing always against secondJSON.it (it here is just a String key, and since there is no value for this key, you get null). You will have to use: secondJSON.get(it.key) // or secondJSON."$it.key" to access the key from the other map. Be aware, that you might want to check...

Spring : How to configure tomcat Datasource Programatically in Groovy DAO

java,spring,spring-mvc,tomcat,groovy

Here's the piece of code you can follow (with PostgreSQL, but it should more or less work the same): import org.postgresql.ds.PGPoolingDataSource import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import javax.sql.DataSource @Configuration class PostgreSQLDatasourceConfiguration { @Bean(name = 'dataSource') DataSource ds(@Value('${DATABASE_URL}') String databaseFullUrl) { assert databaseFullUrl, 'Database URL is required to...

Why isn't split working here?

regex,groovy

String#split takes a regular expression as an argument. . is a regular expression special character, see the regex tutorial: Because we want to do more than simply search for literal pieces of text, we need to reserve certain characters for special use. In the regex flavors discussed in this tutorial,...

Getting the value of child node in xml using groovy

xml,groovy

It should work well - if the syntax is corrected parseText instead of parsexml - all the profiles are found. Catch the sample: def bookXml = '''<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>''' def bookxml = new...

Throttle requests in camel not working

groovy,apache-camel,throttle,eip

I am not sure how to implement the ThrottlingInflightPolicy you have setup, but you can implement a route like this that should accomplish your goal. from("jms:queue:EndPoint1?concurrentConsumers=20") .throttle(10) .to("Other_Logic_Or_Routing"); Notes: maxInflightExchanges can be controlled by simply lowering concurrentConsumers to 20 Throttle component can ensure that your messaging rate does not exceed...

What is the difference between any and find in groovy?

groovy

any returns boolean - true if any of the elements on the list matches the closure condition, while find returns first element that meets the criteria in closure being passed. If you need to know if there're elements matching certain criteria, use any, if you need only a single element...

calculate max length of each field in csv file using groovy

csv,groovy

The following piece of code will do the job: def txt='''foo,bar abcd,12345 def,234567''' txt.split('\n').collect { it.split(',') }.transpose().collect { field -> field.max { it.size() } }*.size() ...

spockframework: check expected result after every feature

groovy,automated-tests,spock,geb

Spock uses AST transforms to wire in the functionality for each test label (when, expect, etc); they may not run the transformations on the cleanup method. They are either not expecting or not encouraging assertions in cleanup, so that code may run but not actually assert anything. You can get...

What do you call this programming pattern? [closed]

javascript,groovy

I believe the pattern you're pointing to is the "Callback" pattern, or more generally "Higher Order Functions", in which a function takes in a function as a parameter, and then uses the passed in function in some way. Some examples would be Each, Map, Reduce, etc... These often use lambda...

Confused about the invokeMethod method in the Groovy MOP

groovy,mop

In short you are not using the standard meta class, so you don't get the standard Groovy MOP. Car.metaClass.invokeMethod = { will let Car have an ExpandoMetaClass as meta class. This meta class uses the invokeMethod you give in as open block (like you do) to intercept calls. This is...

How to split value of dict on two parts

java,groovy

Here You go: def dict = [some_key : ['a', 'bc', 'd']] dict.some_key = dict.some_key.collect { it.collect{ it } }.sum() println dict collect invoked on String will return a List of characters....

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

java,datetime,groovy

You have changed months with days. should be: String d="20/05/2015"; instead of String d="05/20/2015"; ...

How to get xquery assertion value using groovy script

groovy,soapui

Use getPath() method to get the XQuery Expression on your assertion. Take into account that this method is specific for assertions of XQueryContainsAssertion class, so if you invoke in other assertion object you'll get a groovy.lang.MissingMethodException. Also think about that with your code you're casting each testStep in your testCase...

Spock Framework: problems with spying

java,unit-testing,groovy,spock,spock-spy

It should be: @Grab('org.spockframework:spock-core:0.7-groovy-2.0') @Grab('cglib:cglib-nodep:3.1') import spock.lang.* class CallingClassTest extends Specification { def "check that functionTwo calls functionOne"() { def c = Spy(CallingClass) when: def s = c.functionTwo() then: 1 * c.functionOne() >> "mocked function return" s == "some string mocked function return" } } public class CallingClass { public...

Junit using groovy expected exception

java,unit-testing,groovy,junit

However, the assert and verify after that are not called. As soon as the exception is encountered, the method execution stops. However, my earlier test case written in Java worked perfectly well. Given this code in java: @Test(expected = NoResultException.class) void testFetchAllNoResultsReturned() throws Exception { List<Name> namesLocal = null;...

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

oop,object,grails,groovy

There is no good reason to do something like this... def output = [:] output = [key0: 'value0', key1: 'value1', key2: 'value2'] Maybe this will help clarify what is going on. The following is equivalent to the code above... def output = new LinkedHashMap() output = new LinkedHashMap() output.put 'key0',...

Groovy 2d array

groovy

It all works correctly, you use a Map - not 2D array: def m = [item1: [123, 123, 2321], item2: [1231,1222,1313]] m['item1'] << 1234 println(m) If you need a declaration it can be done in the following way: Map<String, List<Integer>> m = [:] however it will be erased at runtime....

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

groovy,jenkins,jenkins-plugins

Your groovy postbuild configuration and syntax look fine to me. I assume you are experiencing this with a Build Flow type job. I can reproduce this behavior with a configuration similar to yours and I suspect that it is related to the build flow. One solution that worked for me...

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

groovy,spring-boot

Basically just add the org.codehaus.groovy:groovy-all dependency to your build.gradle file and also add apply plugin: 'groovy' and it should pick up your groovy files.

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

json,parsing,groovy,jsonslurper

According to the documentation, the HTTPBuilder could be parsing your JSON for you. If your JSON response has its root as a JSON array, then that explains the ArrayList object in your reader variable.

Cannot launch the Groovy Console

groovy,groovy-console

I had this one before and it was due to an environment classpath variable set to point to an invalid jar

Groovy - timestamp from minutes

oracle,grails,groovy,timestamp

I assume you want to use the current day offset with the number of minutes given for your timestamp. Since a new Date or Timestamp will be initialized to the current time and date, you can use that and override the minute field with the values from your array. Values...

Groovy Postbuild do not execute scripts on Jenkins

groovy,jenkins,jenkins-plugins

I found the solution: Script was executed but wasn't printed to console output. To print result to console output you need to write: manager.listener.logger.println("Some string") instead println. To make it shorter do: variable = manager.listener.logger.&println...

How does the Groovy compiler work?

groovy

Groovy parses the source code with antlr via the groovy grammar description, then generates bytecode using asm It does not require javac...

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

spring,groovy,spring-integration

This has been fixed on the master branch. Meanwhile a simple work-around is url:{"http://www.google.com/finance/info?q=$it".toString()} or url:{"http://www.google.com/finance/info?q=$it" as String} ...

Create a new dynamically named list in groovy

list,variables,dynamic,groovy

You can dynamically add variables but you will need to use this (being the instance of the object you are setting the variable on), e.g.: this."${items[i]}" += value[i] This should give you what you need or at least point you in the right direction....

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

recursion,groovy

You need to declare the getList variable before you define it for this to work, change def getList = { sep, list -> To def getList getList = { sep, list -> ...

How to pass multidimensional arrays to a method? Groovy

java,multidimensional-array,arraylist,groovy

Looks like you forgot keyword static for method.

Groovy insert and select query together using sql server database

sql-server,sql-server-2008,groovy

Try add "SET NOCOUNT ON" in your query statement before the first SET: DECLARE @throughDate DATETIME, @startDate DATETIME DECLARE @test TABLE(test_id CHAR(50)) SET NOCOUNT ON SET @throughDate = '5-27-2015' sql-server will print out some text messages for each insert/update/select statement without the "NOCOUNT", which break your record set. ...

Groovy multiple Delegate annotation/Wrapper for list

list,groovy,delegates,annotations

Short answer: reaplce += with add You problem is not @Delegate, but misunderstanding what += does. See this example: def l = [1,2,3] l += [4,5] assert l == {1,2,3,4,5] As you can see, the list [4,5] is not added as list. Instead a new list consisting of the elements...

Setting nextFireTime of a quartz job manually in groovy

groovy,quartz-scheduler

I may be wrong but are you sure you can schedule a job by simply setting the nextFireTime property? I guess you have to use http://quartz-scheduler.org/api/2.2.0/org/quartz/Scheduler.html#rescheduleJob(org.quartz.TriggerKey, org.quartz.Trigger) do reschedule a job. e.g. SchedulerFactory sf = new StdSchedulerFactory() Scheduler sched = sf.getScheduler() def name = "jobname" Trigger trigger = sched.getTrigger(new TriggerKey("trigger_"...

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

groovy

toURL() invoked on String comes from this class, not from DefaultGroovyMethods, so everything works fine and correct method is invoked.

How to get testStep responseAsXml in groovyScript

groovy,soapui

If you want to get the response from com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep, a possible way is first get the testStep from this class using getTestStep() method. This method returns a object of class com.eviware.soapui.model.testsuite.TestStep, from this object you can get the testSteps properties like request, response, endpoint... using getPropertyValue(java.lang.string) method. So in your...

Groovy TimeDuration Argument Types

date,groovy

you should be using: use ( TimeCategory ) { diff = finish - start println diff.weeks } what you see in the groovy doc static Duration getWeeks(Integer self) is the how the groovy system calls the methods. Almost all such static groovy methods have this form: static doSmth( self, otherArgs......

list of test step results in groovy script

groovy,automated-tests,soapui

I think the better approach you can use is get the assertion status of the testSteps, and then check if the status is FAILED, UNKNOWN or VALID. You can use the follow groovy code to do so: import com.eviware.soapui.model.testsuite.Assertable.AssertionStatus def TestCase = testRunner.getTestCase() def StepList = TestCase.getTestStepList() StepList.each{ // check...

Write Spock test cases for Spring boot application

java,spring,groovy,spock

Yes, you can write spock test cases for your spring application. Look at the official documentation for an example of Spock testing with Spring Boot 35.3.1 Using Spock to test Spring Boot applications A simple google search reveals a basic example of Using Spock to test Spring classes. Spock relies...

Run a Curl comand from a jenkins job

shell,curl,groovy,jenkins,command

So I understand that you want to upload a file to Artifactory by using curl and Artifactory's REST API? The easiest would be to use the Artifactory plugin, and upload files from your workspace into an Artifactory repository. If you want to do it without that: Install cURL for Windows...

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

groovy,xml-parsing

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 "http://cmp.thn.com:80/artifactory/files-release-local" } } buildscript {...

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

collections,groovy

There are several ways to do this. A good place to start learning Groovy's methods on collections is with collect and inject. The method collect generates a new collection for the old one, taking a closure that describes how to change each element of the existing collection to get a...

Restrict allowed httpMethods using enum

rest,groovy,enums

Is that what you're looking for: public enum HttpMethod { POST, DELETE, GET, PUT, HEAD, TRACE, CONNECT, PATCH } class EntityQuery { String field1 String field2 } def createEntity(HttpMethod h, EntityQuery q) { if(!(h in [HttpMethod.POST, HttpMethod.GET])) { throw new Exception('Only POST and GET methods allowed') } } createEntity(HttpMethod.PUT, new...

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

groovy,spock

the best I've come up with is use a where: clause def 'Create instant pubsub node'() { setup: smackClient.initializeConnection(domain, serviceName, resource, port, timeout, debugMode) smackClient.connectAndLogin(username, password) when: smackClient.getSPubSubInstance(smackClient.getClientConnection()).createInstantnode() then: notThrown exception where: exception << [XMPPErrorException, NoResponseException, NotConnectedException] } I've created a simpler example on the spock web console...

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

groovy,microbenchmark

For .. in is part of the standard language flow control. Instead each calls a closure so with extra overhead. .each {...} is syntax sugar equivalent to the method call .each({...}) Moreover, due to the fact that it is a closure, inside each code block you can't use break and...

Special Groovy magic re property access and collections / iterables?

groovy

That's the GPath expression documented (ish) here, and yes, it only works for properties. (There's an old blog post by Ted Naleid here about digging in to how it worked in 2008) For methods, you need to use *. or .collect() See also: Groovy spread-dot operator Better docs link (as...

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

groovy,titan,gremlin

When vertices are added to Titan an Element identifier is assigned. That value is up to Titan and you should not expect it to start at "1" or any other specific number when you do. If you need there to be some kind of number like that you should add...

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

spring,groovy,cron,spring-el

You should set env variable like you do: export db_cron="0 19 21 * * *" then restart your ide if you are using or restart your terminal session. @Scheduled(cron = "${db_cron}") def void schedule() { ... } I tried it and here is my screenshot. Everything works as expected......

How to use multiple classes in multiple files in scripts?

groovy,scripting

I think that it is easier than you think: libs\ groovy-all-2.4.3.jar src\ main.groovy Greeter.groovy Where main.groovy public class Main { public static void main(args) { println 'Main script starting...' def greeter = new Greeter() greeter.sayHello() } } and Greeter.groovy class Greeter { def sayHello() { println 'Hello!' } } Simply...

Decode base64 image in Grails [duplicate]

grails,groovy

Base64 uses Ascii characters to send binary files, so to retrieve your image, you basically have to decode the Base64 string back to a byte array and save it to a file. String encoded = 'iVBORw0KGgoAAAANSUhEUg' // You complete String encoded.replaceAll("\r", "") encoded.replaceAll("\n", "") byte[] decoded = encoded.decodeBase64() new File("file/path").withOutputStream...

Add floats yields Double

groovy

Groovy decided to take 5 standard result types of numeric operations. fall back to certain standard numeric types for operations. Those are int, long, BigInteger, double and BigDecimal. Thus adding/multiplying two floats returns a double. Division and pow are special. From http://www.groovy-lang.org/syntax.html Division and power binary operations aside, binary operations...

Class fields as method parameters

oop,groovy

Assuming your EntityQuery.groovy ( model )looks like : private String typeName private Order order Assuming you have Order.groovy ( model ) that looks like : private String fieldName; private String orderType; private String orderName; use these model chain as a parameter, I think that is still strongly-typed (correct me). Your...

Using “name” when Configuring Graphite with Jenkins Job DSL

groovy,jenkins-plugins,jenkins-job-dsl

After Reading the Documentation again I found an example of a conflicting element: https://github.com/jenkinsci/job-dsl-plugin/wiki/The-Configure-Block The doc suggests using the ‘delegate variable'. So my Code now uses: delegate.name('BUILD_FAILED') This now means my jobs are created with the right names and no 'BUILD_FAILED' job is generated....

Groovy: run SQL SELECT LIKE from file with params

sql,select,groovy

try this SELECT * FROM [db].[dbo].[TABLE] WHERE [ID] LIKE '%'+convert(varchar(50),:id)+'%' ...

geb filtering link by its content

groovy,automation,geb

You can select by text in Geb: $("a", text: "blah blah blah...") If you want to reuse a selector and filter by text then you can indeed use filter(): def links = $("a") def linksWithText = a.filter(text: "blah blah blah...") ...

null.collect() returns empty list

groovy

collect method is added to all objects at runtime via DefaultGroovyMethods class, see here, so every class has this methods: class Lol {} assert new Lol().collect({}) == [null] assert new Lol().iterator().toList() //is not empty, contains 'this' ...

Parse RSS with groovy

parsing,groovy,rss,xmlslurper

You can tell XmlSlurper and XmlParser to not try to handle namespaces in the constructor. I believe this does what you are after: 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'.toURL().withReader { r -> new XmlSlurper(false, false).parse(r).channel.item.each { println it.title println it.description } } ...

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

json,string,groovy,soapui,assertions

I think your problem is to access a json value from a path based with . notation, in your case path.field to solve this you can use the follow approach: import groovy.json.JsonSlurper def path='path.field' def value='My Wanted Value' def response = '''{ "path" : { "field" : "My Wanted Value"...

using classes in jenkins job dsl

groovy,jenkins,jenkins-job-dsl

When using println in scripts (in your example, in the runIt function), Groovy sends the call to a out variable defined in the script's binding or to System.out.println if the variable is not set. The Job DSL plugin sets this variable so that the output goes to the build log....

groovy/XML: Replace a node by another one

xml,groovy,xml-parsing,xmlslurper

Here you go: import groovy.xml.* def xml = '''<myXml> <myNode> <Name>name1</Name> <Name>name2</Name> <Name>name3</Name> </myNode> </myXml>''' def namelist = ['name4','name5','name6','name7'] def slurped = new XmlSlurper().parseText(xml) slurped.myNode.replaceNode { myNode { namelist.collect { n -> Name "$n" } } } new StreamingMarkupBuilder().bind { mkp.yield slurped }.toString() The node was in fact replaced but...

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

java,spring,spring-mvc,groovy

I had the same problem with groovy templates. It appears that groovy template engine wraps your template code into a temporary class named after the template file. In your case it creates class named ships and that class name hides your model attribute. So, ships.each{...} trys to iterate over an...

Chaining Null-Safe Operator

groovy,nullpointerexception

It is the way Groovy works, indeed, and has bitten others: println book?.author?.firstName?.trim().concat(" is great.") ... Looking at this line of code, I thought for sure I was safe from any sneaky NullPointerException. If book, author or firstName are null I'll simply end up printing null and not have to...

Get just content of soap response in Groovy

xml,soap,groovy

SO you could do this: import groovy.xml.* def xml = '''<?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>'''.stripMargin() def result = XmlUtil.serialize(new...

Variable Substitution in logback groovy

java,variables,groovy,logback,logback-groovy

The System.getProperty() call retrieves properties set with -D on the java command line whereas in the .bat file you are setting shell/environment variables. Try using System.getenv() in the logback.groovy file....

Groovy's @CompileStatic and map constructors

groovy

As the CompileStatic documentation says: will actually make sure that the methods which are inferred as being called will effectively be called at runtime. This annotation turns the Groovy compiler into a static compiler, where all method calls are resolved at compile time and the generated bytecode makes sure that...

Groovy: Why can't the closure access itself?

groovy

You can not access the variable, to which the closure will be assigned to, since it pops into existence after the right hand side (or at least get's not captured). This is the reason, why the second example (the same code like in the groovy docs) works. The variable is...

Get nth child node without knowing node name Groovy

xml,groovy

How about: def text = <xml from above> def node = new XmlSlurper().parseText(text)[0] 5.times { node = node.children()[0] } assert node.name() == "node6" ...

Groovy generated constructor missing during compile

groovy,gradle

Analysis: This looks to me like a joint compilation issue. Most likely the transform @TupleConstructor runs after Groovy did create the .java stub files, causing the java compilation part to fail. It could have worked before, because you compiled the groovy part independent and then reused existing class files (no...

Java syntax to Groovy syntax

java,groovy,syntax

The following should work: import java.security.cert.* import javax.net.ssl.* TrustManager[] trustAllCerts = [ [ getAcceptedIssuers: { -> null }, checkClientTrusted: { X509Certificate[] certs, String authType -> }, checkServerTrusted: { X509Certificate[] certs, String authType -> } ] as X509TrustManager ] ...

Adding double in groovy

groovy

The reason your method didn't work is that addition operations goes from left to right. You can instead do it like this: println "answer "+(double)(abc1+abc2); ...

Changing and adding arguments of method before invocation

groovy,metaprogramming

Class Thing should implement GroovyInterceptable as below to make invokeMethod work: class Thing implements GroovyInterceptable { void display(String text) { println(text) } def invokeMethod(String name, args) { if(name == "display" && args.length == 0) { metaClass.getMetaMethod(name).invoke(this, "some text") } else { metaClass.getMetaMethod(name, args).invoke(this, args) } } } Thing thing =...

InvokeDynamic for Grails

grails,groovy,invokedynamic

Support was added in Grails 3 (https://jira.grails.org/browse/GRAILS-8339). The Groovy documentation lays out how to use it (http://www.groovy-lang.org/indy.html).

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

android,regex,groovy

You could do this: def s = 'some text %@ some text %@ some text' def newS = 1.with { idx -> s.replaceAll(/%@/, { v -> "%${idx++}\$s" }) } Which gives the output: 'some text %1$s some text %2$s some text' ...

What is “all” iterator?

android,groovy

Finally I found where all comes from. It is a method from Gradle api : https://github.com/gradle/gradle/blob/master/subprojects/core/src/main/groovy/org/gradle/api/internal/DefaultDomainObjectCollection.java

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

groovy

Very interesting scenario, indeed! I'd say that's because Groovy tries to cast the null value returned by println into int as defined by the interface. If you change return type of the method shout to void the problem goes away. The problem goes away if you approach it from the...

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

ant,groovy,javadoc,groovydoc

The following Ant task hack seems to produce reasonable results for Groovy 2.4.3's Groovydoc output. (At least I haven't found anything it has broken yet.) <replace dir="build/doc/groovy/api"> <replacefilter token="(java.lang.Object " value="("/> <replacefilter token=", java.lang.Object" value=", "/> <replacefilter token="java.lang." value=""/> <replacefilter token="java.util." value=""/> <!-- ... add more here ... --> </replace>...

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

mysql,jdbc,groovy,groovy-console

Solution: The driver has to be on the classpath. Reason: If you look into the DriverManager class you find code like this: Class.forName(driver.getClass().getName(), true, classLoader);. This is to check if the driver is accessible from your classloader context. And that context is determined by going back to the class that...

create email list of all users

groovy,jenkins,jenkins-scriptler

First of all you should know that Jenkins will not always be able to tell you whether the user exists or not. From Jenkins' javadoc: This happens, for example, when the security realm is on top of the servlet implementation, there's no way of even knowing if an user of...

Groovy replace node values in xml with xpath

xml,xpath,groovy

You can try using XmlSlurper instead probably it's an easy way. You can define your map using the node name as a key and the text as a value iterate over it changing the node in the Xml. You can use something similar the code below: import groovy.util.XmlSlurper import groovy.xml.XmlUtil...

null object error when calling code from script assertion - soapui

groovy,soapui

I am not seeing null object error now. The issue was that testRunner is not available in script assertion so we need to create it like this in script assertion and then pass it in the caller method. import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner import com.eviware.soapui.support.types.StringToObjectMap import com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext testCase = messageExchange.modelItem.testStep.testCase tcRunner = new...

Token error with groovy in NetBeans

netbeans,groovy,titan

This could be a number of things, but typically, an unexpected token error means you might have an extra comma, space, or character that doesn't belong there, like in the function call. If you know what types of params buildIndex expects, it can be determined if it's an issue with...

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

groovy,annotations

In Groovy, the syntax is the list one – i.e. with square brackets: @Retention(RetentionPolicy.RUNTIME) @Target([ElementType.TYPE, ElementType.FIELD]) public @interface AnnotExample { String name() } ...

@Path annotation: abstract resource in dropwizard

java,groovy,annotations,jetty,dropwizard

Ok, the problem was the "@Timed"-Annotation. Deleting it solved the problem.

sonar maven analysis only picks .java file

maven,groovy,sonarqube,sonarqube-5.0

Since it was a multi module project, I had to include the properties sonar.sources and sonar.tests in all the module's pom.xml file. <properties> <sonar.sources>src/main</sonar.sources> <sonar.tests>src/test</sonar.tests> </properties> ...

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

sql,sql-server,groovy

Or use a different quote character in the Groovy code: sql.eachRow("select top 1 " + "Country, " + "from dbo.Address where UPPER(Country) = 'JAPAN' ORDER BY NEWID()") or multi-line strings: sql.eachRow('''select top 1 Country, from dbo.Address where UPPER(Country) = 'JAPAN' ORDER BY NEWID()''') or multi-line strings with a margin: sql.eachRow('''select...