SlideShare a Scribd company logo
Smart Use of Annotation
              Processing - APT

                  @gdigugli
                  @dbaeli



Mars JUG 2013
Speakers
@dbaeli - Dimitri BAELI             @gdigugli - Gilles Di Guglielmo
• Java developer since 1999         • Java developer since 1999
• R&D Team Mentor at                • Software architect at



• Coder, DevOps, Agile Coach        • ILOG - IBM
    – From idea to production           2D graphic toolkit
• eXo Platform                          Rule engine
    • VP Quality                    • Prima-Solutions
                                        Services platform for J2EE
                                        Domain models code generators




Mars JUG 2013                                                            2
Content Display Management




Mars JUG 2013
The story
Effective Content Display                using APT Tooling
• Content Management                     • APT Engine
    Labels                              • APT Processors
    Layout & images
                                             Generate technical code
• Clean code                                 Generate reports
    Strong Quality                          Generate patterns
    Easy Maintenance       based on i18n
                               • @Message
                               • @MessageBundle
                               • Dedicated APT Processors

                https://github.com/lesfurets/ez18n


Mars JUG 2013
Improved i18n
                for text display




Mars JUG 2013
Java i18n pattern
• The JDK default tooling to:
     Dynamically bind the content
     Usable for Texts, but also CSS and images (urls)
• Tooling :
     java.util.ResourceBundle : for .properties reading
     java.util.MessageFormat : tiny templating
     .properties files with naming pattern


Mars JUG 2013
java.util.ResourceBundle
• The .properties loader for a given Locale
• Key / Value in .properties
• Naming convention for the storage
    Messages_en_EN.properties

           Language   Country




Mars JUG 2013
java.util.MessageFormat




•    Tiny templating
•    format(“<pattern>”, args)
•    Date, numbers are formatted according to the Locale
•    Options, conditional values easy to use

    Mars JUG 2013
.properties issues
• Low quality control
    – Keys are strings in the code
    – Poor IDE support
         • No warning on unused or wrong keys
    – Encoding Hell
         • use uxxxx or you’re in trouble
• Forces you to maintain two files in sync
    – key declaration / value in .properties
    – Key usage in the .java files


Mars JUG 2013
Improved i18n




Mars JUG 2013
Ez18n : improved i18n
• Interfaces representing each .properties
• The methods acts as keys




           Messages.java         Messages.properties


Mars JUG 2013
Annotations and Code generation
• Same pattern as in GWT, but for J2SE
• New Annotations in the code :
     @MessageBundle to mark interfaces
          represents a ResourceBundle
     @Message to mark methods
         represents a localization key
• Generate :
     .properties file (for ‘default’)
     A ResourceBundle for each .properties
     Manage other languages out-side your code

Mars JUG 2013
Improved i18n benefits
• Now you can
     Refactor your keys
     Maintain the ‘default’ in Java
     Never change a .properties file for default locale
• And use it with other libs:
     GWT (done on GitHub)
     Even JQuery, Dojo, CoffeeScript (planned)
 We called that ez18n

Mars JUG 2013
APT to generate
  .properties and ResourceBundle
      classes from annotations



Mars JUG 2013
Behind the scene
                 How APT works




Mars JUG 2013
APT basics
•   APT - Annotation Processing Tool
•   Kind of old-school pre-processing
•   Standard in JDK6+ (JSR 269)
•   No runtime overload
•   Based on annotations in source code
•   Standard since JDK 1.6 (available in Sun JDK
    1.5)

Mars JUG 2013
APT annotations
• Use @Retention, @Target




Mars JUG 2013
APT Processors
• javax.annotation.processing.Processor
• Code parsing similar to Reflection
     No need of compiled code
     Some limitations
• 2 key elements :
     @SupportedAnnotationTypes to declare the
      matching annotations
     FileObject : the future generated file

