SlideShare uma empresa Scribd logo
1 de 19
Desenvolva plugins para o
compilador do Java 8
JustJava 2013
Marcelo de Castro
marcelo@castro.eti.br
@mcastroinfo
Plugin para o javac 8
0101010101011111000000000101001110001
1100011100000001111010101010110001110
1001001010000101001010101011010110111
• Por quê, para quê, desenvolver
plugins para o compilador do
Java?
– Adicionar checagem extras em tempo
de compilação
– Adicionar transformações de código
– Customizar análise do código fonte
Este código compila?
Teste.java
public class Teste {
public static final int var = 0;
public static void main(String[] args) {
int i = 0; System.out.println("#JustJava2013");
try{
i++;
}catch(Exception Ex){
}
}
public static void method(int a, int b, int c, int d,
int e, int f, int g, int h, int i, int j, int k){
}
class inner{}
}
Jogo dos 5 erros(!?)
public class Teste {
public static final int var = 0;
public static void main(String[] args) {
int i = 0; System.out.println("#JustJava2013");
try{
i++;
}catch(Exception Ex){
}
}
public static void method(int a, int b, int c, int d,
int e, int f, int g, int h, int i, int j, int k){
}
class inner{}
}
VAR
ex
Inner
vazio
Muitos
parâmetros
Compilar ou não compilar
?????
public class Teste {
public static final int var = 0;
public static void main(String[] args) {
int i = 0; System.out.println("#JustJava2013");
try{
i++;
}catch(Exception Ex){
}
}
public static void method(int a, int b, int c, int d,
int e, int f, int g, int h, int i, int j, int k){
}
class inner{}
}
Alterando o
comportamento do javac
1. Usar Java 8 (tools.jar no CLASSPATH)
2. Implementar Plugin(*)
3. Implementar TaskListener
4. Implementar a lógica desejada
– (TreePathScanner, TreeScanner, TreeVisitor)
– Ex: Não aceitar bloco catch vazio
5. Gerar o jar do Plugin
– META-INF/services/
• com.sun.source.util.Plugin
– NomeTotalmenteQualificadoDoPlugin(*)
6. Compilar usando o plugin
– javac -processorpath CodeCheckPlugin.jar -
Xplugin:CodeCheckPlugin Teste.java
API
0101010101011111000000000101001110001
1100011100000001111010101010110001110
1001001010000101001010101011010110111
interfaces
com.sun.source.util
• Plugin
– permite definir um plugin para o
compilador
• SourcePositions
– fornece métodos para obter a
posição corrente da compilação
• TaskListener
– fornece um listener para monitorar
atividades do javac
interface Plugin
public class CodeCheckPlugin implements Plugin {
@Override
public String getName() {
return "CodeCheckPlugin";
}
@Override
public void init(JavacTask task, String... strings) {
System.out.println("Iniciando plugin!");
task.setTaskListener(new CheckTaskListener(task));
}
}
interface TaskListener
public class CheckTaskListener implements TaskListener{
@Override
public void started(TaskEvent taskEvent) {
if(taskEvent.getKind().equals(TaskEvent.Kind.ANALYZE)) {
CompilationUnitTree compUnit =
taskEvent.getCompilationUnit();
TreePathScanner emptyCacthVisitor =
new EmptyCacthVisitor(task);
emptyCacthVisitor.scan(compUnit, null);
}
}
@Override
public void finished(TaskEvent te) {
}
}
TaskEvent.Kind
•PARSE
•ENTER
•ANNOTATION_PROCESSING
•ANNOTATION_PROCESSING_ROUND
•ANALYZE
•GENERATE
Source File
Teste.java
Byte Code
Teste.class
Abstract Syntax Trees
Exemplo da Gramática da Linguagem Java
normalClassDeclaration
: 'class' Identifier typeParameters?
('extends' type)?
('implements' typeList)?
classBody
public class Teste
extends TesteBase{
}
class TesteBase{}
*AST: abstract syntax tree
interface SourcePositions
SourcePositions sourcePositions =
trees.getSourcePositions();
sourcePositions.getStartPosition
(compilationUnitTree, tree);
sourcePositions.getEndPosition
(compilationUnitTree, tree);
Classes (Syntax Trees)
com.sun.source.util
com.sun.source.tree
• public abstract class Trees
• public abstract class DocTrees extends Trees
• public interface Tree
• public enum Tree.Kind
• public interface CompilationUnitTree extends Tree
• public interface MethodTree extends Tree
• public interface BlockTree extends Tree
• public interface CatchTree extends Tree
• public interface StatementTree extends Tree
• public interface ModifiersTree extends Tree
• public interface VariableTree extends Tree
• public interface PrimitiveTypeTree extends Tree
• + um montão de Tree
DEMO
0101010101011111000000000101001110001
1100011100000001111010101010110001110
1001001010000101001010101011010110111
Referências
• OpenJDK 8 http://openjdk.java.net/
• Javadoc (javac b74)
http://download.java.net/lambda/b74/docs/jdk/api/javac/tree/
• Compiler Grammar http://openjdk.java.net/projects/compiler-grammar/
• Hacking the Java Compiler for Fun and Profit By Raoul-Gabriel Urma
• “Java Compiler Plugins”, Oracle Java Magazine January/February 2013,
Raoul-Gabriel Urma& Jonathan Gibbons http://www.oraclejavamagazine-
digital.com/javamagazine/20130102?sub_id=jFwJyABK25xj#pg56
OBRIGADO
Marcelo de Castro
marcelo@castro.eti.br
@mcastroinfo

