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) :...
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...
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,...
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....
THe lines: groupId ${group} artifactId 'myapp' version ${version} Are not valid groovy, and should probably be: groupId "${group}" artifactId 'myapp' version "${version}" ...
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...
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...
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...
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...
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...
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,...
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...
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...
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...
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() ...
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...
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...
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...
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....
You have changed months with days. should be: String d="20/05/2015"; instead of String d="05/20/2015"; ...
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...
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...
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;...
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',...
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....
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...
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.
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.
I had this one before and it was due to an environment classpath variable set to point to an invalid jar
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,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...
Groovy parses the source code with antlr via the groovy grammar description, then generates bytecode using asm It does not require javac...
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} ...
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....
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 -> ...
java,multidimensional-array,arraylist,groovy
Looks like you forgot keyword static for method.
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. ...
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...
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_"...
toURL() invoked on String comes from this class, not from DefaultGroovyMethods, so everything works fine and correct method is invoked.
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...
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......
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...
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...
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...
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 {...
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...
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...
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...
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...
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...
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...
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......
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...
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...
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...
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...
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....
try this SELECT * FROM [db].[dbo].[TABLE] WHERE [ID] LIKE '%'+convert(varchar(50),:id)+'%' ...
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...") ...
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' ...
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 } } ...
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"...
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....
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...
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...
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...
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...
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....
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...
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...
How about: def text = <xml from above> def node = new XmlSlurper().parseText(text)[0] 5.times { node = node.children()[0] } assert node.name() == "node6" ...
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...
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 ] ...
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); ...
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 =...
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).
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' ...
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
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...
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>...
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...
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...
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...
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...
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...
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() } ...
java,groovy,annotations,jetty,dropwizard
Ok, the problem was the "@Timed"-Annotation. Deleting it solved the problem.
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> ...
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...