Mars JUG 2013
SPI Discovery
•   SPI - Service Provider Interface
•   Is a built in way to discover Classes at runtime
•   Based on Interface implementation
•   @see java.util.ServiceLoader
     /META-INF/services/
    javax.annotation.processing.Processor



Mars JUG 2013
Similarities with java.lang.reflect
Java.lang.reflect            Javax.annotation.processing
java.lang.Class              TypeElement
Constructor                  ExecutableElement
Field, Parameter             VariableElement
Method                       ExecutableElement
java.lang.Package            PackageElement


•   NO Class.newInstance()
•   NO instanceOf, NO isAssignable()
•   NO getConstructor, getMethod, …
•   Weak inheritance support

Mars JUG 2013
Processor code sample
 Processor declaration




 Use a FileObject to generate the content




Mars JUG 2013
APT command line
javac
    -cp $CLASSPATH
    -proc:only                  Or -proc:none
    -encoding UTF-8
    -processor $PROCESSOR         processors fqcn list
    -d $PROJECT_HOMEtargetclasses
    -s $PROJECT_HOMEtargetgenerated-sourcesapt
    -sourcepath $SOURCE_PATH
    -verbose
    $FILES                              optional




Mars JUG 2013
APT tooling
• Maven integration
     maven-processor-plugin (google-code)
     Maven java compiler simply
• Ant integration
     javac
• IDE integration
     Extend the JDK compilation options


Mars JUG 2013
APT usages
• Generate required repetitive code :
     Not always possible at runtime
     Unit tests, JMX declarations
     Utility code with coverage and debug
• Build your reports on your code
     Your metrics without runtime overload
     Even fail the build if you want !



Mars JUG 2013
One or Two phase compilation
• One phase :
     APT runs during the compilation
     Generated code is directly produced as bytecode
      (.class)
     Harder to debug (no .java created)
 Two phases : “proc:only”
     javac with proc:only then with proc:none
     Creates .java files in the sourcepath


Mars JUG 2013
Problems with APT
• Beware of the “Generate” golden hammer
     generate needed code
• APT Processors can be tricky:
     hard to test / maintain
     bad error management (hidden errors !)
     Not really (well) documented
• No built-in templating mechanism
• Enforced file path creation
• Beware of maven parallel builds
     Because javac is not thread safe

Mars JUG 2013
It’s time to convince your team
• APT parses the source code to generate
     Java Files & .class, Reports (.csv, …)
     Build log information or even build failures
• It allows you to have a source level DSL
     Annotate your code & Generate the plumbing
     Compile / Debug the generated code
• APT framework is compact


Mars JUG 2013
Go deep in APT usage
                     with Ez18n




Mars JUG 2013
Demo
• The Stock-watcher available on
    – http://github.com/lesfurets/ez18n
    – In the ez18n-webapp module
    – Derived from a GWT Sample
• With a desktop browser
• With a mobile browser



Mars JUG 2013
Ez18n - Big picture
                                      Messages
                      +loveMeTender() : String [ 1]
                      +doYouLove( name : String [ 1] ) : S tring [1]




                   MessagesMobile Bundle                                                      MessagesDe sktopBundle

MessagesMobileBundle()                                                       MessagesDesktopBundle()
getMessage( key : String [ 1] , params : Object [1] ) : String [ 1]          getMessage( key : String [ 1] , params : Object [1] ) : String [ 1]
loveMeTender() : String [1]                                                  loveMeTender() : String [1]
doYouLove( name : S tring [1] ) : String [1]                                 doYouLove( name : S tring [1] ) : String [1]




           «annotate»                                                                                                                  «annotate»
                               «inject »                               «inject »

                                                                                        -delegate -delegate 1
                                                                                                   1
    Mobile                             BundleFactory                                           Re sourceBundle                 De sktop

                                <S >get ( service, annotation )




 Mars JUG 2013
Ez18n - APT chaining
                         • 5 APT processors to
                           obtain the default
                           pattern
                         • Optional CSV files for
                           analysis/tooling




