SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
Willitblend?JavaagentsandOSGi
RobertMunteanu,Adobe
Slides revision: 20200829-d098a06
APACHECON NA
Spt. 28th - Oct. 2nd 2020 1
Welcome
2
Aboutme
3
Outline
Quick demo
Java agents primer
Usage scenarios
OSGi integration
Integration testing
Testing demo
4
Quickdemo
5
Javaagentsprimer
6
JavainstrumentationAPIs
java.lang.instrument Javadoc, Java SE 8
Provides services that allow Java programming
language agents to instrument programs running
on the JVM.
7
Staticagents
# loaded at application startup
$ java -javaagent:agent.jar -jar app.jar
Premain-Class: org.example.my.Agent
import java.lang.instrument.*;
public class Agent {
public static void premain(String args,⏎
Instrumentation inst) {
inst.addTransformer(new ClassFileTransformer() {
/* implementation elided */
});
}
}
8
Dynamicagents
// dynamically attached to a running JVM
VirtualMachine vm = VirtualMachine.attach(vmPid);
vm.loadAgent(agentFilePath);
vm.detach();
Agent-Class: org.example.my.Agent
import java.lang.instrument.*;
public class Agent {
public static void agentmain(String args,⏎
Instrumentation inst) {
inst.addTransformer(new ClassFileTransformer() {
/* implementation elided */
});
}
}
9
Classtransformation
public interface ClassFileTransformer {
byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer)
throws IllegalClassFormatException;
}
10
Javabytecode
public static void main(java.lang.String[]);
Code:
0: getstatic #16⏎
// Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #22⏎
// String Hello, world
5: invokevirtual #24⏎
// Method java/io/PrintStream.println:(Ljava/lang/String;
8: return
11
Bytecodegenerationlibraries
Apache Commons BCEL
ByteBuddy
CGLib
Javassist
ObjectWeb ASM
12
BytecodegenerationwithJavassist
public byte[] transform(...) throws ... {
ClassPool classPool = ClassPool.getDefault();
CtMethod method = classPool.getMethod(⏎
Descriptor.toJavaName(className), "main");
method.insertAfter("System.out.println " + ⏎
"("... hello yourself!...");");
byte[] newClass = method.getDeclaringClass()⏎
.toBytecode();
method.getDeclaringClass().detach();
return newClass;
}
13
Usagescenarios
14
Whentouseagents
1. Code outside of your control
2. No better platform facilities exist
3. (Usually) Cross-cutting concerns
15
Agentexamples
1. Monitoring (logging, tracing, error reporting ...)
2. Profiling
3. Debugging
4. Mocking libraries
5. Code reload/Hot swap
16
OSGiintegration
17
Mindtheclassloader
- ClassPool defaultPool = ClassPool.getDefault();
- CtClass cc = defaultPool.get(⏎
- Descriptor.toJavaName(className));
+ ClassPool classPool = new ClassPool(true);
+ classPool.appendClassPath(new LoaderClassPath(loader));
+ classPool.insertClassPath(new ByteArrayClassPath(⏎
+ Descriptor.toJavaName(className), classfileBuffer));
18
Carefullymanagedependencies
New requirements typically fail since they are not
defined by the bundle
Bundles can be processed at build-time
Patching Import-Package
DynamicImport-Package: *
19
OSGialternatives-WeavingHooks
 Simplified deployment - OSGi bundle
 Simple registration via OSGi whiteboard
 Handles updated bundle package imports
 OSGi-only solution