Mais conteúdo relacionado

Mais procurados

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
Javazone 2019 - Mutants to the rescue: How effective are your unit tests?
Javazone 2019 - Mutants to the rescue: How effective are your unit tests?Javazone 2019 - Mutants to the rescue: How effective are your unit tests?
Javazone 2019 - Mutants to the rescue: How effective are your unit tests?Paco van Beckhoven
 
おっぴろげJavaEE DevOps
おっぴろげJavaEE DevOpsおっぴろげJavaEE DevOps
おっぴろげJavaEE DevOpsTaiichilow Nagase
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
Selenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IESelenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IEClever Moe
 
Using java8 for unit testing while being backward compatible
Using java8 for unit testing while being backward compatibleUsing java8 for unit testing while being backward compatible
Using java8 for unit testing while being backward compatibleNikola Petrov
 
Advanced Selenium Workshop
Advanced Selenium WorkshopAdvanced Selenium Workshop
Advanced Selenium WorkshopClever Moe
 
San Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker PresentationSan Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker PresentationClever Moe
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modulesRafael Winterhalter
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
New Generation Record/Playback Tools for AJAX Testing
New Generation Record/Playback Tools for AJAX TestingNew Generation Record/Playback Tools for AJAX Testing
New Generation Record/Playback Tools for AJAX TestingClever Moe
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your DatabaseDavid Wheeler
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)Christian Johansen
 
LausanneJUG 2017 - Jigsaw est prêt à tuer le classpath
LausanneJUG 2017 - Jigsaw est prêt à tuer le classpathLausanneJUG 2017 - Jigsaw est prêt à tuer le classpath
LausanneJUG 2017 - Jigsaw est prêt à tuer le classpathAlexis Hassler
 

Mais procurados (20)

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Javazone 2019 - Mutants to the rescue: How effective are your unit tests?
Javazone 2019 - Mutants to the rescue: How effective are your unit tests?Javazone 2019 - Mutants to the rescue: How effective are your unit tests?
Javazone 2019 - Mutants to the rescue: How effective are your unit tests?
 
おっぴろげJavaEE DevOps
おっぴろげJavaEE DevOpsおっぴろげJavaEE DevOps
おっぴろげJavaEE DevOps
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Selenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IESelenium XPath Performance Problems in IE
Selenium XPath Performance Problems in IE
 
Using java8 for unit testing while being backward compatible
Using java8 for unit testing while being backward compatibleUsing java8 for unit testing while being backward compatible
Using java8 for unit testing while being backward compatible
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
 
Advanced Selenium Workshop
Advanced Selenium WorkshopAdvanced Selenium Workshop
Advanced Selenium Workshop
 
Selenium with java
Selenium with javaSelenium with java
Selenium with java
 
San Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker PresentationSan Jose Selenium Meet-up PushToTest TestMaker Presentation
San Jose Selenium Meet-up PushToTest TestMaker Presentation
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
New Generation Record/Playback Tools for AJAX Testing
New Generation Record/Playback Tools for AJAX TestingNew Generation Record/Playback Tools for AJAX Testing
New Generation Record/Playback Tools for AJAX Testing
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
 
Smolder Introduction
Smolder IntroductionSmolder Introduction
Smolder Introduction
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
 
LausanneJUG 2017 - Jigsaw est prêt à tuer le classpath
LausanneJUG 2017 - Jigsaw est prêt à tuer le classpathLausanneJUG 2017 - Jigsaw est prêt à tuer le classpath
LausanneJUG 2017 - Jigsaw est prêt à tuer le classpath
 

Semelhante a Desenvolva plugins para o compilador do Java 8

Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Marcelo de Castro
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekPaco van Beckhoven
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!Paco van Beckhoven
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCPEric Jain
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemGuardSquare
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suiteericholscher
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDISven Ruppert
 
Sakai10 Selenium Workshop
Sakai10 Selenium WorkshopSakai10 Selenium Workshop
Sakai10 Selenium Workshopcoreyjack
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projectsVincent Massol
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringromanovfedor
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web developmentalice yang
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Appschrisb206 chrisb206
 

Semelhante a Desenvolva plugins para o compilador do Java 8 (20)

Turbinando o compilador do Java 8
Turbinando o compilador do Java 8Turbinando o compilador do Java 8
Turbinando o compilador do Java 8
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Mutation testing Bucharest Tech Week
Mutation testing Bucharest Tech WeekMutation testing Bucharest Tech Week
Mutation testing Bucharest Tech Week
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCP
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
 
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion MiddlewareAMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDI
 
