SlideShare a Scribd company logo
1 of 48
Multi-device Content Display
             &
 Smart Use of Annotation
        Processing
          @gdigugli
          @dbaeli
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




2
We’re working for
A French Insurance Aggregator
mobile & desktop
mobile & desktop
mobile & desktop
In the search of
Effective content display
The story
Effective Content Display              using APT Tooling
• Multi device & languages             • 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/dbaeli/ez18n
Improved i18n
for text display
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
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
java.util.MessageFormat



•   Tiny templating
•   format(“<pattern>”, args)
•   Date, numbers are formatted according to the Locale
•   Options, conditional values easy to use
.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
Improved i18n
Ez18n : improved i18n
• Interfaces representing each .properties
• The methods acts as keys




      Messages.java              Messages.properties
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
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
Extend this pattern for
    Multi-display
Extended to displays
• Add mobile support in @Message declaration
                               DesktopMessages.properties




    Messages.java              MobileMessages.properties
Multiple kind of displays
•   One ResourceBundle by kind of display
•   All driven by @MessageBundle annotation
•   Fallback on the default display
•   Keep the plumbing generated
APT to generate
.properties and ResourceBundle
    classes from annotations
Behind the scene
 How APT works
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)
APT annotations
• Use @Retention, @Target
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
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
Processor code sample
 Processor declaration




 Use a FileObject to generate the content
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
APT tooling
• Maven integration
   maven-processor-plugin (google-code)
• Ant integration
   javac
• IDE integration
   Extend the JDK compilation options
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 !
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
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
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
Go deep in APT usage
     with Ez18n
Demo

• The Stock-watcher available on
  – http://github.com/dbaeli/ez18n
  – In the ez18n-webapp module
• With a desktop browser
• With a mobile browser
Ez18n - Big picture
                                           Messages
                          +loveMeTender() : String [1]
                          +doYouLove( name : String [1] ) : String [1]




                     MessagesMobi leB undle                                                       MessagesDeskto pBundl e

MessagesMobileBundle()                                                         MessagesDesktopBundle()
getMessage( k : String [1], params : Object [1] ) : String [1]
             ey                                                                getMessage( k : String [1], params : Object [1] ) : String [1]
                                                                                            ey
loveMeTender() : String [1]                                                    loveMeTender() : String [1]
doYouLove( name : String [1] ) : String [1]                                    doYouLove( name : String [1] ) : String [1]




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

                                                                                           -delegate    -delegate
                                                                                                         1           1
     Mobi l e                                 Bund leFacto ry                                      Resour ceBundl e                   Desktop

                                    <S>get( serv annotation )
                                                ice,
Ez18n - APT chaining
         • 5 APT processors to
           obtain the default
           pattern
         • Optional CSV files for
           analysis/tooling
From Messages to DesktopMessages.properties

• One property file per interface with
  @MessageBundle
• One property entry per method with @Message
From Messages to MobileMessages.properties

• Another property file is generated for the mobile
  content
• If @Message#mobile is empty, the
  @Message#value is used as fallback
From Messages to
MessagesDesktopBundle.java (1/2)
From Messages to
MessagesDesktopBundle.java (2/2)
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
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
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
Ez18n - Summary




    Maven, javac
   Injection & APT
If you’d like
a JSR for ez18n
please tell us !

                   Ez18n =
                   @Message
                   @MessageBundle
                   Set of Processors
APT virtual mini-track
Sessions
• CON3372 - Advanced Annotation Processing with JSR 269
     Jaroslav Tulach
• CON6489 - Build Your Own Type System for Fun and Profit
     Werner Dietl and Michael Ernst
• CON4469 - Annotations and Annotation Processing: What’s New in JDK 8?
     Joel Borggrén-Franck
• HOL3925 - Hack into Your Compiler!
     Jaroslav Tulach
• CON7928 - Writing Annotation Processors to Aid Your Development Process
     Ian Robertson
Thanks to
• Joseph D. Darcy (APT spec lead) - https://blogs.oracle.com/darcy/


“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)
Thank you !


         Ez18n is on GitHub.
            Just fork it !


          https://github.com/dbaeli/ez18n