20
OSGialternatives-WeavingHooks
@Component
public class SimpleWeavingHook implements WeavingHook {
public void weave(WovenClass wovenClass) {
/* checks, exception handling elided */
ClassPool cp = buildClassPool(wovenClass);
CtClass toTransform = cp.get(Descriptor.toJavaName(⏎
wovenClass.getClassName()));
CtMethod getMethod = toTransform.⏎
getDeclaredMethod("doGet");
getMethod.insertBefore(⏎
"System.out.println("doGet invoked");");
wovenClass.setBytes(toTransform.toBytecode());
}
}
21
Integrationtesting
22
Packagingchallenges
Java agents...
must be packaged as a Jar file, with a specific
manifest
not trivially attached to the current process
usually a one-way deal, no support for rolling
back class changes
23
Customtestlaunchers
"unit" tests
launch Java process with custom agents attached
require separate communication channel with
java agent
no out-of-the-box support for code coverage and
other tools
24
Bootstrappingthetest
// 1. which java?
String javaHome = System.getProperty("java.home");
Path javaExe = Paths.get(javaHome, "bin", "java");
// 2. which jar?
String ja = findAgentJar();
// 3. which classpath?
String classPath = buildClassPath();
// 4. launch
ProcessBuilder pb = new ProcessBuilder(
javaExe.toString(), "-javaagent:" + ja,
"-cp", classPath,
TestApplication.class.getName()
);
25
Verifyingsideeffects
Path stdout = Paths.get("target", "stdout.txt");
Path stderr = Paths.get("target", "stderr.txt");
pb.redirectInput(Redirect.INHERIT);
pb.redirectOutput(stdout.toFile());
pb.redirectError(stderr.toFile());
26
Addingcodecoverage
ProcessBuilder pb = new ProcessBuilder(
javaExe.toString(),
"-javaagent:" + codeCoverageAgent,
"-javaagent:" + ja,
"-cp",
classPath,
TestApplication.class.getName()
);
27
OSGiintegrationtesting
// note - must run in a forked container
@RunWith(PaxExam.class)
public class OsgiIT {
@Configuration
public Option[] config() throws IOException {
return options( junitBundles(), ⏎
vmOption("-javaagent:" + agentJar) );
}
@Test
public void callTimesOut() throws IOException {
assertTrue(agentReallyWorks());
}
}
28
Testingdemo
29
Resources
https://docs.oracle.com/javase/8/docs/api/java/lang/instrum
summary.html
https://www.javassist.org/
https://sling.apache.org/documentation/bundles/connectio
agent.html
30

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with Swift
 
Vue JS @ MindDoc. The progressive road to online therapy
Vue JS @ MindDoc. The progressive road to online therapyVue JS @ MindDoc. The progressive road to online therapy
Vue JS @ MindDoc. The progressive road to online therapy
 
Desenvolva plugins para o compilador do Java 8
Desenvolva plugins para o compilador do Java 8Desenvolva plugins para o compilador do Java 8
Desenvolva plugins para o compilador do Java 8
 
Javascript Unit Testing
Javascript Unit TestingJavascript Unit Testing
Javascript Unit Testing
 
Js tacktalk team dev js testing performance
Js tacktalk team dev js testing performanceJs tacktalk team dev js testing performance
Js tacktalk team dev js testing performance
 
RelProxy, Easy Class Reload and Scripting with Java
RelProxy, Easy Class Reload and Scripting with JavaRelProxy, Easy Class Reload and Scripting with Java
RelProxy, Easy Class Reload and Scripting with Java
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
 
[CLIW] Web testing
[CLIW] Web testing[CLIW] Web testing
[CLIW] Web testing
 
Asynchronous Programming at Netflix
Asynchronous Programming at NetflixAsynchronous Programming at Netflix
Asynchronous Programming at Netflix
 
Head toward Java 14 and Java 15 #LINE_DM
Head toward Java 14 and Java 15 #LINE_DMHead toward Java 14 and Java 15 #LINE_DM
Head toward Java 14 and Java 15 #LINE_DM
 
Test your code
Test your codeTest your code
Test your code
 
Mutation testing in Java
Mutation testing in JavaMutation testing in Java
Mutation testing in Java
 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
 
Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt test
 
What's new in Java 11
What's new in Java 11What's new in Java 11
What's new in Java 11
 
Testing Web Apps with Spring Framework
Testing Web Apps with Spring FrameworkTesting Web Apps with Spring Framework
Testing Web Apps with Spring Framework
 
MUTANTS KILLER - PIT: state of the art of mutation testing system
MUTANTS KILLER - PIT: state of the art of mutation testing system MUTANTS KILLER - PIT: state of the art of mutation testing system
MUTANTS KILLER - PIT: state of the art of mutation testing system
 
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey BuzdinMarvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
 

Ähnlich wie Will it blend? Java agents and OSGi

Unit Testing RPG with JUnit
Unit Testing RPG with JUnitUnit Testing RPG with JUnit
Unit Testing RPG with JUnit
Greg.Helton
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
robbiev
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
alice yang
 