Mars JUG 2013
From Messages to DesktopMessages.properties

• One property file per interface with
  @MessageBundle
• One property entry per method with @Message




Mars JUG 2013
From Messages to
            MessagesDesktopBundle.java (1/2)




Mars JUG 2013
From Messages to
            MessagesDesktopBundle.java (2/2)




Mars JUG 2013
From Messages to
     META-INF/services/org.ez18n.sample.Messages




                    • Using META-INF/services to inject the
                      mobile & desktop implementation
                    • The two implementations could be
                      filtered at runtime using annotations
                      and java.util.ServiceLoader
                        @Mobile
                        @Desktop



Mars JUG 2013
A factory for the Messages implementations
  • Using java.util.ServiceLoader to inject the interface with
    @MessageBundle
  • @Desktop and @Mobile used to filter the injection result




Mars JUG 2013
Client code sample with JUnit
• Some basic JUnit test using the API

                                          The unit tests are
                                          generated using APT
                                          too 



                         BundleFactory.get(…) usage in the test
                         @Before to retrieve the bundle
                         implementation




Mars JUG 2013
Ez18n - Summary




                    Maven, javac
                   Injection & APT




Mars JUG 2013
If you’d like
                a JSR for ez18n
                please tell us !

                                   Ez18n =
                                   @Message
                                   @MessageBundle
                                   Set of Processors




Mars JUG 2013
APT Adoption
“As the lead engineer on JSR 269 in JDK 6, I'd be
heartened to see greater adoption and use of
annotation processing by Java developers.”
      Joseph D. Darcy (Oracle)




Mars JUG 2013
APT JDK 8
• possibilité d’ajouter une annotation sur les
  types d’objets (JSR 308)
• possibilité de répéter une annotation sur une
  déclaration (JEP 120)
• portage de l’API “javax.lang.model” au
  runtime pour qu’elle ne soit pas disponible
  uniquement à la compilation (JEP 119)
• Voir les notes :
  http://blog.soat.fr/2012/11/devoxx-2012-jsr-
  308-annotations-on-java-types/
Mars JUG 2013
JavaOne 2012
                   APT virtual mini-track
• Sessions
    – Advanced Annotation Processing with JSR 269
         • Jaroslav Tulach
    – Build Your Own Type System for Fun and Profit
         • Werner Dietl and Michael Ernst
    – Annotations and Annotation Processing: What’s New in JDK 8?
         • Joel Borggrén-Franck
    – Hack into Your Compiler!
         • Jaroslav Tulach
    – Writing Annotation Processors to Aid Your Development Process
         • Ian Robertson

• Thanks to
    – Joseph D. Darcy (APT spec lead) - https://blogs.oracle.com/darcy/




Mars JUG 2013
Thank you !


                Ez18n is on GitHub
                   Just fork it !


                https://github.com/lesfurets/ez18n



Mars JUG 2013                                        43

More Related Content

What's hot

Itinerary Website (Web Development Document)
Itinerary Website (Web Development Document)Itinerary Website (Web Development Document)
Itinerary Website (Web Development Document)
Traitet Thepbandansuk
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
Madhura Bhalerao
 
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
BIOVIA
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
Md. Tanvir Hossain
 
Java1
Java1Java1
Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kollipara
Manjula Kollipara
 
Dvm
DvmDvm
WORKS 11 Presentation
WORKS 11 PresentationWORKS 11 Presentation
WORKS 11 Presentation
dgarijo
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
white paper
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)
Thomas Lundström
 

What's hot (12)

Itinerary Website (Web Development Document)
Itinerary Website (Web Development Document)Itinerary Website (Web Development Document)
Itinerary Website (Web Development Document)
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Java1
Java1Java1
Java1
 
Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kollipara
 
Dvm
DvmDvm
Dvm
 
WORKS 11 Presentation
WORKS 11 PresentationWORKS 11 Presentation
WORKS 11 Presentation
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)
 