48

More Related Content

What's hot

Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and ScalaFilip Krikava
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaTomer Gabel
 
Annotations in PHP: They Exist
Annotations in PHP: They ExistAnnotations in PHP: They Exist
Annotations in PHP: They ExistRafael Dohms
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
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 APIwhite paper
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonsecassuserfadb24
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problemsHolger Schill
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 
IBM Solutions '99 XML and Java: Lessons Learned
IBM Solutions '99 XML and Java: Lessons LearnedIBM Solutions '99 XML and Java: Lessons Learned
IBM Solutions '99 XML and Java: Lessons LearnedTed Leung
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSteve Fort
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
Kotlin Native - C / Swift Interop - ACCU Autmn 2019
Kotlin Native - C / Swift Interop - ACCU Autmn 2019Kotlin Native - C / Swift Interop - ACCU Autmn 2019
Kotlin Native - C / Swift Interop - ACCU Autmn 2019Eamonn Boyle
 
Core java lessons
Core java lessonsCore java lessons
Core java lessonsvivek shah
 

What's hot (20)

Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and Scala
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in Scala
 
Annotations in PHP: They Exist
Annotations in PHP: They ExistAnnotations in PHP: They Exist
Annotations in PHP: They Exist
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
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
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Bean Intro
Bean IntroBean Intro
Bean Intro
 
Xtext beyond the defaults - how to tackle performance problems
Xtext beyond the defaults -  how to tackle performance problemsXtext beyond the defaults -  how to tackle performance problems
Xtext beyond the defaults - how to tackle performance problems
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Dvm
DvmDvm
Dvm
 
En webinar jpa v2final
En webinar jpa v2finalEn webinar jpa v2final
En webinar jpa v2final
 
introduction of Java beans
introduction of Java beansintroduction of Java beans
introduction of Java beans
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 
IBM Solutions '99 XML and Java: Lessons Learned
IBM Solutions '99 XML and Java: Lessons LearnedIBM Solutions '99 XML and Java: Lessons Learned
IBM Solutions '99 XML and Java: Lessons Learned
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
Kotlin Native - C / Swift Interop - ACCU Autmn 2019
Kotlin Native - C / Swift Interop - ACCU Autmn 2019Kotlin Native - C / Swift Interop - ACCU Autmn 2019
Kotlin Native - C / Swift Interop - ACCU Autmn 2019
 
Java beans
Java beansJava beans
Java beans
 
Core java lessons
Core java lessonsCore java lessons
Core java lessons
 

Viewers also liked

All about Arctic Foxes
All about Arctic FoxesAll about Arctic Foxes
All about Arctic Foxeskefiore
 
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 2013gdigugli
 
The Western Native Americans Tim
The Western Native Americans TimThe Western Native Americans Tim
The Western Native Americans Timkefiore
 
Native americans of the woodlands cal
Native americans of the woodlands calNative americans of the woodlands cal
Native americans of the woodlands calkefiore
 
All about Mountain Lions
All about Mountain LionsAll about Mountain Lions
All about Mountain Lionskefiore
 
An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...
An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...
An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...lizbreed
 
Give 'Em The Business
Give 'Em The BusinessGive 'Em The Business
Give 'Em The Businesslizbreed
 
Marketing Research 101
Marketing Research 101Marketing Research 101
Marketing Research 101lizbreed
 
SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()gdigugli
 
GTD Getting things done presentation 06-2015
GTD Getting things done presentation 06-2015GTD Getting things done presentation 06-2015
GTD Getting things done presentation 06-2015Raphael Monteiro
 
Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...
Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...
Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...lizbreed
 
Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...
Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...
Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...lizbreed
 

Viewers also liked (15)

All about Arctic Foxes
All about Arctic FoxesAll about Arctic Foxes
All about Arctic Foxes
 
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
 
The Western Native Americans Tim
The Western Native Americans TimThe Western Native Americans Tim
The Western Native Americans Tim
 
Koala
KoalaKoala
Koala
 
2011/2012
2011/20122011/2012
2011/2012
 
