Workaround for lack of generators/yield keyword in Groovy - groovy

Wondering if there is a way I can use sql.eachRow like a generator, to use it in a DSL context where a Collection or Iterator is expected. The use case I'm trying to go for is streaming JSON generation - what I'm trying to do is something like:
def generator = { sql.eachRow { yield it } }
jsonBuilder.root {
status "OK"
rows generator()
}

You would need continuation support (or similiar) for this to work to some extend. Groovy does not have continuations, the JVM also not. Normally continuation passing style works, but then the method eachRow would have to support that, which it of course does not. So the only way I see is a makeshift solution using threads or something like that. So maybe something like that would work for you:
def sync = new java.util.concurrent.SynchronousQueue()
Thread.start { sql.eachRow { sync.put(it) } }
jsonBuilder.root {
status "OK"
rows sync.take()
}
I am not stating, that this is a good solution, just a random consumer-producer-work-around for your problem.

Related

Kotlin : How to Class().fooA().fooB()

I am currently taking my code skill to the more advanced level in order to achieved "easier maintain code", I got this problem
val attachView = Custom()
attachView.setRoot(root)
attachView.setAdded(add)
attachView.build()
Those code, as you can see I repeatedly calling attachView over and over again. it works fine, but I want it to be more compact by eliminating calling attachView multiple time. My final aim is just like this
Custom().setRoot().setAdded().build()
is there any method that I must to know in order to build something like that ?
No external method will give you such semantics:
Custom().setRoot().setAdded().build()
It can be achieved by changing the internals of Customer class. So that the setRoot() and setAdded() will return this. Like fun setRoot(root: Root): Custom, etc.
With Kotlin you can use several functions to avoid adding attachView. before methods call. Like
-with
with(Custom()) {
setRoot(root)
setAdded(add)
build()
}
-apply
Custom().apply {
setRoot(root)
setAdded(add)
build()
}
val attachView = Custom().apply {
setRoot(root)
setAdded(add)
build()
}
If you really want a one-liner you can do this
val attachView = Custom().apply { setRoot(root); setAdded(add); build() }

What is the difference between passing a Map and using `body.resolveStrategy = Closure.DELEGATE_FIRST`