Sakai10 Selenium Workshop
Sakai10 Selenium WorkshopSakai10 Selenium Workshop
Sakai10 Selenium Workshop
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projects
 
S313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discoveringS313352 optimizing java device testing with automatic feature discovering
S313352 optimizing java device testing with automatic feature discovering
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Desenvolva plugins para o compilador do Java 8

  • 1. Desenvolva plugins para o compilador do Java 8 JustJava 2013
  • 3. Plugin para o javac 8 0101010101011111000000000101001110001 1100011100000001111010101010110001110 1001001010000101001010101011010110111
  • 4. • Por quê, para quê, desenvolver plugins para o compilador do Java? – Adicionar checagem extras em tempo de compilação – Adicionar transformações de código – Customizar análise do código fonte
  • 5. Este código compila? Teste.java public class Teste { public static final int var = 0; public static void main(String[] args) { int i = 0; System.out.println("#JustJava2013"); try{ i++; }catch(Exception Ex){ } } public static void method(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k){ } class inner{} }
  • 6. Jogo dos 5 erros(!?) public class Teste { public static final int var = 0; public static void main(String[] args) { int i = 0; System.out.println("#JustJava2013"); try{ i++; }catch(Exception Ex){ } } public static void method(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k){ } class inner{} } VAR ex Inner vazio Muitos parâmetros
  • 7. Compilar ou não compilar ????? public class Teste { public static final int var = 0; public static void main(String[] args) { int i = 0; System.out.println("#JustJava2013"); try{ i++; }catch(Exception Ex){ } } public static void method(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k){ } class inner{} }
  • 8. Alterando o comportamento do javac 1. Usar Java 8 (tools.jar no CLASSPATH) 2. Implementar Plugin(*) 3. Implementar TaskListener 4. Implementar a lógica desejada – (TreePathScanner, TreeScanner, TreeVisitor) – Ex: Não aceitar bloco catch vazio 5. Gerar o jar do Plugin – META-INF/services/ • com.sun.source.util.Plugin – NomeTotalmenteQualificadoDoPlugin(*) 6. Compilar usando o plugin – javac -processorpath CodeCheckPlugin.jar - Xplugin:CodeCheckPlugin Teste.java
  • 10. interfaces com.sun.source.util • Plugin – permite definir um plugin para o compilador • SourcePositions – fornece métodos para obter a posição corrente da compilação • TaskListener – fornece um listener para monitorar atividades do javac
  • 11. interface Plugin public class CodeCheckPlugin implements Plugin { @Override public String getName() { return "CodeCheckPlugin"; } @Override public void init(JavacTask task, String... strings) { System.out.println("Iniciando plugin!"); task.setTaskListener(new CheckTaskListener(task)); } }
  • 12. interface TaskListener public class CheckTaskListener implements TaskListener{ @Override public void started(TaskEvent taskEvent) { if(taskEvent.getKind().equals(TaskEvent.Kind.ANALYZE)) { CompilationUnitTree compUnit = taskEvent.getCompilationUnit(); TreePathScanner emptyCacthVisitor = new EmptyCacthVisitor(task); emptyCacthVisitor.scan(compUnit, null); } } @Override public void finished(TaskEvent te) { } }
  • 14. Abstract Syntax Trees Exemplo da Gramática da Linguagem Java normalClassDeclaration : 'class' Identifier typeParameters? ('extends' type)? ('implements' typeList)? classBody public class Teste extends TesteBase{ } class TesteBase{} *AST: abstract syntax tree
  • 15. interface SourcePositions SourcePositions sourcePositions = trees.getSourcePositions(); sourcePositions.getStartPosition (compilationUnitTree, tree); sourcePositions.getEndPosition (compilationUnitTree, tree);
  • 16. Classes (Syntax Trees) com.sun.source.util com.sun.source.tree • public abstract class Trees • public abstract class DocTrees extends Trees • public interface Tree • public enum Tree.Kind • public interface CompilationUnitTree extends Tree • public interface MethodTree extends Tree • public interface BlockTree extends Tree • public interface CatchTree extends Tree • public interface StatementTree extends Tree • public interface ModifiersTree extends Tree • public interface VariableTree extends Tree • public interface PrimitiveTypeTree extends Tree • + um montão de Tree
  • 18. Referências • OpenJDK 8 http://openjdk.java.net/ • Javadoc (javac b74) http://download.java.net/lambda/b74/docs/jdk/api/javac/tree/ • Compiler Grammar http://openjdk.java.net/projects/compiler-grammar/ • Hacking the Java Compiler for Fun and Profit By Raoul-Gabriel Urma • “Java Compiler Plugins”, Oracle Java Magazine January/February 2013, Raoul-Gabriel Urma& Jonathan Gibbons http://www.oraclejavamagazine- digital.com/javamagazine/20130102?sub_id=jFwJyABK25xj#pg56