A Java agents are pluggable self contained components that run embedded in a JVM and intercept the classloading process. They were introduced in Java 5 along with the powerful java.lang.instrument package. Java agents can be loaded statically at startup or dynamically (programmatically) at runtime to attach to a running process in a fail-safe fashion.
Java agents were an awesome addition to the JVM as it opened a lot of opportunities for tool designers and changed Java tooling landscape quite drastically. In conjunction with Java bytecode manipulation libraries it is now possible to do amazing things to Java classes: we can experiment with programming models, redefine classes in runtime, record execution flow, etc.
The presentation provides an overview of Java agents’ functionality along with the usage examples and real world experiences. You will learn, how to implement an agent and apply Instrumentation API in combination with bytecode manipulation libraries to solve interesting tasks.
Covered topic in Java 7 Presentation (Project Coin):
• Java Language enhancement history from version JDK 1.1 to Java 7
• Definition of Java7 Project Coin from JSR 334 Lead Joseph D.Darcy’s
• Java 7 Language enhancement
1. String in Switch(alternative for if else statement with String)
2. Binary Literal(0B) and Underscore in literal for more readability (int binary=10_1)
3. Multi catch and more precious rethrow
4. Try with resource statement(Automatic resource management)
5. Diamond Operator(Generics)
6. Improved Compiler warning for varargs.
A Java agents are pluggable self contained components that run embedded in a JVM and intercept the classloading process. They were introduced in Java 5 along with the powerful java.lang.instrument package. Java agents can be loaded statically at startup or dynamically (programmatically) at runtime to attach to a running process in a fail-safe fashion.
Java agents were an awesome addition to the JVM as it opened a lot of opportunities for tool designers and changed Java tooling landscape quite drastically. In conjunction with Java bytecode manipulation libraries it is now possible to do amazing things to Java classes: we can experiment with programming models, redefine classes in runtime, record execution flow, etc.
The presentation provides an overview of Java agents’ functionality along with the usage examples and real world experiences. You will learn, how to implement an agent and apply Instrumentation API in combination with bytecode manipulation libraries to solve interesting tasks.
Covered topic in Java 7 Presentation (Project Coin):
• Java Language enhancement history from version JDK 1.1 to Java 7
• Definition of Java7 Project Coin from JSR 334 Lead Joseph D.Darcy’s
• Java 7 Language enhancement
1. String in Switch(alternative for if else statement with String)
2. Binary Literal(0B) and Underscore in literal for more readability (int binary=10_1)
3. Multi catch and more precious rethrow
4. Try with resource statement(Automatic resource management)
5. Diamond Operator(Generics)
6. Improved Compiler warning for varargs.
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Soumen Santra
Features
JVM
Architecture
Security
Data Types
Class and Object
Program
First Java Application
Declaring and creating objects
Arrays
Constructors
this keyword
static keyword
Inheritance
Overriding
Access Modifiers
super keyword
final keyword
abstract classes
interfaces
Exceptions (error handling)
User Defining exceptions
ESUG 2017
Youtube: https://youtu.be/TkvjUXn3tGs
First Name: James
Last Name: Foster
Abstract:
One of the features of traditional Smalltalk is that the development
tools are in the same object space as the application being
developed. A corollary is that it has generally been a challenge to
debug a remote object space or build up a new class library from
scratch. But GemStone's multi-user architecture provides some
intriguing abilities to isolate not just classes, but methods. In
this presentation we provide an introduction to GemStone/S and
demonstrate running a Minimal-Pharo (with over 1400 classes) in
GemStone.
Bio:
As a junior-high student in 1971, James discovered the local
university’s computer center and a life-long obsession with computers
began. He was introduced to Smalltalk/V for the Mac in the mid-90s,
and became a Smalltalk bigot. James is VP of Finance & Operations for
GemTalk Systems and is a passionate advocate for GemStone and all
things Smalltalk. [Because this presentation includes an introduction
to GemStone we request that it come early in the week, before other
GemStone-related presentations.]
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
Java OOP Programming language (Part 3) - Class and Object
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Can two JVM languages, none of them Java, work harmoniously, side by side? Should they? In this lecture we’ll see how code written in Groovy and Scala work with Java and how they can be made to work with each other. The lecture is based on the experience of introducing Scala to an actual Groovy project.
GPars (Groovy Parallel Systems) is an open-source concurrency and parallelism library for Java and Groovy that gives you a number of high-level abstractions for writing concurrent and parallel code in Groovy (map/reduce, fork/join, asynchronous closures, actors, agents, dataflow concurrency and other concepts), which can make your Java and Groovy code concurrent and/or parallel with little effort.
To support localized messages in your Grails application, you should be defining all user messages in a properties file this is called internationalization
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Soumen Santra
Features
JVM
Architecture
Security
Data Types
Class and Object
Program
First Java Application
Declaring and creating objects
Arrays
Constructors
this keyword
static keyword
Inheritance
Overriding
Access Modifiers
super keyword
final keyword
abstract classes
interfaces
Exceptions (error handling)
User Defining exceptions
ESUG 2017
Youtube: https://youtu.be/TkvjUXn3tGs
First Name: James
Last Name: Foster
Abstract:
One of the features of traditional Smalltalk is that the development
tools are in the same object space as the application being
developed. A corollary is that it has generally been a challenge to
debug a remote object space or build up a new class library from
scratch. But GemStone's multi-user architecture provides some
intriguing abilities to isolate not just classes, but methods. In
this presentation we provide an introduction to GemStone/S and
demonstrate running a Minimal-Pharo (with over 1400 classes) in
GemStone.
Bio:
As a junior-high student in 1971, James discovered the local
university’s computer center and a life-long obsession with computers
began. He was introduced to Smalltalk/V for the Mac in the mid-90s,
and became a Smalltalk bigot. James is VP of Finance & Operations for
GemTalk Systems and is a passionate advocate for GemStone and all
things Smalltalk. [Because this presentation includes an introduction
to GemStone we request that it come early in the week, before other
GemStone-related presentations.]
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
Java OOP Programming language (Part 3) - Class and Object
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Can two JVM languages, none of them Java, work harmoniously, side by side? Should they? In this lecture we’ll see how code written in Groovy and Scala work with Java and how they can be made to work with each other. The lecture is based on the experience of introducing Scala to an actual Groovy project.
GPars (Groovy Parallel Systems) is an open-source concurrency and parallelism library for Java and Groovy that gives you a number of high-level abstractions for writing concurrent and parallel code in Groovy (map/reduce, fork/join, asynchronous closures, actors, agents, dataflow concurrency and other concepts), which can make your Java and Groovy code concurrent and/or parallel with little effort.
To support localized messages in your Grails application, you should be defining all user messages in a properties file this is called internationalization
Like Java Server Pages (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails' tag library mechanism is simple, elegant and completely reloadable at runtime.
Docker is an open platform for developing, shipping, and running
applications. Docker is designed to deliver your applications faster. With
Docker you can separate your applications from your infrastructure and
treat your infrastructure like a managed application. Docker helps you
ship code faster, test faster, deploy faster, and shorten the cycle
between writing code and running code.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
Historically concept of Actors has been derived from Erlang and is being used as a Threading model in Scala and AKka.
We can think Actors like two persons who do not talk to each other but communicate via a mailbox
A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal related to that enclosure.
Reflection is one of those things like multi-threading where everyone with experience of it says “Don’t use it unless you absolutely have to”.
Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow with redirects and so on.
Introduction to Groovy runtime metaprogramming and AST transformsMarcin Grzejszczak
Introduction to Groovy runtime metaprogramming and AST transforms - by Marcin Grzejszczak author of the http://toomuchcoding.blogspot.com blog.
The sources can be found here
Mercurial Bitbucket - https://bitbucket.org/gregorin1987/too-much-coding/src/e5ab7c69ab7b2796075fd6f087fbf31346aa2d2b/Groovy/ast/?at=default
Git Github - https://github.com/marcingrzejszczak/too-much-coding/tree/master/Groovy/ast
Grooscript is an open source project, a little framework that convert groovy code to javascript, more info in grooscript.org.
Javascript is cool now, a vibrant community with many new developments. Web development is moving to client size and you must be start to worry about javascript and all the new awesome tools for it. With grooscript, you can join this new wave with our lovely groovy. You can code all the logic of your application in groovy, test with spock, use gradle or any other java or groovy framework. Grooscript will convert your application code to javascript and then you can use it in the browser or Node.js.
In this talk I will introduce about grooscript, how started, how can be used, explore its limitations,… Also I will show grooscript grails plugin, and what do you can do with it. We will take a look at Node.js plugin and gradle plugin, and how to use this tools. I will show some demos of different ways to use grooscript.
oops concept in java | object oriented programming in javaCPD INDIA
object oriented programming is a key concept for the development of application in windows as well as web based application environment. oops concept maps real world through its concept of classes, objects, inheritance, polymorphism which help in making a robust application.
Alexa is Amazon’s cloud-based voice service.
It is a way to communicate the system using our voice.
Alexa provides a set of built-in capabilities, referred to as skills.
Apache Commons is an Apache project focused on all aspects of reusable Java components.
It is divided into three components: Commons Proper, Commons Sandbox, Commons Dormant.
Running queries across multiple tables. This will involve the concept of joins—that is, how we join tables together.
Using joins to run queries over multiple tables, including:
Natural, inner, and cross joins
Straight joins
Left and right joins
Writing subqueries
Using SELECT statement options
Swagger is an open source software framework backed by
a large ecosystem of tools that helps developers
design, build, document and consume RESTful Web
services.
The theory of SOLID principles was
introduced by Robert C. Martin in his 2000
paper “Design Principles and Design
Patterns”.
SOLID => Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion.
ArangoDB is a native multi-model database system developed by triAGENS GmbH. The database system supports three important data models (key/value, documents, graphs) with one database core and a unified query language AQL (ArangoDB Query Language). ArangoDB is a NoSQL database system but AQL is similar in many ways to SQL
Geth is widely used to interact with Ethereum networks. Ethereum software enables a user to set up a
“private” or “testnet” Ethereum chain. This chain will be totally different from main chain.
Component that tell geth that we want to use/create a private Ethereum Chain:
1. Custom Genesis file
2. Custom Data Directory
3. Custom Network Id
4. Disable Node Discovery
Ethereum is an open software platform based on blockchain technology that enables developers to
build and deploy decentralized applications.
Ethereum is a distributed public blockchain network.
While the Bitcoin blockchain is used to track ownership of digital currency (bitcoins), the Ethereum
blockchain focuses on running the programming code of any decentralized application.
Ether is a cryptocurrency whose blockchain is generated by the Ethereum platform. Ether can be
transferred between accounts and used to compensate participant mining nodes for computations
performed.
Google Authenticator is a software token that implements two-step verification services using the Time-based One-time Password Algorithm (TOTP) and HMAC-based One-time Password Algorithm (HOTP), for authenticating users of mobile applications by Google. The service implements algorithms specified in RFC 6238 and RFC 4226, respectively.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...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.
Welcome to the first live UiPath Community Day Dubai! Join us for this unique occasion to meet our local and global UiPath Community and leaders. You will get a full view of the MEA region's automation landscape and the AI Powered automation technology capabilities of UiPath. Also, hosted by our local partners Marc Ellis, you will enjoy a half-day packed with industry insights and automation peers networking.
📕 Curious on our agenda? Wait no more!
10:00 Welcome note - UiPath Community in Dubai
Lovely Sinha, UiPath Community Chapter Leader, UiPath MVPx3, Hyper-automation Consultant, First Abu Dhabi Bank
10:20 A UiPath cross-region MEA overview
Ashraf El Zarka, VP and Managing Director MEA, UiPath
10:35: Customer Success Journey
Deepthi Deepak, Head of Intelligent Automation CoE, First Abu Dhabi Bank
11:15 The UiPath approach to GenAI with our three principles: improve accuracy, supercharge productivity, and automate more
Boris Krumrey, Global VP, Automation Innovation, UiPath
12:15 To discover how Marc Ellis leverages tech-driven solutions in recruitment and managed services.
Brendan Lingam, Director of Sales and Business Development, Marc Ellis
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
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.
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.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
The Metaverse and AI: how can decision-makers harness the Metaverse for their...Jen Stirrup
The Metaverse is popularized in science fiction, and now it is becoming closer to being a part of our daily lives through the use of social media and shopping companies. How can businesses survive in a world where Artificial Intelligence is becoming the present as well as the future of technology, and how does the Metaverse fit into business strategy when futurist ideas are developing into reality at accelerated rates? How do we do this when our data isn't up to scratch? How can we move towards success with our data so we are set up for the Metaverse when it arrives?
How can you help your company evolve, adapt, and succeed using Artificial Intelligence and the Metaverse to stay ahead of the competition? What are the potential issues, complications, and benefits that these technologies could bring to us and our organizations? In this session, Jen Stirrup will explain how to start thinking about these technologies as an organisation.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
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
2. Agenda
▣ Groovy Is Dynamic
▣ What is MetaProgramming?
▣ Runtime MetaProgramming
□ What is MOP?
□ Understanding Groovy
□ Meta Class
▣ Intercepting Methods Using MOP
□ InvokeMethod
□ GroovyInterceptable
□ Intercepting Methods using MetaClass
▣ MOP Method Injection
□ MetaClass
□ Categories
□ Mixins/Traits
3. Agenda (continues..)
▣ MOP Method Synthesis
▣ MOP Class Synthesis
▣ Compile-time MetaProgramming
□ AST and Compilation
□ Groovy AST Transformation
□ Global AST Transformation
□ Local AST Transformation
▣ Why we should use MetaProgramming?
▣ References
4. Groovy Is Dynamic
▣ Groovy allows "Delay" to runtime some
checks/decisions that are usually performed
during the compilation.
▣ Add properties/behaviours in runtime.
▣ Wide range of applicability
□ DSLs
□ Builders
□ Advanced logging, tracing, debugging & profiling
□ Allow organize the codebase better
That's why we can talk about Metaprogramming
in Groovy.
6. ‘’
Metaprogramming is
the writing of computer
programs that write or
manipulate other
programs (or
themselves) as their
data.
- Wikipedia
7. Overview
The Groovy language supports two flavors of
metaprogramming:
▣ Runtime metaprogramming, and
▣ Compile-time metaprogramming.
The first one allows altering the class model and
the behavior of a program at runtime, while the
second only occurs at compile-time.
9. Runtime MetaProgramming
▣ Groovy provides this through Meta-Object
Protocol (MOP).
▣ We can use MOP to:
□ Invoke methods dynamically
□ Synthesize classes and methods on the fly.
With runtime metaprogramming we can
postpone to runtime the decision to intercept,
inject and even synthesize methods of classes
and interfaces.
11. Understanding Groovy
For a deep understanding of Groovy MOP we
first need to understand Groovy objects and
Groovy’s method handling. In Groovy, we work
with three kinds of objects:
▣ POJO,
▣ POGO, and
▣ Groovy Interceptors
So, for each object Groovy allows
metaprogramming but in different manner.
12. continues...
▣ POJO - A regular Java object, whose class can be
written in Java or any other language for the JVM.
▣ POGO - A Groovy object, whose class is written in
Groovy. It extends java.lang.Object and implements
the groovy.lang.GroovyObject interface by default.
▣ Groovy Interceptor - A Groovy object that implements
the groovy.lang.GroovyInterceptable interface and has
method-interception capability, which we’ll discuss in
the GroovyInterceptable section.
For every method call Groovy checks whether the object is
a POJO or a POGO. For POJOs, Groovy fetches it’s
MetaClass from the groovy.lang.MetaClassRegistry and
delegates method invocation to it.
16. Groovy Object Interface
GroovyObject has a default implementation in the
groovy.lang.GroovyObjectSupport class and it is responsible to
transfer invocation to the groovy.lang.MetaClass object. The
GroovyObject source looks like this:
package groovy.lang;
public interface GroovyObject {
Object invokeMethod(String name, Object args);
Object getProperty(String propertyName);
void setProperty(String propertyName, Object newValue);
MetaClass getMetaClass();
void setMetaClass(MetaClass metaClass);
}
18. invokeMethod
This invokeMethod is called when the method you called is not
present on a Groovy object. Example:
class InvokeMethodDemo {
def invokeMethod(String name, Object args) {
return "called invokeMethod $name $args"
}
def test() {
return 'method exists'
}
}
def invokeMethodDemo = new InvokeMethodDemo()
assert invokeMethodDemo.test() == 'method exists'
assert invokeMethodDemo.hello() == 'called invokeMethod hello []'
20. GroovyInterceptable
▣ Classes compiled by Groovy implements GroovyObject
interface.
▣ We can implement GroovyInterceptable to hook into
the execution process.
package groovy.lang;
public interface GroovyInterceptable extends
GroovyObject {
}
When a Groovy object implements the
GroovyInterceptable interface, it’s invokeMethod() is called
for any method calls.
23. Intercepting Methods using MetaClass
If we want to intercept all methods call but do not want to
implement the GroovyInterceptable interface we can
implement invokeMethod() on an object’s MetaClass.
▣ Groovy maintains a meta class of type MetaClass for
each class.
▣ Maintains a collection of all methods and properties of
A.
▣ If we can't modify the class source code or if it's a Java
class we can modify the meta-class.
▣ We can intercept methods by implementing the
invokeMethod() method on the MetaClass.
26. MOP Method Injection
▣ In Groovy we can “open” a class at any time.
▣ Injecting methods at code-writing time; we
know the names of methods we want to add.
▣ Different techniques:
□ MetaClass
□ Categories
□ Extensions
□ Mixins / Traits
28. Types of MetaClass
▣ MetaClassImpl: Default meta class, it's used in the vast
majority of case.
▣ ExpandoMetaClass: allow the addition or replacement
of methods, properties and constructors on the fly.
▣ Other meta classes used internally and for testing.
Note: This is only true for Groovy.
▣ In Grails all MetaClass are ExpandoMetaClass.
29. Adding Methods Using MetaClass
class StringUtils {
static String truncate(String text, Integer length, Boolean overflow = false) {
text.take(length) + (overflow ? '...' : '')
}
}
String chuckIpsum = "If you can see Chuck Norris, he can see you.
If you can not see Chuck Norris you may be only seconds away from death"
println StringUtils.truncate(chuckIpsum, 72)
println StringUtils.truncate(chuckIpsum, 72, true)
String.metaClass.truncateDemo = { Integer length, Boolean overflow = false ->
println "truncate string upto length $length"
delegate.take(length) + (overflow ? '...' : '')
}
assert chuckIpsum.truncateDemo(20, true) == StringUtils.truncate(chuckIpsum, 20, true)
35. Categories
▣ Changes made to a MetaClass are “persistent”
and hard to revert.
▣ Categories are useful to change the meta
class in a confined small piece of code.
▣ A category can alter a class’ MetaClass.
▣ The MOP is modified in the closure and after
the closure execution, it resets to its old state.
▣ Category classes are not special.
39. Mixins
▣ A mixin allow “bring in” or “mix in”
implementations from multiple classes.
▣ Groovy first call the mixed-in class.
▣ Mix multiple classes. The last added mixin
takes precedence.
▣ Override a method of a previous Mixin but not
methods in the meta class.
▣ Mixins cannot easily be un-done.
40. continues..
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
class SupermanPower {
String fly() {
"Flying..."
}
}
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
41. continues..
class SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
class SupermanPower {
String fly() {
"Flying..."
}
}
@Mixin([SpidermanPower])
class Person {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
assert !(person instanceof SpidermanPower)
Person.mixin SupermanPower
assert person.fly() == "Flying..."
assert !(person instanceof SupermanPower)
42. ‘’
When we started fixing
mixin bugs we didn't
know if they were a
bug or a feature, so we
removed mixins and
add traits.
- Jochen Theodorou
43. ▣ Groovy 2.3+
▣ Similar to Java 8 default methods
▣ Supported in JDK 6, 7 and 8
▣ Stateful
▣ Composition over inheritance
▣ Documentation
Traits
Note - Link to Groovy Traits PPT
44. Traits Example
trait SpidermanPower {
String spiderSense() {
"Using spider-sense..."
}
}
class Person implements SpidermanPower {}
def person = new Person()
assert person.spiderSense() == "Using spider-sense..."
println("=====> person.spiderSense(): ${person.spiderSense()}")
assert person instanceof SpidermanPower
def person2 = person.withTraits SupermanPower
assert person2.fly() == "Flying..."
println("=====> person2.fly(): ${person2.fly()}")
assert person2 instanceof SupermanPower
trait SupermanPower {
String fly() {
"Flying..."
}
}
46. MOP Method Synthesis
▣ Dynamically figure out the behaviour for
methods upon invocation.
▣ A synthesized method may not exist as a
separate method until we call it.
▣ invokeMethod, methodMissing and
propertyMissing.
▣ “Intercept, Cache, Invoke” pattern.
47. Check for Methods and Properties
class Person {
String name
Integer age
String sayHi() {
"Hi, my name is ${name} and I'm ${age}"
}
String sayHiTo(String name) {
"Hi ${name}, how are you?"
}
}
def p = new Person(name: 'Superman',
age: 34)
assert p.respondsTo('sayHi')
assert p.respondsTo('sayHiTo', String)
assert !p.respondsTo('goodbye')
assert p.hasProperty('name')
assert !p.hasProperty('country')
48. Method Delegation
cl = { ->
append "Hi!"
append " this is closure delegate demo."
}
sb = new StringBuffer()
cl.delegate = sb
cl()
println "SB: ${sb}"
49. Continues.. (Example 2)
class ClosureDemo {
void append(String arg) {
println("append called with: ${arg}")
}
void doit() {
def cl = {
append 'MetaProgramming Demo by'
append ' Ali and Gaurav'
}
def sb = new StringBuffer()
cl.delegate = sb
cl()
println("SB: ${sb}")
}
static void main(args) {
new ClosureDemo().doit()
}
}
51. Creating Dynamic Classes with
Expando
carA = new Expando()
carB = new Expando(year: 2012, miles: 0)
carA.year = 2012
carA.miles = 10
println "carA: " + carA
println "carB: " + carB
In Groovy we can create a class entirely at runtime. The
Groovy Expando class gives us the ability to synthesize
classes dynamically.
It got its name because it is dynamically expandable. We can
assign properties and methods to it either at construction
time using a Map or at any time dynamically.
car = new Expando(year: 2012, miles: 0,
turn: { println 'turning...' })
car.drive = {
miles += 10
println "$miles miles driven"
}
car.drive()
car.turn()
53. Compile-time MetaProgramming
▣ Advanced feature.
▣ Analyze and modify a program’s structure at
compile time.
▣ Cross-cutting features:
▣ Inspect classes for thread safety
▣ Log messages
▣ Perform pre and postcheck operations all
without explicitly modifying the source code.
▣ We write code that generates bytecode or
gets involved during the bytecode
generation.
54. AST and Compilation
▣ AST: Abstract Syntax Tree
▣ During compilation the AST is transformed
▣ Hook into different phases to change the final
byte-code.
▣ Initialization, Parsing, Conversion, Semantic
analysis, Canonicalization, Instruction
selection, Class generation, Output,
Finalization.
55. Groovy AST Transformations
▣ Groovy provides out-of-the-box a lot of AST
Transformations
▣ @EqualsAndHashCode, @ToString,
@TuppleConstructor, @Canonical, @Grab,
@Immutable, @Delegate, @Singleton,
@Category, @Log4j, @CompileStatic,
@TypeChecked, @Synchronized, etc.
56. Global AST Transformations
▣ There's no need to annotate anything.
▣ Applied to every single source unit during
compilation.
▣ Can be applied to any phase in the
compilation.
▣ Need a metadata file into the JAR file
▣ (META-
INF/services/org.codehaus.groovy.transform.
ASTTransformation)
▣ Grails uses Global Transformations intensively
for example in GORM.
57. Local AST Transformations
▣ Annotate the code and only applied to that
code.
▣ Easy to debug.
▣ No need to create metadata file in a jar.
▣ Steps: Define an interface, Define the AST
transformation, Enjoy!
59. Concept Review
▣ Metaprogramming Easy and very out-of-the
box
▣ Easy and very powerful
▣ Write better code
▣ Add Behaviour easily
▣ Take advantage of this power because
Groovy, it’s Groovy
61. Thanks!
Any questions?
You can find us at -
▣ ali.tanwir@nexthoughts.com
▣ gaurav.gupta@nexthoughts.com
You can find demo code used with this presentation at -
https://github.com/NexThoughts/groovyMetaProgrammin
g