Native americans of the woodlands cal
Native americans of the woodlands calNative americans of the woodlands cal
Native americans of the woodlands cal
 
All about Mountain Lions
All about Mountain LionsAll about Mountain Lions
All about Mountain Lions
 
An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...
An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...
An Economic Gardeing Project in Michigan: Libraries as Strategic Partners in ...
 
Give 'Em The Business
Give 'Em The BusinessGive 'Em The Business
Give 'Em The Business
 
Marketing Research 101
Marketing Research 101Marketing Research 101
Marketing Research 101
 
SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()SoftShake 2015 - DomainModel.stream()
SoftShake 2015 - DomainModel.stream()
 
Active Job - Rails
Active Job - RailsActive Job - Rails
Active Job - Rails
 
GTD Getting things done presentation 06-2015
GTD Getting things done presentation 06-2015GTD Getting things done presentation 06-2015
GTD Getting things done presentation 06-2015
 
Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...
Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...
Economic Gardening &amp; the Role of Libraries in Serving Entrepreneurs, Mich...
 
Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...
Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...
Role of Libraries in Serving Entrepreneurs, Creating Entrepreneurial Communit...
 

Similar to JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Annotation Processing

JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentationjuliasceasor
 
Xcode, Basics and Beyond
Xcode, Basics and BeyondXcode, Basics and Beyond
Xcode, Basics and Beyondrsebbe
 
"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
 
Python_for_Visual_Effects_and_Animation_Pipelines
Python_for_Visual_Effects_and_Animation_PipelinesPython_for_Visual_Effects_and_Animation_Pipelines
Python_for_Visual_Effects_and_Animation_PipelinesRussell Darling
 
Bootstrapping iPhone Development
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone DevelopmentThoughtWorks
 
Java Chapter 2 Overview.ppt
Java Chapter 2 Overview.pptJava Chapter 2 Overview.ppt
Java Chapter 2 Overview.pptMiltonMolla1
 
Java Chapter 2 Overview.ppt
Java Chapter 2 Overview.pptJava Chapter 2 Overview.ppt
Java Chapter 2 Overview.pptMiltonMolla1
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...Maarten Balliauw
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2Eric Nelson
 
.Net overviewrajnish
.Net overviewrajnish.Net overviewrajnish
.Net overviewrajnishRajnish Kalla
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOLMicro Focus
 
Getting started with titanium
Getting started with titaniumGetting started with titanium
Getting started with titaniumNaga Harish M
 
Ankit Chohan - Java
Ankit Chohan - JavaAnkit Chohan - Java
Ankit Chohan - JavaAnkit Chohan
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...Maarten Balliauw
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!Alessandro Giorgetti
 
ACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdfACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdfAnyscale
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Julie Lerman
 

Similar to JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Annotation Processing (20)

JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentation
 
Xcode, Basics and Beyond
Xcode, Basics and BeyondXcode, Basics and Beyond
Xcode, Basics and Beyond
 
"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...
 
Python_for_Visual_Effects_and_Animation_Pipelines
Python_for_Visual_Effects_and_Animation_PipelinesPython_for_Visual_Effects_and_Animation_Pipelines
Python_for_Visual_Effects_and_Animation_Pipelines
 
Bootstrapping iPhone Development
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone Development
 
Java Chapter 2 Overview.ppt
Java Chapter 2 Overview.pptJava Chapter 2 Overview.ppt
Java Chapter 2 Overview.ppt
 
Java Chapter 2 Overview.ppt
Java Chapter 2 Overview.pptJava Chapter 2 Overview.ppt
Java Chapter 2 Overview.ppt
 
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
NDC Sydney 2019 - Microservices for building an IDE – The innards of JetBrain...
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
 
.Net overviewrajnish
.Net overviewrajnish.Net overviewrajnish
.Net overviewrajnish
 
System software
System softwareSystem software
System software
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOL
 
Getting started with titanium
Getting started with titaniumGetting started with titanium
Getting started with titanium
 
Ankit Chohan - Java
Ankit Chohan - JavaAnkit Chohan - Java
Ankit Chohan - Java
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!TypeScript . the JavaScript developer best friend!
TypeScript . the JavaScript developer best friend!
 
