/r/groovy

Photograph via snooOG

A Subreddit for the Apache Groovy programming language

All things Apache Groovy Programming

/r/groovy

3,102 Subscribers

3

JSON slurper usage

Hi everyone, 1st post here
I'm writing my bachelor's degree thesis project in groovy and I need to parse a JSON file obtained from the dataset given by CAIDA Ark
Now the problem is I can't quite figure out the correct usage of jsonslurper.
The JSON I mentioned is a simple collection of ~30k records I need to parse and store in my classes for further data analysis, however I'm having a pretty rough time using json slurper, are there any suggestion/am I missing something? I'd appreciate any help

4 Comments
2024/05/08
14:59 UTC

2

Groovy resources and references

Hi, I've been trying to understand Groovy more in-depth.

My goal is to use Groovy in an OOP way to develop Jenkins pipelines. I am not using Declarative pipelines. However, I find resources lacking. I can easily find surface level information on most things, but if that is unable to resolve my issues, I don't have a deeper resource to delve through.

For example, I would like to implement a Strategy design pattern in my backend so that my pipeline can import the package and easily determine which test to run. This way, I can have many pipelines with drier code. However, I genuinely cannot find any resource explaining how to import a locally developed package into a Jenkins pipeline. This is baffling to me.

Even if I solve this issue, I feel that if I can't easily figure out something seemingly so basic, I probably need a book or a course on Groovy. Are there any recommendations? I was thinking about buying Groovy in Action, Second Edition.

2 Comments
2024/05/08
09:31 UTC

2

Is runtime class loading and runtime evaluation a vulnerability?

Hey all

One of groovy’s greatest strengths is DSLs. There is a lot of power there.

But is this inherently dangerous? Taking an arbitrary user input, then compiling it and running it — isn’t that just remote code execution as a feature?

http://groovy-lang.org/integrating.html#_groovy_integration_mechanisms

Are there any mitigations that can be done to avoid these issues when creating a DSL that is intended to be provided, or is the whole thing a bad idea?

Obviously one way is to limit the sources of these inputs to trusted sources (ex: file system only in a secure directory), but are there other ways? What about signature checking? Anything like that?

Would love to hear any experience people have building DSLs that are more than just on disk.

3 Comments
2024/04/07
22:30 UTC

6

Found a page of best free Groovy courses

Some of the best resources to learn Groovy that I refer to frequently.

0 Comments
2024/03/18
14:19 UTC

3

Collection of the best free Groovy resources

Some of the best resources to learn Groovy that I refer to frequently.

0 Comments
2024/03/04
19:06 UTC

3

ScriptRunner for JIRA - beginners guide (Part 2) | ScriptRunner Guides

0 Comments
2024/02/27
22:58 UTC

7

Groovy wrapper for Bld build-technology

https://github.com/paul-hammant/groovy-bld-prototype. First commit was the result of "bld create" for a Rife2 webapp. Second commit is the creation of a Groovy build grammer for Bld (that also deleted the old build file). Probably only about 5% complete, but just enough to match the functionality of the of the Java one it replaces. I'm not going to take it forward myself. As a (re)learning exercise for Groovy it was fun to do! To be fair I'd tried to get GPT4 to make it, but by-hand was better in the end.

0 Comments
2024/02/27
08:07 UTC

2

WMI time data to seconds

Hi,

I have some data that returns values in LDAP/FILETIME format. AD last login, machine SYSTEMUPDATE etc.

I have the below code that queries some WMI classes, including the one that returns SYSTEMUPTIME value. What I am trying to do is express this value in seconds first, then days later so show:

  • Uptime in Seconds: xyz
  • Uptime in Days: x.y days (rounded to 1 decimal place)

e.g. if SYSTEMUPTIME is 207360 seconds that is 2.4 days. Or 547940 seconds is 6.34189815 days (which would be rounded later on to 6.3 days).

I can't quite seem to get the right formula to convert SYSTEMUPTIME to seconds. In the below block, I just need it in seconds.

The real world SYSTEMUPTIME value returned on a sample machine is 133527726265000000.

Thanks

wmi_query_results.each
{ wmi_query_output ->
    wmi_query_output[0].each {
        key, value ->
            if(key == 'SYSTEMUPTIME') {
                //calculation goes here
            }
            println "${key}=${value}"
    }

}
0 Comments
2024/02/23
11:34 UTC

5

Groovy with springboot

I’m pretty good with groovy, but I’m not comfortable with java (groovy has spoiled me)

Any resources I can refer to (preferably a video tutorial or any course) to learn groovy with springboot ?

Also is it a good option to even consider developing springboot applications in groovy when compared to java or kotlin ?

4 Comments
2024/02/16
07:24 UTC

3

Groovy way to write batch inserts for MySQL?