20150516 modern web_conf_tw
20150516 modern web_conf_tw20150516 modern web_conf_tw
20150516 modern web_conf_tw
Tse-Ching Ho
 
Google Developer Fest 2010
Google Developer Fest 2010Google Developer Fest 2010
Google Developer Fest 2010
Chris Ramsdale
 

Ähnlich wie Will it blend? Java agents and OSGi (20)

Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Dropwizard and Friends
Dropwizard and FriendsDropwizard and Friends
Dropwizard and Friends
 
Phone gap 12 things you should know
Phone gap 12 things you should knowPhone gap 12 things you should know
Phone gap 12 things you should know
 
Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010
 
Unit Testing RPG with JUnit
Unit Testing RPG with JUnitUnit Testing RPG with JUnit
Unit Testing RPG with JUnit
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
Dalvik Source Code Reading
Dalvik Source Code ReadingDalvik Source Code Reading
Dalvik Source Code Reading
 
Tuto jtatoo
Tuto jtatooTuto jtatoo
Tuto jtatoo
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
Jasmine with JS-Test-Driver
Jasmine with JS-Test-DriverJasmine with JS-Test-Driver
Jasmine with JS-Test-Driver
 
Griffon Presentation
Griffon PresentationGriffon Presentation
Griffon Presentation
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCP
 
20150516 modern web_conf_tw
20150516 modern web_conf_tw20150516 modern web_conf_tw
20150516 modern web_conf_tw
 
GlassFish v3 : En Route Java EE 6
GlassFish v3 : En Route Java EE 6GlassFish v3 : En Route Java EE 6
GlassFish v3 : En Route Java EE 6
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
Google Developer Fest 2010
Google Developer Fest 2010Google Developer Fest 2010
Google Developer Fest 2010
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile Devices
 

Mehr von Robert Munteanu

Mehr von Robert Munteanu (20)

Secure by Default Web Applications
Secure by Default Web ApplicationsSecure by Default Web Applications
Secure by Default Web Applications
 
Sling Applications - A DevOps perspective
Sling Applications - A DevOps perspectiveSling Applications - A DevOps perspective
Sling Applications - A DevOps perspective
 
Escape the defaults - Configure Sling like AEM as a Cloud Service
Escape the defaults - Configure Sling like AEM as a Cloud ServiceEscape the defaults - Configure Sling like AEM as a Cloud Service
Escape the defaults - Configure Sling like AEM as a Cloud Service
 
Crash course in Kubernetes monitoring
Crash course in Kubernetes monitoringCrash course in Kubernetes monitoring
Crash course in Kubernetes monitoring
 
Cloud-native legacy applications
Cloud-native legacy applicationsCloud-native legacy applications
Cloud-native legacy applications
 
Cloud-Native Sling
Cloud-Native SlingCloud-Native Sling
Cloud-Native Sling
 
From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...
 
What's new in the Sling developer tooling?
What's new in the Sling developer tooling?What's new in the Sling developer tooling?
What's new in the Sling developer tooling?
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 
Zero downtime deployments for Sling application using Docker
Zero downtime deployments for Sling application using DockerZero downtime deployments for Sling application using Docker
Zero downtime deployments for Sling application using Docker
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 
Do you really want to go fully micro?
Do you really want to go fully micro?Do you really want to go fully micro?
Do you really want to go fully micro?
 
Effective web application development with Apache Sling
Effective web application development with Apache SlingEffective web application development with Apache Sling
Effective web application development with Apache Sling
 
Of microservices and microservices
Of microservices and microservicesOf microservices and microservices
Of microservices and microservices
 
Slide IDE Tooling (adaptTo 2016)
Slide IDE Tooling (adaptTo 2016)Slide IDE Tooling (adaptTo 2016)
Slide IDE Tooling (adaptTo 2016)
 
Secure by Default Web Applications with Apache Sling
Secure by Default Web Applications with Apache SlingSecure by Default Web Applications with Apache Sling
Secure by Default Web Applications with Apache Sling
 
Apache Sling as a Microservices Gateway
Apache Sling as a Microservices GatewayApache Sling as a Microservices Gateway
Apache Sling as a Microservices Gateway
 
Apache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middlewareApache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middleware
 

Kürzlich hochgeladen

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Will it blend? Java agents and OSGi