java slides
java slidesjava slides
java slides
 
ACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdfACM Sunnyvale Meetup.pdf
ACM Sunnyvale Meetup.pdf
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
 

JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Annotation Processing

  • 1. Multi-device Content Display & Smart Use of Annotation Processing @gdigugli @dbaeli
  • 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 2
  • 3. We’re working for A French Insurance Aggregator
  • 7. In the search of Effective content display
  • 8. The story Effective Content Display using APT Tooling • Multi device & languages • 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/dbaeli/ez18n
  • 10. 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
  • 11. 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
  • 12. java.util.MessageFormat • Tiny templating • format(“<pattern>”, args) • Date, numbers are formatted according to the Locale • Options, conditional values easy to use
  • 13. .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
  • 15. Ez18n : improved i18n • Interfaces representing each .properties • The methods acts as keys Messages.java Messages.properties
  • 16. 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
  • 17. 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
  • 18. Extend this pattern for Multi-display
  • 19. Extended to displays • Add mobile support in @Message declaration DesktopMessages.properties Messages.java MobileMessages.properties
  • 20. Multiple kind of displays • One ResourceBundle by kind of display • All driven by @MessageBundle annotation • Fallback on the default display • Keep the plumbing generated
  • 21. APT to generate .properties and ResourceBundle classes from annotations
  • 22. Behind the scene How APT works
  • 23. 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)
  • 24. APT annotations • Use @Retention, @Target
  • 25. 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
  • 26. 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
  • 27. Processor code sample  Processor declaration  Use a FileObject to generate the content
  • 28. 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
  • 29. APT tooling • Maven integration  maven-processor-plugin (google-code) • Ant integration  javac • IDE integration  Extend the JDK compilation options
  • 30. 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 !
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. Go deep in APT usage with Ez18n
  • 35. Demo • The Stock-watcher available on – http://github.com/dbaeli/ez18n – In the ez18n-webapp module • With a desktop browser • With a mobile browser
  • 36. Ez18n - Big picture Messages +loveMeTender() : String [1] +doYouLove( name : String [1] ) : String [1] MessagesMobi leB undle MessagesDeskto pBundl e MessagesMobileBundle() MessagesDesktopBundle() getMessage( k : String [1], params : Object [1] ) : String [1] ey getMessage( k : String [1], params : Object [1] ) : String [1] ey loveMeTender() : String [1] loveMeTender() : String [1] doYouLove( name : String [1] ) : String [1] doYouLove( name : String [1] ) : String [1] «annotate» «annotate» «inject» «inject» -delegate -delegate 1 1 Mobi l e Bund leFacto ry Resour ceBundl e Desktop <S>get( serv annotation ) ice,
  • 37. Ez18n - APT chaining • 5 APT processors to obtain the default pattern • Optional CSV files for analysis/tooling
  • 38. From Messages to DesktopMessages.properties • One property file per interface with @MessageBundle • One property entry per method with @Message
  • 39. From Messages to MobileMessages.properties • Another property file is generated for the mobile content • If @Message#mobile is empty, the @Message#value is used as fallback
  • 42. 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
  • 43. 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
  • 44. 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
  • 45. Ez18n - Summary Maven, javac Injection & APT
  • 46. If you’d like a JSR for ez18n please tell us ! Ez18n = @Message @MessageBundle Set of Processors
  • 47. APT virtual mini-track Sessions • CON3372 - Advanced Annotation Processing with JSR 269  Jaroslav Tulach • CON6489 - Build Your Own Type System for Fun and Profit  Werner Dietl and Michael Ernst • CON4469 - Annotations and Annotation Processing: What’s New in JDK 8?  Joel Borggrén-Franck • HOL3925 - Hack into Your Compiler!  Jaroslav Tulach • CON7928 - Writing Annotation Processors to Aid Your Development Process  Ian Robertson Thanks to • Joseph D. Darcy (APT spec lead) - https://blogs.oracle.com/darcy/ “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)
  • 48. Thank you ! Ez18n is on GitHub. Just fork it ! https://github.com/dbaeli/ez18n 48