Hi All! I'm not much of a groovy coder but some of our stuff at work is in Groovy. I'm currently rewriting some database stuff to achieve a specific behaviour and I want to be able to do multiple inserts in a single SQL statement something like the following:

INSERT INTO Person (Id, Name) VALUES (1, 'Amir' ), (2, 'Sofia'), (3, 'Aya')

I'm struggling to find a good groovy and safe way to create this kind of statement and so far the only solution I can come up with is building the strings myself, which feels more likely to let SQL injection vulnerabilities slip in, so I would rather avoid it.

I've been using the groovy.Sql.withBatch() but this seems to generate single insert statements rather than that batched behaviour with multiple values provided in a single line the way that I want.

Any suggestions for a good (and safe) way to achieve this?

Thanks

1 Comment
2024/01/30
17:26 UTC

7

Datasource.groovy externalized params vs hard coded in the file

I'm currently having a discussion with my team about externalizing our datasource info for an older groovy app. It has been my experience for the past 14 years that all modern web apps do this as it makes switching to a different db very easy without having to recompile. Their stance is that if they put all the environments in the datasource file we just run grails dev war or grails test war for whatever environment we need.

I don't have a ton of experience with Groovy but I've worked with Java for years, am I missing some understanding with Groovy here?

edit: Plus other benefits of having a place where you can make changes and not have to recompile.

4 Comments
2024/01/25
21:26 UTC

9

Groovy CLI utilities

I've been doing side projects (mostly around retro emulation) and its a lot of script work. I know groovy pretty well, but I tried doing some other langs. Bash is obviously horrid. Python/ruby/perl ...ech, I went back to Groovy

So I've been playing around with shebang'd / hashbang groovy scripts, and made a bunch of utility classes for filesystem / etc. I also wrote a groovy shebang script that works like this:

xg 'some groovy scriptlet' json

and it evals the scriptlet (the json arg serialized the response as json).

So of course after about a day of fun-coding this stuff, I wondered if there was anything more formal out there, or other ideas people had?

Also, the JVM warmup is just brutal, is there a way to speed that up? They are adhoc scripts so it isn't a huge deal.

6 Comments
2024/01/22
04:43 UTC

0

Looking for tutorials or books on writing DSLs in Java

Hello all
I need to write DSL for our internal needs , the code should be written in JAVA not groovy scripts
Trying to search for info and tutorials without any success .
Did any one knows where to find tutorials/code/books ?
Thanks

4 Comments
2023/11/30
15:26 UTC

3

How helpful are LLMs with Groovy?

Recently, many folks have been claiming that their Large Language Model (LLM) is the best at coding. Their claims are typically based off self-reported evaluations on the HumanEval benchmark. But when you look into that benchmark, you realize that it only consists of 164 Python programming problems.

This led me down a rabbit hole of trying to figure out how helpful LLMs actually are with different programming, scripting, and markup languages. I am estimating this for each language by reviewing LLM code benchmark results, public LLM dataset compositions, available GitHub and Stack Overflow data, and anecdotes from developers on Reddit. Below you will find what I have figured out about Groovy so far.

Do you have any feedback or perhaps some anecdotes about using LLMs with Groovy to share?

---

Groovy is the #26 most popular language according to the 2023 Stack Overflow Developer Survey.

Benchmarks

❌ Groovy is not one of the 19 languages in the MultiPL-E benchmark

❌ Groovy is not one of the 16 languages in the BabelCode / TP3 benchmark

❌ Groovy is not one of the 13 languages in the MBXP / Multilingual HumanEval benchmark

❌ Groovy is not one of the 5 languages in the HumanEval-X benchmark

Datasets

✅ Groovy is included in The Stack dataset

❌ Groovy is not included in the CodeParrot dataset

❌ Groovy is not included in the AlphaCode dataset

❌ Groovy is not included in the CodeGen dataset

❌ Groovy is not included in the PolyCoder dataset

Stack Overflow & GitHub presence

Groovy has 30,014 tagged questions on Stack Overflow

Groovy projects have had 132,381 PRs on GitHub since 2014

Groovy projects have had 108,265 issues on GitHub since 2014

Groovy projects have had 431,291 pushes on GitHub since 2014

Groovy projects have had 140,122 stars on GitHub since 2014

Anecdotes from developers

Figaf

And that it was possible to use the code created by the tool to generate some code that could be used to start your programming. This could save quite a bit of time for developers to use this as a starting point, and you don’t need to have a large experience to start coding in UDFs in Groovy. It is also interesting that it has much knowledge about what is going on in an SAP universe, I would have thought it was more difficult to get data about it.

u/West_Performance_129

