The document discusses new features in Groovy 1.8 including command chains that allow dropping dots and parentheses when chaining method calls, runtime performance improvements, and bundling of GPars for parallel programming. It also outlines plans for Groovy 2.0 such as alignments with JDK 7 including Project Coin and invokedynamic for continued runtime optimizations and static type checking.
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.
Flame Graphs for MySQL DBAs - FOSDEM 2022 MySQL DevroomValeriy Kravchuk
Flame graph is way to visualize profiling data that allows the most frequent code paths to be identified quickly and accurately. They can be generated using Brendan Gregg's open source programs on github.com/brendangregg/FlameGraph, which create interactive SVG files to be checked in browser. The source of profiling data does not really matter - it can be perf profiler, bpftrace, Performance Schema, EXPLAIN output or any other source that allows to convert the data into the expected format of comma-separated "path" plus metric per line.
Different types of Flame Graphs (CPU, Off-CPU, Memory, Differential etc) are presented. Various tools and approaches to collect profile information of different aspects of MySQL server internal working are presented Several real-life use cases where Flame Graphs helped to understand and solve the problem are discussed.
Watch Re-runs on your SQL Server with RML Utilitiesdpcobb
RML Utilities provide command line tools and interactive reports enabling you to:
Take SQL trace files (captured with SQL Profiler, sp_trace or extended events in SQL 2012+),
Process them into replayable RML files (using readtrace.exe),
Play them back in a different SQL environment (using ostress.exe),
And compare the performance at a granular level (using reporter.exe or custom queries).
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.
Flame Graphs for MySQL DBAs - FOSDEM 2022 MySQL DevroomValeriy Kravchuk
Flame graph is way to visualize profiling data that allows the most frequent code paths to be identified quickly and accurately. They can be generated using Brendan Gregg's open source programs on github.com/brendangregg/FlameGraph, which create interactive SVG files to be checked in browser. The source of profiling data does not really matter - it can be perf profiler, bpftrace, Performance Schema, EXPLAIN output or any other source that allows to convert the data into the expected format of comma-separated "path" plus metric per line.
Different types of Flame Graphs (CPU, Off-CPU, Memory, Differential etc) are presented. Various tools and approaches to collect profile information of different aspects of MySQL server internal working are presented Several real-life use cases where Flame Graphs helped to understand and solve the problem are discussed.
Watch Re-runs on your SQL Server with RML Utilitiesdpcobb
RML Utilities provide command line tools and interactive reports enabling you to:
Take SQL trace files (captured with SQL Profiler, sp_trace or extended events in SQL 2012+),
Process them into replayable RML files (using readtrace.exe),
Play them back in a different SQL environment (using ostress.exe),
And compare the performance at a granular level (using reporter.exe or custom queries).
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 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.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
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.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
UiPath Test Automation using UiPath Test Suite series, part 4
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
1. What’s new in Groovy?
Groovy 1.8 and what’s ahead
Guillaume Laforge @glaforge
Groovy Project Manager http://glaforge.appspot.com
SpringSource / VMware http://gplus.to/glaforge
2. Guillaume Laforge
• Groovy Project Manager at VMware
• Initiator of the Grails framework
• Creator of the Gaelyk toolkit
• Co-author of Groovy in Action
• Follow me on...
• My blog: http://glaforge.appspot.com
• Twitter: @glaforge
• Google+: http://gplus.to/glaforge
2
3. Agenda
• What’s new in Groovy 1.8?
–Nicer DSLs with command chains
–Runtime performance improvements
–GPars bundled for taming your multicores
–Closure enhancements
–Builtin JSON support
–New AST transformations
3
4. Agenda
• What’s cooking for Groovy 2.0?
–Alignments with JDK 7
• Project Coin (small language changes)
• InvokeDynamic
– Continued runtime performance improvements
–Static type checking and compilation
4
5. Command chains
• A grammar improvement allowing you
to drop dots & parens
when chaining method calls
–an extended version of top-level statements like println
• Less dots, less parens allow you to
–write more readable business rules
–in almost plain English sentences
• (or any language, of course)
5
12. Command chains
Before... we used to do...
take 2.pills, of: chloroquinine, after: 6.hours
8
13. Command chains
Before... we used to do...
take 2.pills, of: chloroquinine, after: 6.hours
Normal argument
8
14. Command chains
Before... we used to do...
take 2.pills, of: chloroquinine, after: 6.hours
Normal argument Named arguments
8
15. Command chains
Before... we used to do...
take 2.pills, of: chloroquinine, after: 6.hours
Normal argument Named arguments
Woud call:
def take(Map m, Quantity q)
8
16. Command chains
Now, even less punctuation!
take 2 pills of chloroquinine after 6 hours
9
17. Command chains
Now, even less punctuation!
take).2 pills of chloroquinine )
( ( ). ( ). ( after 6 hours
9
18. Command chains
// Java fluent API approach
class RegimenBuilder {
...
def take(int n) {
this.pills = n
return this
}
def pills(String of) {
return this
}
...
}
10
19. Command chains
// variable injection
def (of, after, hours) = /*...*/
// implementing the DSL logic
{ }
def take(n) {
[pills: { of ->
[chloroquinine: { after ->
['6': { time -> }]
}]
}]
}
//
----------------------------------------
take 2 pills of chloroquinine after 6 hours
11
22. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
12
23. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
12
24. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
check that: margarita tastes good
12
25. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
check that: margarita tastes good
// closure parameters for new control structures
12
26. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
check that: margarita tastes good
// closure parameters for new control structures
given {} when {} then {}
12
27. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
check that: margarita tastes good
// closure parameters for new control structures
given {} when {} then {}
// zero-arg methods require parens
12
28. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
check that: margarita tastes good
// closure parameters for new control structures
given {} when {} then {}
// zero-arg methods require parens
select all unique() from names
12
29. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
check that: margarita tastes good
// closure parameters for new control structures
given {} when {} then {}
// zero-arg methods require parens
select all unique() from names
// possible with an odd number of terms
12
30. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
// leverage named-args as punctuation
check that: margarita tastes good
// closure parameters for new control structures
given {} when {} then {}
// zero-arg methods require parens
select all unique() from names
// possible with an odd number of terms
take 3 cookies
12
31. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
( ). ( ). ( )
// leverage named-args as punctuation
check that: margarita tastes good
// closure parameters for new control structures
given {} when {} then {}
// zero-arg methods require parens
select all unique() from names
// possible with an odd number of terms
take 3 cookies
12
32. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
( ). ( ). ( )
// leverage named-args as punctuation
check that: margarita )tastes good
( ). (
// closure parameters for new control structures
given {} when {} then {}
// zero-arg methods require parens
select all unique() from names
// possible with an odd number of terms
take 3 cookies
12
33. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
( ). ( ). ( )
// leverage named-args as punctuation
check that: margarita )tastes good
( ). (
// closure parameters for new control structures
given). when {} )
( {} ( ). ( then {}
// zero-arg methods require parens
select all unique() from names
// possible with an odd number of terms
take 3 cookies
12
34. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
( ). ( ). ( )
// leverage named-args as punctuation
check that: margarita )tastes good
( ). (
// closure parameters for new control structures
given). when {} )
( {} ( ). ( then {}
// zero-arg methods require parens
select all unique() from names
( ). . ( )
// possible with an odd number of terms
take 3 cookies
12
35. Command chains
// methods with multiple arguments (commas)
take coffee with sugar, milk and liquor
( ). ( ). ( )
// leverage named-args as punctuation
check that: margarita )tastes good
( ). (
// closure parameters for new control structures
given). when {} )
( {} ( ). ( then {}
// zero-arg methods require parens
select all unique() from names
( ). . ( )
// possible with an odd number of terms
take).3 cookies
(
12
36. Runtime performance
• Significant runtime improvements
for primitive type operations
–classical Fibonacci example x13 faster!
–closer to Java performance
• Some direct method calls on this
13
37. GPars bundled
• GPars is bundled
in the Groovy distribution
• GPars covers a wide range of parallel and
concurrent paradigms
–actors, fork/join, map/filter/reduce, dataflow, agents
–parallel arrays, executors, STM, and more...
14
38. Closure enhancements
• Closure annotation parameters
• Some more functional flavor
–composition
–trampoline
–memoization
• Currying improvements
15
39. Closure annotation parameters
@Retention(RetentionPolicy.RUNTIME)
@interface Invariant {
Class value() // a closure class
}
{
@Invariant({ number >= 0 })
class Distance {
float number
String unit
}
def d = new Distance(number: 10, unit: "meters")
def anno = Distance.getAnnotation(Invariant)
def check = anno.value().newInstance(d, d)
assert check(d)
16
40. Closure annotation parameters
@Retention(RetentionPolicy.RUNTIME)
@interface Invariant {
Class value() // a closure class
}
{
@Invariant({ number >= 0 })
class Distance {
GCon tracts
float number oor-m an’s
P
String unit
}
def d = new Distance(number: 10, unit: "meters")
def anno = Distance.getAnnotation(Invariant)
def check = anno.value().newInstance(d, d)
assert check(d)
16
67. @Log
• Four different loggers can be injected
–@Log, @Commons, @Log4j, @Slf4j
• Possible to implement your own strategy
import groovy.util.logging.*
@Log
class Car {
Car() {
log.info 'Car constructed'
}
}
def c = new Car()
26
68. @Log
• Four different loggers can be injected
–@Log, @Commons, @Log4j, @Slf4j
• Possible to implement your own strategy
import groovy.util.logging.*
@Log
class Car {
Guarded Car() {
w/ an if log.info 'Car constructed'
}
}
def c = new Car()
26
69. @Field
• Surprising scoping rules in scripts
–variables are local to the run() method
–variables aren’t visible in methods
• although visually the variable is in a surrounding scope
• @Field creates a field in the script class
@Field List awe = [1, 2, 3]
def awesum() { awe.sum() }
assert awesum() == 6
27
70. Controlling code execution
• Your application may run user’s code
–what if the code runs in infinite loops or for too long?
–what if the code consumes too many resources?
28
71. Controlling code execution
• Your application may run user’s code
–what if the code runs in infinite loops or for too long?
–what if the code consumes too many resources?
• 3 new transforms at your rescue
–@ThreadInterrupt: adds Thread#isInterrupted checks
so your executing thread stops when interrupted
–@TimedInterrupt: adds checks in method and closure
bodies to verify it’s run longer than expected
–@ConditionalInterrupt: adds checks with your own
conditional logic to break out from the user code
28
72. Controlling code execution
• Your application may run user’s code
–what if the code runs in infinite loops or for too long?
–what if the code consumes too many resources?
• 3 new transforms at your rescue
–@ThreadInterrupt: adds Thread#isInterrupted checks
so your executing thread stops when interrupted
–@TimedInterrupt: adds checks in method and closure
bodies to verify it’s run longer than expected
–@ConditionalInterrupt: adds checks with your own
conditional logic to break out from the user code
• Also see compilation customizers later on 28
73. @ThreadInterrupt
@ThreadInterrupt
import groovy.transform.ThreadInterrupt
while (true) {
// eat lots of CPU
}
29
33
74. @ThreadInterrupt
@ThreadInterrupt
import groovy.transform.ThreadInterrupt
while (true) {
{ if (Thread.currentThread.isInterrupted())
throw new InterruptedException() }
// eat lots of CPU
}
29
33
75. @ThreadInterrupt
@ThreadInterrupt
import groovy.transform.ThreadInterrupt
while (true) {
{ if (Thread.currentThread.isInterrupted())
throw new InterruptedException() }
// eat lots of CPU
}
• Two optional annotation parameters available
–checkOnMethodStart (true by default)
–applyToAllClasses (true by default)
29
33
76. @TimedInterrupt
@TimedInterrupt(10)
import groovy.transform.TimedInterrupt
while (true) {
// eat lots of CPU
}
• InterruptedException thrown when checks
indicate code ran longer than desired
• Optional annotation parameters available
–same as @ThreadInterrupt
–value: for an amount of time duration
–unit: for the time duration unit (TimeUnit.SECONDS) 30
77. @ConditionalInterrupt
• Specify your own condition to be inserted
at the start of method and closure bodies
– check for available resources, number of times run, etc.
• Leverages closure annotation parameters from
Groovy 1.8
@ConditionalInterrupt({ counter++ > 2 })
import groovy.transform.ConditionalInterrupt
import groovy.transform.Field
@Field int counter = 0
100.times {
println 'executing script method...'
}
31
78. @ToString
• Provides a default toString() method to your types
• Available annotation options
– includeNames, includeFields, includeSuper, excludes
import groovy.transform.ToString
@ToString
class Person {
String name
int age
}
println new Person(name: 'Pete', age: 15)
// => Person(Pete, 15)
32
79. @EqualsAndHashCode
• Provides default implementations for equals()
and hashCode() methods
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode
class Coord {
int x, y
}
def c1 = new Coord(x: 20, y: 5)
def c2 = new Coord(x: 20, y: 5)
assert c1 == c2
assert c1.hashCode() == c2.hashCode()
33
80. @TupleConstructor
• Provides a «classical» constructor with all
properties
• Several annotation parameter options available
import groovy.transform.TupleConstructor
@TupleConstructor
class Person {
String name
int age
}
def m = new Person('Marion', 3)
assert m.name == 'Marion'
assert m.age == 3
34
81. @Canonical
• One annotation to rule them all!
–@Canonical mixes together
• @ToString
• @EqualsAndHashCode
• @TupleConstructor
• You can customize behavior by combining
@Canonical and one of the other annotations
35
82. @InheritConstructors
• Classes like Exception are painful when
extended, as all the base constructors should
be replicated
class CustomException extends Exception {
CustomException() { super() }
CustomException(String msg) { super(msg) }
CustomException(String msg, Throwable t) { super(msg, t) }
CustomException(Throwable t) { super(t) }
}
36
83. @InheritConstructors
• Classes like Exception are painful when
extended, as all the base constructors should
be replicated
import groovy.transform.*
@InheritConstructors
class CustomException extends Exception {
CustomException() { super() }
CustomException(String msg) { super(msg) }
CustomException(String msg, Throwable t) { super(msg, t) }
CustomException(Throwable t) { super(t) }
}
36
84. @WithReadLock, @WithWriteLock
import groovy.transform.*
class ResourceProvider {
private final Map<String, String> data = new HashMap<>()
@WithReadLock
String getResource(String key) {
return data.get(key)
}
@WithWriteLock
void refresh() {
//reload the resources into memory
}
}
37
85. @WithReadLock, @WithWriteLock
import groovy.transform.*
class ResourceProvider {
private final Map<String, String> data = new HashMap<>()
{ @WithReadLock
String getResource(String key) {
return data.get(key)
}
{ @WithWriteLock
void refresh() {
//reload the resources into memory
}
}
37
87. Compilation customizers
• Ability to apply some customization to the Groovy
compilation process
• Three available customizers
–ImportCustomizer
–ASTTransformationCustomizer
–SecureASTCustomizer
• But you can implement your own
39
88. Imports customizer
def configuration = new CompilerConfiguration()
def custo = new ImportCustomizer()
custo.addStaticStar(Math.name)
configuration.addCompilationCustomizers(custo)
def result = new GroovyShell(configuration)
.evaluate(" cos PI/3 ")
40
89. Applying an AST transformation
def configuration = new CompilerConfiguration()
configuration.addCompilationCustomizers(
new ASTTransformationCustomizer(Log))
new GroovyShell(configuration).evaluate("""
class Car {
Car() {
log.info 'Car constructed'
}
}
log.info 'Constructing a car'
def c = new Car()
""")
41
90. Secure AST customizer
Idea: Implement an «arithmetic shell»
Being able control what a user script is
allowed to do: only arithmetic expressions
• Let’s setup our environment
–some imports
–an import customizer to import java.lang.Math.*
–prepare a secure AST customizer
import org.codehaus.groovy.control.customizers.*
import org.codehaus.groovy.control.*
import static org.codehaus.groovy.syntax.Types.*
def imports = new ImportCustomizer().addStaticStars('java.lang.Math')
def secure = new SecureASTCustomizer()
42
92. Secure AST customizer
...
// language tokens allowed
tokensWhitelist = [
PLUS, MINUS, MULTIPLY, DIVIDE, MOD, POWER, PLUS_PLUS,
MINUS_MINUS, COMPARE_EQUAL, COMPARE_NOT_EQUAL,
COMPARE_LESS_THAN, COMPARE_LESS_THAN_EQUAL,
COMPARE_GREATER_THAN, COMPARE_GREATER_THAN_EQUAL
]
// types allowed to be used (including primitive types)
constantTypesClassesWhiteList = [
Integer, Float, Long, Double, BigDecimal,
Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE
]
// classes who are allowed to be receivers of method calls
receiversClassesWhiteList = [
Math, Integer, Float, Double, Long, BigDecimal ]
}
...
44
93. Secure AST customizer
• Ready to evaluate our arithmetic expressions!
...
def config = new CompilerConfiguration()
config.addCompilationCustomizers(imports, secure)
def shell = new GroovyShell(config)
shell.evaluate 'cos PI/3'
• But the following would have failed:
shell.evaluate 'System.exit(0)'
45
94. Slashy and dollar slashy strings
• Slashy strings are now multiline
–particularly handy for multi-line regexs
• Dollar slashy string notation introduced
–a multiline GString with different escaping rules
def (name, date) = ["Guillaume", "Oct, 26th"]
def dollarSlashy = $/
Hello $name, today we're ${date}
$ dollar-sign
$$ dollar-sign
backslash
/ slash
$/ slash
/$
46
95. New GDK methods
// count
assert [2,4,2,1,3,5,2,4,3].count { it % 2 == 0 } == 5
// count by
assert [0:2, 1:3] == [1,2,3,4,5].countBy{ it % 2 }
assert [(true):2, (false):4]
== 'Groovy'.toList().countBy{ it == 'o' }
// min/max for maps with closures
def map = [a: 1, bbb: 4, cc: 5, dddd: 2]
assert map.max { it.key.size() }.key == 'dddd'
assert map.min { it.value }.value == 1
// map withDefault()
def words = "one two two three three three".split()
def freq = [:].withDefault { k -> 0 }
words.each { freq[it] += 1 }
47
96. (G)String to Enum coercion
enum Color {
red, green, blue
}
// coercion with as
def r = "red" as Color
// implicit coercion
Color b = "blue"
// with GStrings too
def g = "${'green'}" as Color
48
98. Launching remote scripts
• With the Groovy command, you can launch
remote scripts
> groovy http://groovyconsole.appspot.com/raw/110001
• Be careful to what
you’re executing :-)
50
100. Groovy 2.0 roadmap
• Java 7 alignements: Project Coin
–binary literals
–underscore in literals
–multicatch
• JDK 7: InvokeDynamic
• Towards a more modular Groovy
• Static type checking and compilation
• Miscelanous
• What else? Your call!
52
101. Groovy 2.0 roadmap
• Java 7 alignements: Project Coin
–binary literals
–underscore in literals
–multicatch
• JDK 7: InvokeDynamic
• Towards a more modular Groovy
• Static type checking and compilation
• Miscelanous
• What else? Your call!
52
103. Binary literals
• We had decimal, octal and hexadecimal
notations for number literals
• We can now use binary representations too
int x = 0b10101111
assert x == 175
byte aByte = 0b00100001
assert aByte == 33
int anInt = 0b1010000101000101
assert anInt == 41285
54
104. Underscore in literals
• Now we can also add underscores
in number literals for more readability
long creditCardNumber = 1234_5678_9012_3456L
long socialSecurityNumbers = 999_99_9999L
float monetaryAmount = 12_345_132.12
long hexBytes = 0xFF_EC_DE_5E
long hexWords = 0xFFEC_DE5E
long maxLong = 0x7fff_ffff_ffff_ffffL
long alsoMaxLong = 9_223_372_036_854_775_807L
long bytes = 0b11010010_01101001_10010100_10010010
55
105. Multicatch
• One block for multiple exception caught
–rather than duplicating the block
try {
/* ... */
} catch(IOException | NullPointerException e) {
/* one block to treat 2 exceptions */
}
56
106. InvokeDynamic
• Groovy 2.0 will support JDK 7’s
invokeDynamic
–an «indy» branch started recently
–compiler will have a flag for compiling against JDK 7
–might use the invokeDynamic backport
• Benefits
–more runtime performance!
–in the long run, will allow us to get rid of code!
• call site caching, thanks to MethodHandles
• metaclass registry, thanks to ClassValues
• will let the JIT inline calls more easily 57
107. Groovy Modularity
• Groovy’s «all» JAR weighs in at 4MB
• Nobody needs everything
–Template engine, Ant scripting, Swing UI building...
• Provide a smaller core
–and several smaller JARs per feature
• Provide hooks for setting up EMCs / DGM
methods, etc.
58
108. Static Type Checking
• Goal: make the Groovy compiler «grumpy»!
–and throw compilation errors (not at runtime)
• Not everybody needs dynamic features all the time
–think Java libraries scripting
• Grumpy should...
–tell you about your method or variable typos
–complain if you call methods that don’t exist
–shout on assignments of wrong types
–infer the types of your variables
–figure out GDK methods
–etc...
59
109. Typos in your variable or method
import groovy.transform.StaticTypes
void method() {}
@TypeChecked test() {
// Cannot find matching method metthhoood()
metthhoood()
def name = "Guillaume"
// variable naamme is undeclared
println naamme
}
60
110. Typos in your variable or method
import groovy.transform.StaticTypes
void method() {}
@TypeChecked test() {
// Cannot find matching method metthhoood()
metthhoood()
def name = "Guillaume" Compilation
// variable naamme is undeclared errors!
println naamme
}
60
111. Complain on wrong assignments
// cannot assign value of type... to variable...
int x = new Object()
Set set = new Object()
def o = new Object()
int x = o
String[] strings = ['a','b','c']
int str = strings[0]
// cannot find matching method plus()
int i = 0
i += '1'
61
112. Complain on wrong assignments
// cannot assign value of type... to variable...
int x = new Object()
Set set = new Object() Compilation
errors!
def o = new Object()
int x = o
String[] strings = ['a','b','c']
int str = strings[0]
// cannot find matching method plus()
int i = 0
i += '1'
61
113. Complain on wrong return types
String method() { 'String' }
// cannot assign value of type String...
int x = method()
// checks if/else branch return values
int method() {
if (true) { 'String' }
else { 42 }
}
// works for switch/case & try/catch/finally
// transparent toString() implied
String greeting(String name) {
def sb = new StringBuilder()
sb << "Hi" << name
}
62
114. Complain on wrong return types
String method() { 'String' }
// cannot assign value of type String...
int x = method() Compilation
errors!
// checks if/else branch return values
int method() {
if (true) { 'String' }
else { 42 }
}
// works for switch/case & try/catch/finally
// transparent toString() implied
String greeting(String name) {
def sb = new StringBuilder()
sb << "Hi" << name
}
62
115. Type inference
@TypeChecked test() {
def name = " Guillaume "
// String type infered (even inside GString)
println "NAME = ${name.toUpperCase()}"
// Groovy GDK method support
// (GDK operator overloading too)
println name.trim()
int[] numbers = [1, 2, 3]
// Element n is an int
for (int n in numbers) {
println n
}
}
63
116. Staticly checked & dyn. methods
@TypeChecked
String greeting(String name) {
// call method with dynamic behavior
// but with proper signature
generateMarkup(name.toUpperCase())
}
// usual dynamic behavior
String generateMarkup(String name) {
def sw = new StringWriter()
new MarkupBuilder(sw).html {
body {
div name
}
}
sw.toString()
}
64
117. Bytecode viewer
• Groovy Console’s
bytecode viewer
from the AST
browser window
–select class
generation phase
–select a class node
65
118. Disable Global AST xforms
// witout a specific configuration, the AST builder works
def shell = new GroovyShell()
shell.evaluate(script) // passes
def config = new CompilerConfiguration()
config.disabledGlobalASTTransformations =
['org.codehaus.groovy.ast.builder.AstBuilderTransformation']
def script = '''
import org.codehaus.groovy.ast.builder.AstBuilder
new AstBuilder().buildFromCode { "Hello" }
'''
// now with the configuration in place,
// the AST builder transform is not applied
shell = new GroovyShell(config) // <-- with the configuration
shouldFail {
shell.evaluate(script) // fails
}
66
120. Thank you!
e
aforg pment
ume L Develo
Guilla Groovy
f
Head o om
e@ gmail.c
glaforg rge
Email: @glafo e
o/glaforg
Tw itter : ://gplus.t pot.com
+: http rge.apps
Google p://glafo
B log: htt
68