These two examples of encapsulated pipelines get their pipelineParams from two different methods, however it is not readily clear why one is preferable to the other.
What is the ramification of using
def call(body) {
// evaluate the body block, and collect configuration into the object
def pipelineParams= [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = pipelineParams
body()
pipeline {
echo pipelineParams.name
}
}
vs using
def call(Map pipelineParams) {
pipeline {
echo pipelineParams.name
}
}
Example code from https://jenkins.io/blog/2017/10/02/pipeline-templates-with-shared-libraries/
The difference is that in the first case, using a pipeline looks like declarative configuration. It's a so-called builder strategy in terms of DSL:
myDeliveryPipeline {
branch = 'master'
scmUrl = 'ssh://git#myScmServer.com/repos/myRepo.git'
...
}
Whereas in the second case, applying a pipeline looks like imperative code, i.e. it's a regular function call:
myDeliveryPipeline(branch: 'master', scmUrl: 'ssh://git#myScmServer.com/repos/myRepo.git', ...)
There is also explanation in the official Jenkins doc:
There is also a “builder pattern” trick using Groovy’s Closure.DELEGATE_FIRST, which permits Jenkinsfile to look slightly more like a configuration file than a program, but this is more complex and error-prone and is not recommended.
Personally, I can't say that I'm not recommending the DSL approach. The doc doesn't recommend this because it's a bit more complex and can be error-prone

How to reuse code block which describe similiar ant build logic in groovy?

How to reuse code block which describe similiar ant build logic in groovy?
If we have build logic which was implemented by Groovy AntBuilder, just like code below:
ant.someTask(attr1:value1, attr2:value2) {
configuration1(param1:args1, param2:args2){
similiarStructure(additionalArgs:aaa){
setting1(param5:value5) {
//...blah blah blah
}
//further more settings, may be or may be not the same with similiarStructure below
}
}
configuration2(param3:args3, param4:args4){
similiarStructure(additionalArgs:aaa){
setting1(param5:value5) {
//...blah blah blah
}
//further more settings, may be or may be not the same with similiarStructure below
}
}
}
Are there any ways to reuse Groovy AntBuilder code block, which could brief the statment in configuration2 ?
I've try to predefine closures and inject them in both configuration,
but it fails with property not found exception while initializing closure.
I'll provide two answers so you can select which one is more appropriate for your use case and test it. The solutions depend on at what level you want the shared config.
If you want a more general purpose solution that allows you to share the whole of the similarStructure block, you need to perform some more advanced work. The trick is to ensure that the delegate of the shared configuration closure is set appropriately:
def sharedConfig = {
similarStructure(additionalArgs:aaa) {
setting1(param5:value5) {
//...blah blah blah
}
}
}
ant.someTask(attr1: value1, attr2: value2) {
configuration1(param1:args1, param2:args2){
applySharedConfig(delegate, sharedConfig)
}
configuration2(param3:args3, param4:args4){
applySharedConfig(delegate, sharedConfig)
}
}
void applySharedConfig(builder, config) {
def c = config.clone()
c.resolveStrategy = Closure.DELEGATE_FIRST
c.delegate = builder
c.call()
}
Although the applySharedConfig() method seems ugly, it can be used to share multiple configurations across different tasks.
One thing to bear in mind with this solution is that the resolveStrategy of the closure can be very important. I think both DELEGATE_FIRST and OWNER_FIRST (the default) will work fine here. If you run into what appear to be name resolution problems (missing methods or properties) you should try switching the resolution strategy.
I'll provide two answers so you can select which one is more appropriate for your use case and test it. The solutions depend on at what level you want the shared config.
If you are happy to simply share the closure that goes with similarStructure, then the solution is straightforward:
def sharedConfig = {
setting1(param5:value5) {
//...blah blah blah
}
}
ant.someTask(attr1: value1, attr2: value2) {
configuration1(param1:args1, param2:args2) {
similarStructure(additionalArgs:aaa, sharedConfig)
}
configuration2(param3:args3, param4:args4) {
similarStructure(additionalArgs:aaa, sharedConfig)
}
}
The method that is similarStructure should ensure that the sharedConfig closure is properly configured. I haven't tested this, so I'm not entirely sure. The disadvantage of this approach is that you have to duplicate the similarStructure call with its arguments.

how to cast/convert a Collection<T> to an Collection<U>

is there an easy way to do this whiteout using a loops?
how my classes looks like
class T
{
//some stuff
}
class U
{
//some stuff
public U(T myT)
{
//some stuff
}
}
i found on my research the following method List.ConvertAll but it is only for List now i want to know if someone knows a way to achieve this for Collections.
i would prefer a generic solution but anything that solve this in a performant way.
You can use a LINQ select for this:
var enumerableOfU = collectionOfT.Select(t => new U(t));
If you want to enumerate enumerableOfU multiple times, you should append .ToList() or .ToArray() after the Select.
Please note that this internally still uses loops, but you don't have to write it yourself.

Intercepting ClassCastException's in Groovy?

I have a lot of code using and expecting java.util.Date which I would like to migrate to org.joda.time.LocalDate. The problem is that most of the code is dynamically typed.
So I wonder if there is any groovy way to intercept the ClassCastException, do the conversion at runtime (instead of letting the exception bubble up) and log the operation (so I could fix the code).
Example:
import org.joda.time.LocalDate
def someMethod(date) {
println date.year()
}
// this call is ok
someMethod(new LocalDate())
// this call raises an exception
someMethod(new Date())
I don't want to modify the code above, like surrounding the second call with a try-catch and recalling with the right type. I wanted a way to do this globally.
Idea 1:
You can benefit from Groovy multimethods: you write a method overload for the JodaTime's and let the java.util.Date method be chosen when it is a dynamic method parameter:
def someMethod(date) {
println date.year()
}
My advice is to write in this class a overload of these methods doing the conversion:
def someMethod(LocalDate date) {
someMethod date.convertToJavaDate()
}
If you don't have access to that code, you can use metaprogramming.
Idea 2:
If you have a huge library, my guess is that you are better mixing JodaTime class. You will get a power benefit from duck typing. You will need to know which members from java.util.Date are called and reroute them to Joda's own methods:
class LocalDateMixin {
def year() { this[Calendar.YEAR] }
}
LocalDate.metaClass.mixin LocalDateMixin
You can also apply the metaprogramming using extension methods.

Resources