Groovy is a great language with a ton of utility, and can scale like crazy! Write code as dynamic as you want, and choose to refactor into a more type-safe manner later. It's totally worth learning and having it in your toolkit. I program in it every day for many projects. All Java (99.9%) is also valid Groovy, so it's almost impossible not to understand and work with any Java code base you may come across once you get familiar with Groovy. ChatGPT and Github Co-pilot also write excellent Groovy code, which can aid you in learning, and just programming with it in general. It's still actively maintained, too! It's not going away an time soon.

Jamon Holmgren

When I was building react-native-colo-loco, I had to write a Gradle script, which is written in Groovy. I know a little Groovy, but not much. So I focused on writing precise, accurate comments, and let Copilot suggest lines of code. I could then lean on my development experience to pick up on patterns and syntax, and go from there.

---

Original source: https://github.com/continuedev/continue/tree/main/docs/docs/languages/groovy.md

Data for all languages I've looked into so far: https://github.com/continuedev/continue/tree/main/docs/docs/languages/languages.csv

3 Comments
2023/11/07
20:46 UTC

2

Semantics of the `"foo" in myMap`

I've seen people check for the key in a map with something like:

subreddits = [groovy: "r/groovy", cats: "r/cutecats"]

if("cats" in subreddits) {  
  // do something
}

What is the semantics of this "in" check? Does it use .containsKey() under the hood?

4 Comments
2023/11/07
14:20 UTC

5

which is best way to pick out a substring in a string?

Is there an advantage to any of those?

String fooBar = myBigString.substring(mySubStringStart, mySubStringEnd)
String fooBar = myBigString[mySubStringStart..mySubStringEnd]
6 Comments
2023/10/26
08:23 UTC

3

Defect ID in SF Not Passing to Jira Custom Field 'Defect ID'

Hello, we have the script below in our Jira Incoming Sync from Salesforce. We're using Exalate which uses Groovy script to pass values. We’re attempting to pass the Name to the Defect ID from SF to Jira. We input the lines (9 and 10) to identify if the Issue has the custom fields, if so to input the Name within Defect ID in the Issue. However, though the values are within the Remote (Salesforce) Replica, they are excluded in the Local (Jira) Replica. Are we missing something?

def defaultUser = nodeHelper.getUserByEmail("jira.salesforce@XXXXXX.com")
if (firstSync) {
    issue.projectKey = replica.JiraProjectKey__c
    issue.typeName = "Bug"
    if (replica.JiraProjectKey__c == "CIHS") {
        // Set default Epic Link
        issue.parentId = '138089'
    }
    if (issue.customFields.containsKey("Defect ID")) {
        issue.customFields."Defect ID".value = replica.Name
    }
    issue.summary = replica.summary
    issue.description = nodeHelper.toMarkDownFromHtml(replica.description)
    issue.assignee = defaultUser  // set the assignee to a default user
    try {
        issue.customFields."Step To Reproduce".value = replica.StepsToReproduce__c
    }
    catch (Exception ex) {}
    try {
        issue.customFields."Database".value = replica.DatabaseText__c
    }
    catch (Exception ex) {}
     
    try {
        issue.customFields."Schema".value = replica.Schema__c
    }
    catch (Exception ex) {}
    try {
        issue.customFields."SharePlex Server".value = replica.ShareplexServer__c
    }
    catch (Exception ex) {}
    try {
        issue.customFields."Account Login".value = replica.AccountLogin__c
    }
    catch (Exception ex) {}
    try {
        issue.customFields."Soffront Category".value = replica.Category__c?.value ?: ""
    }
    catch (Exception ex) {}
     
    syncHelper.syncBackAfterProcessing()
}
 
 
def reporterUser = nodeHelper.getUserByEmail(replica.OwnerEmail__c)
issue.reporter = reporterUser == null ? defaultUser : reporterUser
issue.environment = replica.EnvironmentText__c
 
if (issue.customFields.containsKey("Escalation")) {
    if (replica.IsEscalated__c) {
        issue.customFields."Escalation".value = ["Yes"]
    } else {
        issue.customFields."Escalation".value = ["No"]
    }
}
if (issue.customFields.containsKey("Escalation Reason")) {
    issue.customFields."Escalation Reason".value = replica.EscalationReason__c?.value ?: ""
}
 
if (issue.customFields.containsKey("Build Break")) {
    if (replica.IsPostRelease__c) {
        issue.customFields."Build Break".value = ["Yes"]
    } else {
        issue.customFields."Build Break".value = ["No"]
    }
}
 
issue.attachments  = attachmentHelper.mergeAttachments(issue, replica) 

1 Comment
2023/10/03
20:16 UTC

3

What is the recommended way to install Groovy on Ubuntu?

Hello,

I use Ubuntu 23.04 and I would like to try coding in Groovy.

On the official site, it is explained how to install it with snap or SDKMAN. But I also see it available with apt or aptitude.

Is there a difference when installing with on method rather than another?

9 Comments
2023/10/03
08:04 UTC

11