Similar to Smart annotation processing - Paris JUG

Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
java slides
java slidesjava slides
java slides
RizwanTariq18
 
ACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdfACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdf
Anyscale
 
3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k
IBM
 
Rad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh K
Roopa Nadkarni
 
Java Programming concept
Java Programming concept Java Programming concept
Java Programming concept
Prakash Poudel
 
Letest
LetestLetest
Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)
DECK36
 
Java-Unit-I.ppt
Java-Unit-I.pptJava-Unit-I.ppt
Java-Unit-I.ppt
RameswarGprec
 
Java compilation
Java compilationJava compilation
Java compilation
Mike Kucera
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
Dataconomy Media
 
What is Google App Engine?
What is Google App Engine?What is Google App Engine?
What is Google App Engine?
weschwee
 
Spring Tooling: What's new and what's coming
Spring Tooling: What's new and what's comingSpring Tooling: What's new and what's coming
Spring Tooling: What's new and what's coming
martinlippert
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repository
nobby
 
desktop_resume
desktop_resumedesktop_resume
desktop_resume
Chris Markle
 
Gwt and JSR 269's Pluggable Annotation Processing API
Gwt and JSR 269's Pluggable Annotation Processing APIGwt and JSR 269's Pluggable Annotation Processing API
Gwt and JSR 269's Pluggable Annotation Processing API
Arnaud Tournier
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Phaniu
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
javeed_mhd
 
Java Basics
Java BasicsJava Basics
Java Basics
Khan625
 
Java in Mule
Java in MuleJava in Mule
Java in Mule
Shahid Shaik
 

Similar to Smart annotation processing - Paris JUG (20)

Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
java slides
java slidesjava slides
java slides
 
ACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdfACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdf
 
3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k3 rad extensibility-srilakshmi_s_rajesh_k
3 rad extensibility-srilakshmi_s_rajesh_k
 
Rad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh KRad Extensibility - Srilakshmi S Rajesh K
Rad Extensibility - Srilakshmi S Rajesh K
 
Java Programming concept
Java Programming concept Java Programming concept
Java Programming concept
 
Letest
LetestLetest
Letest
 
Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)
 
Java-Unit-I.ppt
Java-Unit-I.pptJava-Unit-I.ppt
Java-Unit-I.ppt
 
Java compilation
Java compilationJava compilation
Java compilation
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
 
What is Google App Engine?
What is Google App Engine?What is Google App Engine?
What is Google App Engine?
 
Spring Tooling: What's new and what's coming
Spring Tooling: What's new and what's comingSpring Tooling: What's new and what's coming
Spring Tooling: What's new and what's coming
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repository
 
desktop_resume
desktop_resumedesktop_resume
desktop_resume
 
Gwt and JSR 269's Pluggable Annotation Processing API
Gwt and JSR 269's Pluggable Annotation Processing APIGwt and JSR 269's Pluggable Annotation Processing API
Gwt and JSR 269's Pluggable Annotation Processing API
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java in Mule
Java in MuleJava in Mule
Java in Mule
 

More from gdigugli

SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()
gdigugli
 
Rock solid UI modeling using annotation processing - CodeGeneration 2013
Rock solid UI modeling using annotation processing - CodeGeneration 2013Rock solid UI modeling using annotation processing - CodeGeneration 2013
Rock solid UI modeling using annotation processing - CodeGeneration 2013
gdigugli
 
Ez18n crowdsourcing
Ez18n crowdsourcingEz18n crowdsourcing
Ez18n crowdsourcing
gdigugli
 
Ez18n hands on - Annotation Processing Tool par l'exemple
Ez18n hands on - Annotation Processing Tool par l'exempleEz18n hands on - Annotation Processing Tool par l'exemple
Ez18n hands on - Annotation Processing Tool par l'exemple
gdigugli
 
Ez18n theorie encoding gouvernance
Ez18n theorie encoding gouvernanceEz18n theorie encoding gouvernance
Ez18n theorie encoding gouvernance
gdigugli
 
