Guillaume Laforge presents on creating domain-specific languages with Groovy. He discusses how DSLs can help bridge communication between developers and subject matter experts by using a more expressive shared language. He provides examples of Groovy's capabilities for building DSLs, including its flexible syntax, optional typing, native constructs, closures, and dynamic metaprogramming features. He also covers integrating DSLs into applications and considerations for designing custom DSLs.
In this Meetup Victor Perepelitsky - R&D Technical Leader at LivePerson leading the 'Real Time Event Processing Platform' team , will talk about Java 8', 'Stream API', 'Lambda', and 'Method reference'.
Victor will clarify what functional programming is and how can you use java 8 in order to create better software.
Victor will also cover some pain points that Java 8 did not solve regarding functionality and see how you can work around it.
Presentation on various definitions for JSON including JSON-RPC, JSPON, JSON Schema, JSONP and tools for working these definitions including Persevere client and server..
In this Meetup Victor Perepelitsky - R&D Technical Leader at LivePerson leading the 'Real Time Event Processing Platform' team , will talk about Java 8', 'Stream API', 'Lambda', and 'Method reference'.
Victor will clarify what functional programming is and how can you use java 8 in order to create better software.
Victor will also cover some pain points that Java 8 did not solve regarding functionality and see how you can work around it.
Presentation on various definitions for JSON including JSON-RPC, JSPON, JSON Schema, JSONP and tools for working these definitions including Persevere client and server..
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
This Edureka "Node.js tutorial" will help you to learn the Node.js fundamentals and how to create an application in Node.js. Node.js is an open-source, cross-platform JavaScript runtime environment for developing a diverse variety of server tools and applications. Below are the topics covered in this tutorial:
1) Client Server Architecture
2) Limitations of Multi-Threaded Model
3) What is Node.js?
4) Features of Node.js
5) Node.js Installation
6) Blocking Vs. Non – Blocking I/O
7) Creating Node.js Program
8) Node.js Modules
9) Demo – Grocery List Web Application using Node.js
NextJS - Online Summit for Frontend Developers September 2020Milad Heydari
Developers may think launching SSR application with react must be painful. In this talk, i was describe a simple SSR method, does a deep dive into SSR with Next.js, and how i using it. it's about some useful tips about challenges, optimizations, writing clean codes beside do’s and don’ts in Next.js and cover many of the Next.js features to accomplish a great website application with acceptable performance and speed.
React Global Online Summit for Frontend Developers.
September 2020
https://react.geekle.us/september-2020
https://youtu.be/fkp5_5rezsE
Slides of my talk at Coding-Berlin November Meetup on 01.11.2017 (https://www.meetup.com/CODING-BERLIN/events/244169839). Also have a look at the demo repo at Github: https://github.com/coding-berlin/vuejs-demo
Whether you're a MongoDB professional or totally new to document databases, our MongoDB performance success factors & evaluation framework has something for you,
Curious about MongoDB performance?
Mydbops CTO, Manosh Malai illustrates the secret sauce for MongoDB performance best practices & analysis tool.
In this talk, Jamie will demonstrate some core principles of a minimalist React framework called Next.js - We’ll also learn why SEO isn’t the only benefit of Server Side Rendering in React.
Angular 2 is now in Beta. Reactive Programming techniques are used to write the Angular 2 framework. The same APIs and techniques are exposed to Angular 2 developers for application development.
This talk, by Geoff Filippi, will start with a brief overview of Reactive Programming. We will define and discuss the Observer Design Pattern. Observables are implemented in RxJS and are under consideration for standardization in ES2016. We will compare Observables, Promises, Events and callbacks. We will also discuss how Promises, Events and callbacks can be bridged into Observables.
Finally we will discuss how RxJS is used to implement Angular 2. We will explore how Observables are used in change detection and ngZone, Http, Async Facade and Forms. We will also discuss how to make use of RxJS and Observables in our Angular 2 applications.
Video: https://www.youtube.com/watch?v=SfrEThI_m7g
Source code: https://github.com/Alotor/2015-greach-groovy-dsls
Behind each good Groovy library or framework there is a good DSL (Domain Specific Language). And this is not by chance, one of the most exciting features of Groovy is its amazing syntax flexibility and metaprogramming capabilities that allow us do things in a highly expressive manner through DSLs.
In this talk I’ll explain the basics of doing DLS’s with Groovy. What you’ll need to start and what to investigate deeper. Also, we’ll check some of the most well known ones libraries like Spock, Gradle or Grails so you can use their techniques in your own Groovy projects.
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
This Edureka "Node.js tutorial" will help you to learn the Node.js fundamentals and how to create an application in Node.js. Node.js is an open-source, cross-platform JavaScript runtime environment for developing a diverse variety of server tools and applications. Below are the topics covered in this tutorial:
1) Client Server Architecture
2) Limitations of Multi-Threaded Model
3) What is Node.js?
4) Features of Node.js
5) Node.js Installation
6) Blocking Vs. Non – Blocking I/O
7) Creating Node.js Program
8) Node.js Modules
9) Demo – Grocery List Web Application using Node.js
NextJS - Online Summit for Frontend Developers September 2020Milad Heydari
Developers may think launching SSR application with react must be painful. In this talk, i was describe a simple SSR method, does a deep dive into SSR with Next.js, and how i using it. it's about some useful tips about challenges, optimizations, writing clean codes beside do’s and don’ts in Next.js and cover many of the Next.js features to accomplish a great website application with acceptable performance and speed.
React Global Online Summit for Frontend Developers.
September 2020
https://react.geekle.us/september-2020
https://youtu.be/fkp5_5rezsE
Slides of my talk at Coding-Berlin November Meetup on 01.11.2017 (https://www.meetup.com/CODING-BERLIN/events/244169839). Also have a look at the demo repo at Github: https://github.com/coding-berlin/vuejs-demo
Whether you're a MongoDB professional or totally new to document databases, our MongoDB performance success factors & evaluation framework has something for you,
Curious about MongoDB performance?
Mydbops CTO, Manosh Malai illustrates the secret sauce for MongoDB performance best practices & analysis tool.
In this talk, Jamie will demonstrate some core principles of a minimalist React framework called Next.js - We’ll also learn why SEO isn’t the only benefit of Server Side Rendering in React.
Angular 2 is now in Beta. Reactive Programming techniques are used to write the Angular 2 framework. The same APIs and techniques are exposed to Angular 2 developers for application development.
This talk, by Geoff Filippi, will start with a brief overview of Reactive Programming. We will define and discuss the Observer Design Pattern. Observables are implemented in RxJS and are under consideration for standardization in ES2016. We will compare Observables, Promises, Events and callbacks. We will also discuss how Promises, Events and callbacks can be bridged into Observables.
Finally we will discuss how RxJS is used to implement Angular 2. We will explore how Observables are used in change detection and ngZone, Http, Async Facade and Forms. We will also discuss how to make use of RxJS and Observables in our Angular 2 applications.
Video: https://www.youtube.com/watch?v=SfrEThI_m7g
Source code: https://github.com/Alotor/2015-greach-groovy-dsls
Behind each good Groovy library or framework there is a good DSL (Domain Specific Language). And this is not by chance, one of the most exciting features of Groovy is its amazing syntax flexibility and metaprogramming capabilities that allow us do things in a highly expressive manner through DSLs.
In this talk I’ll explain the basics of doing DLS’s with Groovy. What you’ll need to start and what to investigate deeper. Also, we’ll check some of the most well known ones libraries like Spock, Gradle or Grails so you can use their techniques in your own Groovy projects.
The list of open java online courses from the world famous universities. All courses are actual and available using Coursera online education platform.
Gisting is an implementation of Google\'s MapReduce framework for processing and extracting useful information from very large data sets. At the time of this writing, the code is available for PREVIEW at http://github.com/mchung/gisting. I am currently working to release this framework for general usage.
A guest lecture I gave for the "Internet Technology" course at my old University (Bath). I tried to pull together all of the things I wish I'd been told before I started building things on the Web.
Fort de ses 1.7 millions de téléchargements l'an passé, Groovy continue son bonhomme de chemin en tête parmi les langages de programmation alternatifs pour la JVM.
Groovy 2.0, sorti l'an passé, introduisait dans son offre de la modularité, le support de JDK 7 au niveau syntaxique avec "Project Coin" autant qu'au niveau JVM avec l'utilisation d'"invoke dynamic", et proposait des fonctionnalités de typage et de compilation statique.
Groovy 2.1, quant à lui, s'appuie sur ces bases pour compléter le support d'"invoke dynamic" pour plus de performances. Il propose des améliorations permettant de documenter, d'aider les IDEs, et de vérifier statiquement les Domain-Specific Languages construits avec Groovy. Vous pourrez créer des méta-annotations regroupant d'autres annotations, pour éviter l'annotation "hell". Et enfin, vous irez encore plus loin dans la customisation du compilateur !
Accrochez votre ceinture, paré au décollage !
"Groovy 2.0 and beyond" presentation given at the Groovy/Grails eXchange conference.
Video can be seen here:
http://skillsmatter.com/podcast/groovy-grails/keynote-speech
Groovy Domain Specific Languages - SpringOne2GX 2012Guillaume Laforge
Paul King, Andrew Eisenberg and Guillaume Laforge present about implementation of Domain-Specific Languages in Groovy, while at the SpringOne2GX 2012 conference in Washington DC.
Groovy update - S2GForum London 2011 - Guillaume LaforgeGuillaume Laforge
Groovy Update: what's new in 1.8 and what's coming in 1.9
The Groovy Development team is releasing Groovy 1.8, and this session will cover the new features including improved support for advanced and readable Domain-Specific Languages thanks to Groovy 1.8's "Extended Command Expressions", new performance improvements in the area of integer arithmetics, built-in support for parsing and producing JSON payloads, new AST transformations and now GPars come already bundled.
Groovy DSLs - S2GForum London 2011 - Guillaume LaforgeGuillaume Laforge
Design Your Own Domain Specific Language
This talk examines how dynamic languages in general and Groovy in particular provide toos to help design programming languages that are closer of the natural language of the target subject matter expert. It offers many features that allow you to create embedded DSLs: Closures, compile-time and run-time metaprogramming, operator overloading, named arguments, a more concise and expressive syntax and more.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Knowledge engineering: from people to machines and back
Practical Groovy DSL
1. Guillaume Laforge / Groovy Project Manager / SpringSource
Practical Domain-Specific
Languages with Groovy
All the techniques to create your own DSL.
1
2. Guillaume Laforge
• Groovy Project Manager
• JSR-241 Spec Lead
• Head of Groovy Development
at SpringSource
• Initiator of the Grails framework
• Co-author of Groovy in Action
• Speaker: JavaOne, QCon, JavaZone, Sun TechDays,
Devoxx, The Spring Experience, JAX, Dynamic
Language World, IJTC, and more...
3. A few words about Groovy
• Groovy is a dynamic language for the JVM
• with a Meta Object Protocol
• compiles directly to bytecode, seamless Java interop
• Open Source ASL 2 project hosted at Codehaus
• Relaxed grammar derived from Java 5
• + borrowed good ideas from Ruby, Python, Smalltalk
• Fast... for a dynlang on the JVM
• Closures, properties, optional typing, BigDecimal
by default, nice wrapper APIs, and more...
4. a
d
n
e
g
A • The context and
the usual issues we face
• Some real-life examples of
Domain-Specific Languages
• Groovy’s DSL capabilities
• Integrating a DSL
in your application
• Considerations to remember
when designing your own DSL
7. Developer producing
LOLCODE
HAI
CAN HAS STDIO?
I HAS A VAR
IM IN YR LOOP
UP VAR!!1
VISIBLE VAR
IZ VAR BIGGER THAN 10?
KTHXBYE
IM OUTTA YR LOOP
KTHXBYE
11. DSL: a potential solution?
• Use a more expressive language than a general purpose one
• Share a common metaphore of understanding between developers
and subject matter experts
• Have domain experts help with the design of the business logic of
an application
• Avoid cluttering business code with too much boilerplate
technical code
• Cleanly separate business logic from application code
• Let business rules have their own lifecycle
18. a
d
n
e
g
A • The context and
the usual issues we face
• Some real-life examples of
Domain-Specific Languages
• Groovy’s DSL capabilities
• Integrating a DSL
in your application
• Considerations to remember
when designing your own DSL
19. A collection of DSLs
• In our everyday life, we’re surrounded by DSLs
• Technical dialects
• Notations
• Business languages
28. Real-life Groovy examples
• Anti-malaria drug resistance simulation
• Human Resources employee skills representation
• Insurance policies risk calculation engine
• Loan acceptance rules engine for a financial platform
• Mathematica-like lingua for nuclear safety simulations
• Market data feeds evolution scenarios
• and more...
29. a
d
n
e
g
A • The context and
the usual issues we face
• Some real-life examples of
Domain-Specific Languages
• Groovy’s DSL capabilities
• Integrating a DSL
in your application
• Considerations to remember
when designing your own DSL
30. A flexible & malleable syntax
• No need to write full-blown classes, use scripts
• Optional typing (def)
• in scripts, you can even omit the def keyword
• Native syntax constructs
• Parentheses & semi-colons are optional
• Named arguments
• BigDecimal by default for decimal numbers
• Closures for custom control structures
• Operator overloading
31. Scripts vs classes
• Hide all the boilerplate technical code
• an end-user doesn’t need to know about classes
• public class Rule {
public static void main(String[] args) {
System.out.println(“Hello”);
}
}
• println “Hello”
32. Optional typing
• No need to bother with types or even generics
• unless you want to!
• Imagine an interest rate lookup table method
returning some generified type:
• Rate<LoanType, Duration, BigDecimal>[]
lookupTable() { ... }
def table = lookupTable()
• No need to repeat the horrible generics type info!
33. Native syntax constructs
• Lists
• [Monday, Tuesday, Wednesday]
• Maps
• [CA: ‘California’, TX: ‘Texas’]
• Ranges
• def bizDays = Monday..Friday
• def allowedAge = 18..65
• You can create your own custom ranges
34. Optional parens & semis
• Make statements and expressions
look more like natural languages
• move(left);
•move left
35. Named arguments
• In Groovy you can mix named and unnamed
arguments for method parameters
• named params are actually put in a map parameter
• plus optional parens & semis
• take 1.pill,
of: Chloroquinine,
after: 6.hours
• Corresponds to a method signature like:
• def take(Map m, MedicineQuantity mq)
36. BigDecimal by default
• Main reason why financial institutions often decide to
use Groovy for their business rules!
• Although these days rounding issues are overrated!
• Java vs Groovy for a simple interpolation equation
• BigDecimal uMinusv = c.subtract(a);
BigDecimal vMinusl = b.subtract(c);
BigDecimal uMinusl = a.subtract(b);
return e.multiply(uMinusv)
.add(d.multiply(vMinusl))
.divide(uMinusl, 10, BigDecimal.ROUND_HALF_UP);
• (d * (b - c) + e * (c - a)) / (a - b)
37. Custom control structures,
thanks to closures
• When closures are last, they can be put “out” of the
parentheses surrounding parameters
• unless (account.balance > 100.euros,
{ account.debit 100.euros })
• unless (account.balance > 100.euros) {
account.debit 100.euros
}
• Signature def unless(boolean b, Closure c)
38. Operator overloading
• Currency amounts
a+b a.plus(b)
•
a-b a.minus(b)
15.euros + 10.dollars
a*b a.multiply(b)
• Distance handling
a/b a.divide(b)
a%b a.modulo(b)
• 10.kilometers - 10.meters
a ** b a.power(b)
a|b a.or(b)
• Workflow, concurrency
a&b a.and(b)
•
a^b a.xor(b) taskA | taskB & taskC
a[b] a.getAt(b)
• Credit an account
a << b a.leftShift(b)
a >> b a.rightShift(b)
• account << 10.dollars
+a a.positive()
account += 10.dollars
-a a.negative()
account.credit 10.dollars
~a a.bitwiseNegate()
40. Groovy’s MOP
• All the accesses to methods, properties, constructors,
operators, etc. can be intercepted thanks to the MOP
• While Java’s behavior is hard-wired at compile-
time in the class
• Groovy’s runtime behavior is adaptable at
runtime through the metaclass.
• Different hooks for changing the runtime behavior
• GroovyObject, custom MetaClass implementation,
categories, ExpandoMetaClass
41. GroovyObject
• All instances of classes created in Groovy implement
the GroovyObject interface:
• getProperty(String name)
• setProperty(String name, Object value)
• invokeMethod(String name, Object[]
params)
• getMetaClass()
• setMetaClass(MetaClass mc)
• A GO can have “pretended” methods and properties
42. MetaClass
• The core of Groovy’s MOP system
• invokeConstructor()
• invokeMethod() and invokeStaticMethod()
• invokeMissingMethod()
• getProperty() and setProperty()
• getAttribute() and setAttribute()
• respondsTo() and hasProperty()
• MetaClasses can change the behavior of existing third-
party classes — even from the JDK
43. ExpandoMetaClass
• A DSL for MetaClasses!
• MoneyAmount.metaClass.constructor = { ... }
Number.metaClass.getDollars = { ... }
Distance.metaClass.toMeters = { ... }
Distance.metaClass.static.create = { ... }
• To avoid repetition of Type.metaClass, you can pass a
closure to metaClass { ... }
• The delegate variable in closure represents the
current instance, and it the default parameter
45. The Groovy MarkupBuilder
• def mkp = new MarkupBuilder()
mkp.html {
head {
title “Groovy in Action”
}
body {
div(width: ‘100’) {
p(class: ‘para) {
span “Best book ever!”
}
}
}
}
46. A builder for HR
• softskills {
ideas {
capture 2
formulate 3
}
...
}
knowhow {
languages {
java 4
groovy 5
}
...
}
47. A builder for HR
• softskills {
ideas {
capture 2
formulate 3
}
...
}
knowhow {
languages {
java 4
groovy 5
}
...
}
48. Builders
• Builders are...
• a mechanism for creating any tree-structered graph
• the realization of the GoF builder pattern at the
syntax level in Groovy
• simply a clever use of chained method invocation,
closures, parentheses omission, and use of the
GroovyObject methods
• Existing builders
• XML, Object graph, Swing, Ant, JMX, and more...
49. The clever trick
• GroovyObject#invokeMethod() is used to catch all
non-existing method calls in the context of the
builder
• The nesting of closures visually shows the level of
nesting / depth in the tree
• builder.m1(attr1:1, attr2:2, { builder.m2(..., {...}) }
becomes equivalent to
builder.m1(attr1:1, attr2:2) { m2(...) {...} }
thanks to parens omission
50. Adding properties to numbers
• Three possible approaches
• create a Category
• a category is a kind of decorator for default MCs
• create a custom MetaClass
• a full-blown MC class to implement and to set on
the POGO instance
• use ExpandoMetaClass
• friendlier DSL approach but with a catch
51. With a Category
• class DistanceCategory {
static Distance getMeters(Integer self) {
new Distance(self, Unit.METERS)
}
}
use(DistanceCategory) {
100.meters
}
• Interesting scope: thread-bound & lexical
• But doesn’t work across the hierarchy of classes
• ie. subclasses won’t benefit from the new property
52. With an ExpandoMetaClass
• Number.metaClass.getMeters = {->
new Distance(delegate, Unit.METERS)
}
100.meters
• Works for the class hierarchy for POJOs, and a flag
exists to make it work for POGOs too
• But the catch is it’s really a global change, so beware
EMC enhancements collisions
54. AST Transformations
• Two kinds of transformations
• Global transformations
• applicable to all compilation units
• Local transformations
• applicable to marked program elements
• using specific marker annotations
55. Example #1: @Singleton
• Let’s revisit this evil{(anti-)pattern
public class Evil
public static final Evil instance = new Evil ();
private Evil () {}
Evil getInstance() { return instance; }
}
• In Groovy
@Singleton() class Evil {}
• Also a “lazy” version
@Singleton(lazy = true) class Evil {}
56. Example #2: @Delegate
Not just for Managers
• You can delegate to fields of your classes
• class Employee {
def doTheWork() { “done” }
}
class Manager {
@Delegate
Employee slave = new Employee()
}
def god = new Manager()
assert god.doTheWork() == “done”
• Damn manager who will get all the praiser...
57. Global transformations
• Implement ASTTransformation
• Annotate the transfo specifying a compilation phase
• @GroovyASTTransformation(phase=CompilePhase.CONVERSION)
public class MyTransformation
implements ASTTransformation {
public void visit(ASTNode[] nodes, SourceUnit unit)
{ ... }
}
• For discovery, create the file META-INF/services/
org.codehaus.groovy.transform.ASTTransformation
• Add the fully qualified name of the class in that file
58. Local transformations
• Same approach as Globale transformations
• But you don’t need the META-INF file
• Instead create an annotation to specify on which
element the transformation should apply
• @Retention(RetentionPolicy.SOURCE)
@Target([ElementType.METHOD])
@GroovyASTTransformationClass(
[quot;fqn.MyTransformationquot;])
public @interface WithLogging {...}
59. Example: the Spock framework
• Changing the semantics of the original code
• But keeping a valid Groovy syntax
• @Speck
class HelloSpock {
def quot;can you figure out what I'm up to?quot;() {
expect:
name.size() == size
where:
name << [quot;Kirkquot;, quot;Spockquot;, quot;Scottyquot;]
size << [4, 5, 6]
}
}
60. a
d
n
e
g
A • The context and
the usual issues we face
• Some real-life examples of
Domain-Specific Languages
• Groovy’s DSL capabilities
• Integrating a DSL
in your application
• Considerations to remember
when designing your own DSL
61. Various integration mechanisms
• Java 6’s javax.script.* APIs (aka JSR-223)
• Spring’s language namespace
• Groovy’s own mechanisms
• But a key idea is to externalize those DSL programs
• DSL programs can have their own lifecycle
• no need to redeploy an application because of a
rule change
• business people won’t see the technical code
62. Java 6’s javax.script.* API
• Groovy 1.6 provides its own implementation of the
javax.script.* API
• ScriptEngineManager mgr =
new ScriptEngineManager();
ScriptEngine engine =
mgr.getEngineByName(“Groovy”);
String result = (String)engine.eval(“2+3”);
63. Spring’s lang namespace
• POGOs (Plain Old Groovy Objects) can be pre-
compiled as any POJO and used interchangeably with
POJOs in a Spring application
• But Groovy scripts & classes can be loaded at runtime
through the <lang:groovy/> namespace and tag
• Reloadable on change
• Customizable through a custom MetaClass
• <lang:groovy id=quot;eventsquot;
script-source=quot;classpath:dsl/eventsChart.groovyquot;
customizer-ref=quot;eventsMetaClassquot; />
64. Groovy’s own mechanisms
• Eval
• for evaluating simple expressions
• GroovyShell
• for more complex scripts and DSLs
• GroovyClassLoader
• the most powerful mechanism
66. GroovyShell
• A Binding provides a context of execution
• can implement lazy evaluation if needed
• A base script class can be specified
• def binding = new Binding()
binding.mass = 22.3
binding.velocity = 10.6
def shell = new GroovyShell(binding)
shell.evaluate(“mass * velocity ** 2 / 2”)
67. GroovyClassLoader
• Most powerful mechanism
• could also visit or change the AST
• scripts & classes can be loaded from elsewhere
• more control on compilation
• GroovyClassLoader gcl =
new GroovyClassLoader();
Class clazz = gcl.parseClass(
new File(“f.groovy”));
GroovyObject instance =
(GroovyObject)clazz.newInstance();
instance.setMetaClass(customMC);
68. Externalize business rules
• Although Groovy DSLs can be embedded in normal
Groovy classes, you should externalize them
• Store them elsewhere
• in a database, an XML file, etc.
• Benefits
• Business rules are not entangled
in technical application code
• Business rules can have their own lifecycle,
without requiring application redeployments
69. a
d
n
e
g
A • The context and
the usual issues we face
• Some real-life examples of
Domain-Specific Languages
• Groovy’s DSL capabilities
• Integrating a DSL
in your application
• Considerations to remember
when designing your own DSL
77. Various levels of sandboxing
• Groovy supports the usual Java Security Managers
• Use metaprogramming tricks to prevent calling /
instanciating certain classes
• Create a special GroovyClassLoader AST code visitor
to filter only the nodes of the AST you want to keep
• ArithmeticShell in Groovy’s samples
78. Test, test, test!
• Don’t just test for nominal cases
• Explicitely test for errors!
• Ensure end-users get meaninful error messages
80. Summary
• Groovy’s a great fit for Domain-Specific Languages
• Malleable & flexible syntax
• Full object-orientation
• Metaprogramming capabilities
• Runtime metaprogramming
• Compile-time metaprogramming
• Groovy’s very often used for mission-critical DSLs
81. ?
I kan haz my cheezburgr naw?
Or do ya reely haz keshtionz?