Is Groovy still worth learning for a beginner in 2023?

(I already posted this publication on another subreddit, but it was removed. So I post it again here.)

I've got the opportunity to follow a training based on Groovy and Grails.

I just had a look at the Groovy official website and it looks pretty interesting to me since I already have some notions of Java.

But then I did not find any job offer in my area mention either Groovy or Grails.

So, is it still worth taking the course?

Do Groovy and Grails present any special interest for a novice web developer? Or would you recommend me to stick with Java and Spring or even to try Kotlin?

36 Comments
2023/09/17
07:38 UTC

0

Ssslick -- Stormy Monday

0 Comments
2023/08/09
11:50 UTC

6

Is there any other way to run Groovy ?

hi,

is there any project to compile groovy with llvm or to js ?

just curious

6 Comments
2023/07/23
12:59 UTC

10

@Grab thing is so cool

i dont know why i never saw this on any other language it seems so intuitive.

i can just ship a simple script and it would download the packages in the runtime and run.

why doesnt other languages implement this ?

1 Comment
2023/07/09
22:21 UTC

2

Me deparei com a necessidade de aprender a linguagem groovy no trabalho, mas não tenho nenhum experiência em programação.

Aberto a qualquer sugestão, seja indicação de curso, livros e etc..

0 Comments
2023/07/05
11:52 UTC

3

Help needed: Groovy Apache Eclipse connection

Greetings.

I am going crazy. I am currently learning to code for a job and wanted to build a simple device at home in Eclipse. The language i am supposed to train is Groovy, so i try to use that, but since Java works in groovy script too, i help myself with those solutions, as there are more available.

I try to create a program atm that enters and reads data from a spread sheet.
For that i try to find a way to load apache POIs into Eclipse for Groovy Projects, or even Java ones to read. I dont know how to do that. All tutorials are too old. ChatGPT spits out answers that dont work. The Keywords that it says im supposed to import are not referenced. The .jar to use as source is not findable.

I now used simply the whole .zip as a source, hoping Eclipse would just find what it needs itself, but no.

I need serious help that is not outdated and very beginner friendly. Can someone help me?

1 Comment
2023/06/17
14:25 UTC

4

Hunting down a performance bug

I had the misfortune to figure out why Groovy 2.5.x was 40% slower compared to 2.4.x. Now let me say, our system is old and complicated. Millions of lines and highly customizable. Years ago we introduced GROOVY as an expression language and it works, for the most part. But edge cases show up, like clients running queries that have 70+ expressions per row for 9 million rows. And after a week of research I learned it was a simple “feature” ruining performance. The new field attribute stuff was the slow down, since we never told the clients to use the “def” keyword, it was searching the class for any getters/setters. And we had about 130 custom functions appended to each script, so it was looping a lot. I found a work around, changing out the base class with one that had the 2.4.x guts, but it would be nice to disable those fancy features and not have to override the class file.

3 Comments
2023/06/03
19:29 UTC

8

🏆 Trending and Awesome Groovy open source projects

Hello everyone,

I just want to present you some interesting lists and rankings related to the Groovy open source ecosystem:

- Top Contributors (global or by country): https://opensource-heroes.com/contributors?language=groovy
- Trending projects: https://opensource-heroes.com/discover/groovy (based on GitHub stars increase)
- Awesome projects: https://opensource-heroes.com/awesome/groovy (we plan to add soon a new feature to allow everyone to contribute to that list directly from the site)

You can also find "stars" history in the detail page of some repos (it will be available soon for all Groovy repos, we're still processing some data!)

Hope you find them useful! Any feedback is really appreciated. Please note that be are still in beta 🙏 We want to build a platform that allows everybody to easily explore the open source world! We are about to release a new "Interviews" section with open source contributors explaining their journey, motivations, challenges, ... Sign-up and to tell us your Groovy journey!

2 Comments
2023/05/28
19:56 UTC

3

Code duplication in docker node

My jenkinsfile pipeline has a few stages and each stage is using a different executer node. I'm using docker plugin, and I find myself writing at the beginning of every stage the same node docker configuration. Is there a way I can save the docker configuration as a parameter and use it every time to prevent code duplication?

0 Comments
2023/05/14
17:15 UTC

5

Learning Groovy for Jenkins pipelines.

Hi folks! I am an infrastructure guy using PowerShell for the last 5 or 6 years but recently been exposed to Jenkins pipelines of which I feel quite out of my depth. There's one guy at work who does all the Jenkins stuff so I want to step up and be able to do it myself. Do you guys have any recommended books to learn Groovy in the context of Jenkins pipelines?

I'm talking really basic, parameter declarations, arrays, strings, interpolation...that kind of stuff.

I'm not a developer and don't need to develop in software in Java but I do need to script.

10 Comments
2023/05/13
10:36 UTC

Back To Top