Ez18n Annotation Processing Tool in a nutshell
Ez18n Annotation Processing Tool in a nutshellEz18n Annotation Processing Tool in a nutshell
Ez18n Annotation Processing Tool in a nutshell
gdigugli
 
DevOps illustré : la jungle de la configuration d'une application
DevOps illustré : la jungle de la configuration d'une applicationDevOps illustré : la jungle de la configuration d'une application
DevOps illustré : la jungle de la configuration d'une application
gdigugli
 

More from gdigugli (7)

SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()
 
Rock solid UI modeling using annotation processing - CodeGeneration 2013
Rock solid UI modeling using annotation processing - CodeGeneration 2013Rock solid UI modeling using annotation processing - CodeGeneration 2013
Rock solid UI modeling using annotation processing - CodeGeneration 2013
 
Ez18n crowdsourcing
Ez18n crowdsourcingEz18n crowdsourcing
Ez18n crowdsourcing
 
Ez18n hands on - Annotation Processing Tool par l'exemple
Ez18n hands on - Annotation Processing Tool par l'exempleEz18n hands on - Annotation Processing Tool par l'exemple
Ez18n hands on - Annotation Processing Tool par l'exemple
 
Ez18n theorie encoding gouvernance
Ez18n theorie encoding gouvernanceEz18n theorie encoding gouvernance
Ez18n theorie encoding gouvernance
 
Ez18n Annotation Processing Tool in a nutshell
Ez18n Annotation Processing Tool in a nutshellEz18n Annotation Processing Tool in a nutshell
Ez18n Annotation Processing Tool in a nutshell
 
DevOps illustré : la jungle de la configuration d'une application
DevOps illustré : la jungle de la configuration d'une applicationDevOps illustré : la jungle de la configuration d'une application
DevOps illustré : la jungle de la configuration d'une application
 

Recently uploaded

GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 

Recently uploaded (20)

GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 

Smart annotation processing - Paris JUG

  • 1. Smart Use of Annotation Processing - APT @gdigugli @dbaeli Mars JUG 2013
  • 2. Speakers @dbaeli - Dimitri BAELI @gdigugli - Gilles Di Guglielmo • Java developer since 1999 • Java developer since 1999 • R&D Team Mentor at • Software architect at • Coder, DevOps, Agile Coach • ILOG - IBM – From idea to production  2D graphic toolkit • eXo Platform  Rule engine • VP Quality • Prima-Solutions  Services platform for J2EE  Domain models code generators Mars JUG 2013 2
  • 4. The story Effective Content Display using APT Tooling • Content Management • APT Engine  Labels • APT Processors  Layout & images  Generate technical code • Clean code  Generate reports  Strong Quality  Generate patterns  Easy Maintenance based on i18n • @Message • @MessageBundle • Dedicated APT Processors https://github.com/lesfurets/ez18n Mars JUG 2013
  • 5. Improved i18n for text display Mars JUG 2013
  • 6. Java i18n pattern • The JDK default tooling to:  Dynamically bind the content  Usable for Texts, but also CSS and images (urls) • Tooling :  java.util.ResourceBundle : for .properties reading  java.util.MessageFormat : tiny templating  .properties files with naming pattern Mars JUG 2013
  • 7. java.util.ResourceBundle • The .properties loader for a given Locale • Key / Value in .properties • Naming convention for the storage Messages_en_EN.properties Language Country Mars JUG 2013
  • 8. java.util.MessageFormat • Tiny templating • format(“<pattern>”, args) • Date, numbers are formatted according to the Locale • Options, conditional values easy to use Mars JUG 2013
  • 9. .properties issues • Low quality control – Keys are strings in the code – Poor IDE support • No warning on unused or wrong keys – Encoding Hell • use uxxxx or you’re in trouble • Forces you to maintain two files in sync – key declaration / value in .properties – Key usage in the .java files Mars JUG 2013
  • 11. Ez18n : improved i18n • Interfaces representing each .properties • The methods acts as keys Messages.java Messages.properties Mars JUG 2013
  • 12. Annotations and Code generation • Same pattern as in GWT, but for J2SE • New Annotations in the code :  @MessageBundle to mark interfaces  represents a ResourceBundle  @Message to mark methods represents a localization key • Generate :  .properties file (for ‘default’)  A ResourceBundle for each .properties  Manage other languages out-side your code Mars JUG 2013
  • 13. Improved i18n benefits • Now you can  Refactor your keys  Maintain the ‘default’ in Java  Never change a .properties file for default locale • And use it with other libs:  GWT (done on GitHub)  Even JQuery, Dojo, CoffeeScript (planned)  We called that ez18n Mars JUG 2013
  • 14. APT to generate .properties and ResourceBundle classes from annotations Mars JUG 2013
  • 15. Behind the scene How APT works Mars JUG 2013
  • 16. APT basics • APT - Annotation Processing Tool • Kind of old-school pre-processing • Standard in JDK6+ (JSR 269) • No runtime overload • Based on annotations in source code • Standard since JDK 1.6 (available in Sun JDK 1.5) Mars JUG 2013
  • 17. APT annotations • Use @Retention, @Target Mars JUG 2013
  • 18. APT Processors • javax.annotation.processing.Processor • Code parsing similar to Reflection  No need of compiled code  Some limitations • 2 key elements :  @SupportedAnnotationTypes to declare the matching annotations  FileObject : the future generated file Mars JUG 2013
  • 19. SPI Discovery • SPI - Service Provider Interface • Is a built in way to discover Classes at runtime • Based on Interface implementation • @see java.util.ServiceLoader  /META-INF/services/ javax.annotation.processing.Processor Mars JUG 2013
  • 20. Similarities with java.lang.reflect Java.lang.reflect Javax.annotation.processing java.lang.Class TypeElement Constructor ExecutableElement Field, Parameter VariableElement Method ExecutableElement java.lang.Package PackageElement • NO Class.newInstance() • NO instanceOf, NO isAssignable() • NO getConstructor, getMethod, … • Weak inheritance support Mars JUG 2013
  • 21. Processor code sample  Processor declaration  Use a FileObject to generate the content Mars JUG 2013
  • 22. APT command line javac -cp $CLASSPATH -proc:only Or -proc:none -encoding UTF-8 -processor $PROCESSOR processors fqcn list -d $PROJECT_HOMEtargetclasses -s $PROJECT_HOMEtargetgenerated-sourcesapt -sourcepath $SOURCE_PATH -verbose $FILES optional Mars JUG 2013
  • 23. APT tooling • Maven integration  maven-processor-plugin (google-code)  Maven java compiler simply • Ant integration  javac • IDE integration  Extend the JDK compilation options Mars JUG 2013
  • 24. APT usages • Generate required repetitive code :  Not always possible at runtime  Unit tests, JMX declarations  Utility code with coverage and debug • Build your reports on your code  Your metrics without runtime overload  Even fail the build if you want ! Mars JUG 2013
  • 25. One or Two phase compilation • One phase :  APT runs during the compilation  Generated code is directly produced as bytecode (.class)  Harder to debug (no .java created)  Two phases : “proc:only”  javac with proc:only then with proc:none  Creates .java files in the sourcepath Mars JUG 2013
  • 26. Problems with APT • Beware of the “Generate” golden hammer  generate needed code • APT Processors can be tricky:  hard to test / maintain  bad error management (hidden errors !)  Not really (well) documented • No built-in templating mechanism • Enforced file path creation • Beware of maven parallel builds  Because javac is not thread safe Mars JUG 2013
  • 27. It’s time to convince your team • APT parses the source code to generate  Java Files & .class, Reports (.csv, …)  Build log information or even build failures • It allows you to have a source level DSL  Annotate your code & Generate the plumbing  Compile / Debug the generated code • APT framework is compact Mars JUG 2013
  • 28. Go deep in APT usage with Ez18n Mars JUG 2013
  • 29. Demo • The Stock-watcher available on – http://github.com/lesfurets/ez18n – In the ez18n-webapp module – Derived from a GWT Sample • With a desktop browser • With a mobile browser Mars JUG 2013
  • 30. Ez18n - Big picture Messages +loveMeTender() : String [ 1] +doYouLove( name : String [ 1] ) : S tring [1] MessagesMobile Bundle MessagesDe sktopBundle MessagesMobileBundle() MessagesDesktopBundle() getMessage( key : String [ 1] , params : Object [1] ) : String [ 1] getMessage( key : String [ 1] , params : Object [1] ) : String [ 1] loveMeTender() : String [1] loveMeTender() : String [1] doYouLove( name : S tring [1] ) : String [1] doYouLove( name : S tring [1] ) : String [1] «annotate» «annotate» «inject » «inject » -delegate -delegate 1 1 Mobile BundleFactory Re sourceBundle De sktop <S >get ( service, annotation ) Mars JUG 2013
  • 31. Ez18n - APT chaining • 5 APT processors to obtain the default pattern • Optional CSV files for analysis/tooling Mars JUG 2013
  • 32. From Messages to DesktopMessages.properties • One property file per interface with @MessageBundle • One property entry per method with @Message Mars JUG 2013
  • 33. From Messages to MessagesDesktopBundle.java (1/2) Mars JUG 2013
  • 34. From Messages to MessagesDesktopBundle.java (2/2) Mars JUG 2013
  • 35. From Messages to META-INF/services/org.ez18n.sample.Messages • Using META-INF/services to inject the mobile & desktop implementation • The two implementations could be filtered at runtime using annotations and java.util.ServiceLoader  @Mobile  @Desktop Mars JUG 2013
  • 36. A factory for the Messages implementations • Using java.util.ServiceLoader to inject the interface with @MessageBundle • @Desktop and @Mobile used to filter the injection result Mars JUG 2013
  • 37. Client code sample with JUnit • Some basic JUnit test using the API The unit tests are generated using APT too  BundleFactory.get(…) usage in the test @Before to retrieve the bundle implementation Mars JUG 2013
  • 38. Ez18n - Summary Maven, javac Injection & APT Mars JUG 2013
  • 39. If you’d like a JSR for ez18n please tell us ! Ez18n = @Message @MessageBundle Set of Processors Mars JUG 2013
  • 40. APT Adoption “As the lead engineer on JSR 269 in JDK 6, I'd be heartened to see greater adoption and use of annotation processing by Java developers.” Joseph D. Darcy (Oracle) Mars JUG 2013
  • 41. APT JDK 8 • possibilité d’ajouter une annotation sur les types d’objets (JSR 308) • possibilité de répéter une annotation sur une déclaration (JEP 120) • portage de l’API “javax.lang.model” au runtime pour qu’elle ne soit pas disponible uniquement à la compilation (JEP 119) • Voir les notes : http://blog.soat.fr/2012/11/devoxx-2012-jsr- 308-annotations-on-java-types/ Mars JUG 2013
  • 42. JavaOne 2012 APT virtual mini-track • Sessions – Advanced Annotation Processing with JSR 269 • Jaroslav Tulach – Build Your Own Type System for Fun and Profit • Werner Dietl and Michael Ernst – Annotations and Annotation Processing: What’s New in JDK 8? • Joel Borggrén-Franck – Hack into Your Compiler! • Jaroslav Tulach – Writing Annotation Processors to Aid Your Development Process • Ian Robertson • Thanks to – Joseph D. Darcy (APT spec lead) - https://blogs.oracle.com/darcy/ Mars JUG 2013
  • 43. Thank you ! Ez18n is on GitHub Just fork it ! https://github.com/lesfurets/ez18n Mars JUG 2013 43