SlideShare uma empresa Scribd logo
1 de 54
Annotation pour les g33ks
T H E E N T E R P R I S E S O C I A L P L AT F O R M




                                                       Julien Viet
                                                  FEBRUARY 2013
JULIEN VIET
− Contact
  − julien@julienviet.com
  − @julienviet
  − http://github.com/vietj
− Open source depuis + de 10 ans (déjà)
  − Avec l’opportunité de pouvoir en vivre
     − 2003  2008 JBoss
     − 2008  2013 Exoplatform
  − Mission officielle: le portail pour Java EE
     − Le portail pour Java EE (officiel)

− Marsjug Leader

                 www.exoplatform.com - Copyright 2012 eXo Platform   2
MISSION OFFICIEUSE
− CRaSH : le shell pour la JVM
− Wikbook : écrire de la doc au format wiki
 pour docbook dans des projets Java en
 incluant du source code
− Juzu : que nous allons voir




            www.exoplatform.com - Copyright 2012 eXo Platform   3
E X O P L AT F O R M

− The Enterprise Social Platform
  − Social collaboration Solution
  − Open Source and Enterprise Ready
  − Highly extensible platform
− Notre blog
  − http://blog.exoplatform.com




               www.exoplatform.com - Copyright 2012 eXo Platform   4
FEATURES




            All in a Single Platform

       www.exoplatform.com - Copyright 2012 eXo Platform   5
INTRO A JUZU




www.exoplatform.com - Copyright 2012 eXo Platform   6
JUZU
− Framework MVC
  − Apprentissage rapide
  − Simplicité et liberté
− Plusieurs runtimes
  − Servlet
  − Portlet
  − Vert.x (poc)
− Motivation
  − Besoin d’un framework simple et puissant pour
    portlet/servlet

               www.exoplatform.com - Copyright 2012 eXo Platform   7
www.exoplatform.com - Copyright 2012 eXo Platform   8
USINE A PLUGIN
− A la compilation
  − Generer de la configuration, du code source,
    des resources
  − Faire échouer la compilation
− A l’execution
  − Interception des requêtes
  − Déclarer des beans dans le container
    d’injection


              www.exoplatform.com - Copyright 2012 eXo Platform   9
INJECTION: JSR -330
− Supporte Spring, Guice 3.0 ou CDI

       Router             Asset             Controller              Template   Binding
 …
       plugin             plugin             plugin                  plugin    plugin


                         Asset
                        Manager                                      index

                                  class Controller {
                                      @Inject
                                      Template index;
       Router
                                      @Inject
                                      Service service
                                  }                                            Service



                www.exoplatform.com - Copyright 2012 eXo Platform                        10
GESTION DE LA CONFIGURATION
Notre approche: générer la configuration à partir des
  annotations
   − Les annotations sont puissantes
   − On peut lire la configuration effective
   − Et la surcharger!


  Annota    Compilation             Config               Execution   Model
   tions

                   Modifications


                                    Config               Execution   Model




                 www.exoplatform.com - Copyright 2012 eXo Platform           11
TRAITEMENT
D’ANNOTATION




 www.exoplatform.com - Copyright 2012 eXo Platform   12
MAIS AVANT UN PETIT
     SONDAGE




    www.exoplatform.com - Copyright 2012 eXo Platform   13
LES OUTILS




www.exoplatform.com - Copyright 2012 eXo Platform   14
SUPPORT DES OUTILS
− Basé sur des standards depuis J2SE 6
  − javax.annotation : Pluggable Annotation
    Processing API (JSR 269)
  − javax.lang.model
  − javax.tools
− Deux compilateurs
  − Oracle : javac
  − Eclipse : ecj
− Et les IDEs ?
             www.exoplatform.com - Copyright 2012 eXo Platform   15
ET LES IDES ?




                            1
         2
                                                 3
        www.exoplatform.com - Copyright 2012 eXo Platform   16
AVANT TOUT, QUELQUES
 BONNES PRATIQUES 




    www.exoplatform.com - Copyright 2012 eXo Platform   17
LOGGING
− Comprendre ce qu’il se passe chez
 l’utilisateur
− SOURCE_OUTPUT/my.log
  − Facile à trouver
  − Séparé des classes
− Attention aux compilation successives! 
 append



             www.exoplatform.com - Copyright 2012 eXo Platform   18
REPORTER UNE ERREUR
− Messager
  −     WARNING / MANDATORY_WARNING
  −     ERROR: fait échouer la compilation
  −     NOTE
  − ?   OTHER
− Avec un élément ou une annotation pour
 contextualiser l’erreur



             www.exoplatform.com - Copyright 2012 eXo Platform   19
GESTION DE VOS BUGS
try {
   doProcess(annotations, roundEnv);
} catch(Exception e) {
   processingEnv.getMessager().printMessage(
      Diagnostic.Kind.ERROR,
      e.getMessage());
}

− Sinon erreur compilateur (selon les
 versions)


             www.exoplatform.com - Copyright 2012 eXo Platform   20
GENERATION
− Indiquer un element ou plusieurs elements
 origines lors de la creation d’un fichier
  − Etabli une relation de dépendance entre
    l’origine et le fichier
  − Utile à l’IDE pour supprimer les fichiers en
    cascade




             www.exoplatform.com - Copyright 2012 eXo Platform   21
GENERATION




www.exoplatform.com - Copyright 2012 eXo Platform   22
GENERATION
− De quoi?
  − Une source java qui sera compilé
  − Une classe java (bytecode)
  − Une resource
− Et où?
  − CLASS_OUTPUT
  − SOURCE_OUTPUT



             www.exoplatform.com - Copyright 2012 eXo Platform   23
CYCLE DE VIE
− Maximum une fois par round  bufferiser
  les fichiers et les écrire à la fin du round
− Ecrase le fichier existant issu d’un round
  précédent ou d’une précédente
  compilation
− Invoker close() sur le stream




             www.exoplatform.com - Copyright 2012 eXo Platform   24
GENERATION DE SOURCE JAVA
− Avant le dernier round
− Annoter le source code généré avec
  javax.annotation.Generated
− Indiquer les éléments à l’origine du fichier
  source crée
−  votre code peut utiliser le code généré



             www.exoplatform.com - Copyright 2012 eXo Platform   25
DANS JUZU: TYPE SAFE URL
public class Controller {

   @View @Route(“/show/{id}”)
   public Response show(String id) {
      return Response.ok(“<a href=„” +
Controller_.update(id) + “„>update</a>”);
   }

    @Action @Route(“/update/{id}”)
    public void update(String id) {
       // Do the update
    }
}

               www.exoplatform.com - Copyright 2012 eXo Platform   26
GENERATION DE RESOURCE
filer.createResource(
JavaFileManager.Location location,
CharSequence pkg,
CharSequence relativeName,
Element… originatingElements)

− écriture possible dans META-INF
  − filer.createResource(CLASS_OUTPUT,
    “”, “META-INF/resource.txt”)



            www.exoplatform.com - Copyright 2012 eXo Platform   27
DANS JUZU: COMPILATION LESS


@Application
@Less(
   “assets/bootstrap.less”,
   minify = true)
package my.app;




         www.exoplatform.com - Copyright 2012 eXo Platform   28
AUTRES CAS D’UTILISATION




      www.exoplatform.com - Copyright 2012 eXo Platform   29
AUTRES CAS D’UTILISATION
− Etendre une classe
  − Par une super classe
  − Par une sous classe  requiert une factory
  − Cas d’utilisation
     − static proxy
     − generation de JavaBean

− Classe compagnon
  − Foo  Foo_
  − Cas d’utilisation
     − Generateur de builder pattern
     − JPA meta model
               www.exoplatform.com - Copyright 2012 eXo Platform   30
AUTRES CAS D’UTILISATION
− Remplacer le scan d’annotations par un
 descripteur centralisé
− Etc…




            www.exoplatform.com - Copyright 2012 eXo Platform   31
FRAMEWORKS BASÉS SUR APT
− AndroidAnnotations
− Dagger : l’IOC de Square
− APTVir : un virus APT (sur mon GitHub)
− Type safe queries
  − JPA2 MetaModel
  − QueryDSL
− JBoss Logging Tooling: logger typé
− Storm-gen: generateur de DAO
            www.exoplatform.com - Copyright 2012 eXo Platform   32
ANDROIDANNOTATIONS
@Background
void searchAsync(String searchString) {
  Bookmarks bm =
  client.getBookmarks(searchString);    updateBookma
  rks(bm);
}


@Override
void searchAsync(String searchString) {
  backgroundExecutor.execute(
    () -> { super.searchAsync(searchString); }
  );
}

              www.exoplatform.com - Copyright 2012 eXo Platform   33
L’ARBRE SYNTAXIQUE
− L’arme absolue
− Compliqué et non portable
− Pour javac deux niveaux
  − Compiler Tree API (javac) : lecture seule
  − Implementation de la Tree API : ecriture
− Utilisé par Lombok



             www.exoplatform.com - Copyright 2012 eXo Platform   34
COMPILATION
INCREMENTALE




 www.exoplatform.com - Copyright 2012 eXo Platform   35
COMPILATION INCREMENTALE
− Dans Eclipse la compilation est
 incrémentale
− Ergonomie accrue pour l’utilisateur
− Tous les unités de compilation (fichiers) ne
 sont pas disponibles en même temps




            www.exoplatform.com - Copyright 2012 eXo Platform   36
DESIGN DU PROCESSEUR
− Peut devoir être adapté quand il existe des
 relations entre les elements traités
− Regardons ensemble un exemple…




            www.exoplatform.com - Copyright 2012 eXo Platform   37
EXEMPLE


                           @Application
                           package myapp;




package myapp.controllers;                                Hello
class Controller {                                        {{name}}
   @Inject
   @Path(“index.mustache”)                      myapp/templates/index.mustache
   Template index;
}




               www.exoplatform.com - Copyright 2012 eXo Platform                 38
LE METAMODELE

 Model = { }


                                 Model = {
                                    template: {
                                       templateRefs:[”index.mustache”]
                                    }
@Path(“index.mustache”)           }


  Model = {
    package: “myapp”
    template: {
       templateRefs:[”index.mustache”]
    }                                                           @Application
  }


                                 index.mustache est résolu
                                 myapp/templates/index.mustache

                    www.exoplatform.com - Copyright 2012 eXo Platform          39
CYCLE D’UNE COMPILATION

                  Metamodele existe ?


  Créer metamodel vide                       Charger le metamodel


               Traiter les annotations


               MAJ du metamodele


               Sauver le metamodele

           www.exoplatform.com - Copyright 2012 eXo Platform        40
MAIS AU FAIT
− Pourquoi analyser un template à la compilation ?
   − Vérifier les erreurs
   − Précalculer
   − Pour Juzu : générer une sous classe pour l’injection de
     dépendance

         @Path(“index.gtmpl”)
         Public class index extends
         juzu.Template {
         }



− Question bonus : quid de @Path ?
                 www.exoplatform.com - Copyright 2012 eXo Platform   41
TESTER SON PROCESSEUR




     www.exoplatform.com - Copyright 2012 eXo Platform   42
AVEC L’API JAVAX.TOOLS

1   − Obtenir le compilateur et file manager
       − ToolProvider.getSystemJavaCompiler()
       − compiler.getStandardFileManager(…)

2   − Configurer le file manager
       − mgr.setLocation(SOURCE_OUTPUT, sourceOut);
       − mgr.setLocation(CLASS_OUTPUT, classOut);

3   − Créer et configurer une tâche de compilation
       − CompilationTask task = compiler.getTask(…)
       − task.setProcessors(processors)

4   − Compiler
       − assertEquals(Boolean.TRUE,                              task.call());



             www.exoplatform.com - Copyright 2012 eXo Platform                   43
VERIFICATION D’UN ECHEC
interface Diagnostic<S> {
  Kind getKind();
  S getSource();
  long getPosition();
  long getStartPosition();
  long getEndPosition();
  long getLineNumber();
  long getColumnNumber();
  String getMessage(Locale locale);
}


            www.exoplatform.com - Copyright 2012 eXo Platform   44
COMPILATION INCRÉMENTALE
− Abordable mais un peu plus complexe
− Simulation d’un environement incrémental
− Exemple
  1. Compiler Foo.java  Foo.class
  2. Supprimer Foo.java et déplacer Foo.class
     dans le classpath
  3. Compiler Bar.java


            www.exoplatform.com - Copyright 2012 eXo Platform   45
WHAT ELSE ?




www.exoplatform.com - Copyright 2012 eXo Platform   46
SUPRESSION DE FICHIER
− Suppression de fichier
  − Serait utile pour l’incremental
  − Fichier Java: utiliser les dépendances
  − Fichier resource: opération existe mais non
    supporté Eclipse
− Workaround
  − Remplacer par un fichier vide…



             www.exoplatform.com - Copyright 2012 eXo Platform   47
ACCESS AU SOURCE
− Noms des paramètres de méthode
  − Sinon mode debug
  − Ou Java 8
− JavaDoc
  − Elements#getDocComment(Element)
  − Contenu brut




            www.exoplatform.com - Copyright 2012 eXo Platform   48
MESSAGER
− Eclipse Message#printMessage
  − Sans element  NPE interne
  − Inopérant pour un package  dirty hack




            www.exoplatform.com - Copyright 2012 eXo Platform   49
SUPPORT DU SOURCE_PATH
− Indispensable pour lire les resources
− Javac
  − Doit etre fourni par l’environnement
  − Mais possible à partir d’un élément avec
    Compiler Tree API
− Eclipse
  − Non fourni (bug)
  − Peut etre obtenu avec l’API interne

             www.exoplatform.com - Copyright 2012 eXo Platform   50
LES RESOURCES
− Javac
  − getResource pour lire et createResource pour
    écrire
− ECJ
  − Même resource pour lire / écrire  cacher la
    resource




               www.exoplatform.com - Copyright 2012 eXo Platform   51
COMPLETION
− Pour les IDE, semble supporté
 uniquement par Netbeans




           www.exoplatform.com - Copyright 2012 eXo Platform   52
MA CONCLUSION
     Q&A




 www.exoplatform.com - Copyright 2012 eXo Platform   53
MA CONCLUSION
− Ecrire un processeur est simple
− Mais peut devenir compliqué
− Très bon support du compilateur
− Support des IDE à améliorer
  − Eclipse sauve les honneurs
  − Intellij et netbeans mention passable



             www.exoplatform.com - Copyright 2012 eXo Platform   54

Mais conteúdo relacionado

Destaque

What's new and cool in Portlet 2.0
What's new and cool in Portlet 2.0What's new and cool in Portlet 2.0
What's new and cool in Portlet 2.0jviet
 
Good GateIn Stuff
Good GateIn StuffGood GateIn Stuff
Good GateIn Stuffjviet
 
Crash
CrashCrash
Crashjviet
 
GateIn Frameworks
GateIn FrameworksGateIn Frameworks
GateIn Frameworksjviet
 
Navigation Service
Navigation ServiceNavigation Service
Navigation Servicejviet
 
CRaSH: the shell for the Java Platform
CRaSH: the shell for the Java PlatformCRaSH: the shell for the Java Platform
CRaSH: the shell for the Java Platformjviet
 
Spicing up JMX with Jolokia (Devoxx 2014)
Spicing up JMX with Jolokia (Devoxx 2014)Spicing up JMX with Jolokia (Devoxx 2014)
Spicing up JMX with Jolokia (Devoxx 2014)roland.huss
 
CRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - QuickieCRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - QuickieArnaud Héritier
 

Destaque (8)

What's new and cool in Portlet 2.0
What's new and cool in Portlet 2.0What's new and cool in Portlet 2.0
What's new and cool in Portlet 2.0
 
Good GateIn Stuff
Good GateIn StuffGood GateIn Stuff
Good GateIn Stuff
 
Crash
CrashCrash
Crash
 
GateIn Frameworks
GateIn FrameworksGateIn Frameworks
GateIn Frameworks
 
Navigation Service
Navigation ServiceNavigation Service
Navigation Service
 
CRaSH: the shell for the Java Platform
CRaSH: the shell for the Java PlatformCRaSH: the shell for the Java Platform
CRaSH: the shell for the Java Platform
 
Spicing up JMX with Jolokia (Devoxx 2014)
Spicing up JMX with Jolokia (Devoxx 2014)Spicing up JMX with Jolokia (Devoxx 2014)
Spicing up JMX with Jolokia (Devoxx 2014)
 
CRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - QuickieCRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - Quickie
 

Semelhante a Annotations pour les Geeks

CRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - QuickieCRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - QuickieeXo Platform
 
Rich Desktop Applications
Rich Desktop ApplicationsRich Desktop Applications
Rich Desktop Applicationsgoldoraf
 
The Spring of Adobe Flex Remoting
The Spring of Adobe Flex RemotingThe Spring of Adobe Flex Remoting
The Spring of Adobe Flex RemotingFrançois Le Droff
 
Solutions Linux 2008 - JavaScript
Solutions Linux 2008 - JavaScriptSolutions Linux 2008 - JavaScript
Solutions Linux 2008 - JavaScriptRaphaël Semeteys
 
#J2Code2018 - Mettez du feu à vos applications avec CodeIgniter
#J2Code2018 - Mettez du feu à vos applications avec CodeIgniter#J2Code2018 - Mettez du feu à vos applications avec CodeIgniter
#J2Code2018 - Mettez du feu à vos applications avec CodeIgniterAtsé François-Xavier KOBON
 
Partenariat Exo Platform/Pilot Systems
Partenariat Exo Platform/Pilot SystemsPartenariat Exo Platform/Pilot Systems
Partenariat Exo Platform/Pilot SystemsParis, France
 
Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013Xavier NOPRE
 
Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017Jean-Michel Doudoux
 
Formation Efficy CRM - Technical training
Formation Efficy CRM - Technical trainingFormation Efficy CRM - Technical training
Formation Efficy CRM - Technical trainingEfficy CRM
 
201303 - Java8
201303 - Java8201303 - Java8
201303 - Java8lyonjug
 
Java dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnASJava dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnASGuillaume Sauthier
 
Présentation CoreOS
Présentation CoreOSPrésentation CoreOS
Présentation CoreOSgcatt
 
Aspect avec AspectJ
Aspect avec AspectJAspect avec AspectJ
Aspect avec AspectJsimeon
 

Semelhante a Annotations pour les Geeks (20)

CRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - QuickieCRaSH @ JUGSummerCamp 2012 - Quickie
CRaSH @ JUGSummerCamp 2012 - Quickie
 
Rich Desktop Applications
Rich Desktop ApplicationsRich Desktop Applications
Rich Desktop Applications
 
The Spring of Adobe Flex Remoting
The Spring of Adobe Flex RemotingThe Spring of Adobe Flex Remoting
The Spring of Adobe Flex Remoting
 
iTunes Stats
iTunes StatsiTunes Stats
iTunes Stats
 
Solutions Linux 2008 - JavaScript
Solutions Linux 2008 - JavaScriptSolutions Linux 2008 - JavaScript
Solutions Linux 2008 - JavaScript
 
#J2Code2018 - Mettez du feu à vos applications avec CodeIgniter
#J2Code2018 - Mettez du feu à vos applications avec CodeIgniter#J2Code2018 - Mettez du feu à vos applications avec CodeIgniter
#J2Code2018 - Mettez du feu à vos applications avec CodeIgniter
 
12-Factor
12-Factor12-Factor
12-Factor
 
Partenariat Exo Platform/Pilot Systems
Partenariat Exo Platform/Pilot SystemsPartenariat Exo Platform/Pilot Systems
Partenariat Exo Platform/Pilot Systems
 
Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013Play framework - Human Talks Grenoble - 12.02.2013
Play framework - Human Talks Grenoble - 12.02.2013
 
Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017
 
Catalogue PFE 2019
Catalogue PFE 2019Catalogue PFE 2019
Catalogue PFE 2019
 
CV REBAI Hamida
CV REBAI HamidaCV REBAI Hamida
CV REBAI Hamida
 
Formation Efficy CRM - Technical training
Formation Efficy CRM - Technical trainingFormation Efficy CRM - Technical training
Formation Efficy CRM - Technical training
 
Springioc
SpringiocSpringioc
Springioc
 
Introduction webextensions
Introduction webextensionsIntroduction webextensions
Introduction webextensions
 
201303 - Java8
201303 - Java8201303 - Java8
201303 - Java8
 
Java dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnASJava dans Windows Azure, l'exemple de JOnAS
Java dans Windows Azure, l'exemple de JOnAS
 
Présentation CoreOS
Présentation CoreOSPrésentation CoreOS
Présentation CoreOS
 
Aspect avec AspectJ
Aspect avec AspectJAspect avec AspectJ
Aspect avec AspectJ
 
Plugins Xcode
Plugins XcodePlugins Xcode
Plugins Xcode
 

Annotations pour les Geeks

  • 1. Annotation pour les g33ks T H E E N T E R P R I S E S O C I A L P L AT F O R M Julien Viet FEBRUARY 2013
  • 2. JULIEN VIET − Contact − julien@julienviet.com − @julienviet − http://github.com/vietj − Open source depuis + de 10 ans (déjà) − Avec l’opportunité de pouvoir en vivre − 2003  2008 JBoss − 2008  2013 Exoplatform − Mission officielle: le portail pour Java EE − Le portail pour Java EE (officiel) − Marsjug Leader www.exoplatform.com - Copyright 2012 eXo Platform 2
  • 3. MISSION OFFICIEUSE − CRaSH : le shell pour la JVM − Wikbook : écrire de la doc au format wiki pour docbook dans des projets Java en incluant du source code − Juzu : que nous allons voir www.exoplatform.com - Copyright 2012 eXo Platform 3
  • 4. E X O P L AT F O R M − The Enterprise Social Platform − Social collaboration Solution − Open Source and Enterprise Ready − Highly extensible platform − Notre blog − http://blog.exoplatform.com www.exoplatform.com - Copyright 2012 eXo Platform 4
  • 5. FEATURES All in a Single Platform www.exoplatform.com - Copyright 2012 eXo Platform 5
  • 6. INTRO A JUZU www.exoplatform.com - Copyright 2012 eXo Platform 6
  • 7. JUZU − Framework MVC − Apprentissage rapide − Simplicité et liberté − Plusieurs runtimes − Servlet − Portlet − Vert.x (poc) − Motivation − Besoin d’un framework simple et puissant pour portlet/servlet www.exoplatform.com - Copyright 2012 eXo Platform 7
  • 8. www.exoplatform.com - Copyright 2012 eXo Platform 8
  • 9. USINE A PLUGIN − A la compilation − Generer de la configuration, du code source, des resources − Faire échouer la compilation − A l’execution − Interception des requêtes − Déclarer des beans dans le container d’injection www.exoplatform.com - Copyright 2012 eXo Platform 9
  • 10. INJECTION: JSR -330 − Supporte Spring, Guice 3.0 ou CDI Router Asset Controller Template Binding … plugin plugin plugin plugin plugin Asset Manager index class Controller { @Inject Template index; Router @Inject Service service } Service www.exoplatform.com - Copyright 2012 eXo Platform 10
  • 11. GESTION DE LA CONFIGURATION Notre approche: générer la configuration à partir des annotations − Les annotations sont puissantes − On peut lire la configuration effective − Et la surcharger! Annota Compilation Config Execution Model tions Modifications Config Execution Model www.exoplatform.com - Copyright 2012 eXo Platform 11
  • 12. TRAITEMENT D’ANNOTATION www.exoplatform.com - Copyright 2012 eXo Platform 12
  • 13. MAIS AVANT UN PETIT SONDAGE www.exoplatform.com - Copyright 2012 eXo Platform 13
  • 14. LES OUTILS www.exoplatform.com - Copyright 2012 eXo Platform 14
  • 15. SUPPORT DES OUTILS − Basé sur des standards depuis J2SE 6 − javax.annotation : Pluggable Annotation Processing API (JSR 269) − javax.lang.model − javax.tools − Deux compilateurs − Oracle : javac − Eclipse : ecj − Et les IDEs ? www.exoplatform.com - Copyright 2012 eXo Platform 15
  • 16. ET LES IDES ? 1 2 3 www.exoplatform.com - Copyright 2012 eXo Platform 16
  • 17. AVANT TOUT, QUELQUES BONNES PRATIQUES  www.exoplatform.com - Copyright 2012 eXo Platform 17
  • 18. LOGGING − Comprendre ce qu’il se passe chez l’utilisateur − SOURCE_OUTPUT/my.log − Facile à trouver − Séparé des classes − Attention aux compilation successives!  append www.exoplatform.com - Copyright 2012 eXo Platform 18
  • 19. REPORTER UNE ERREUR − Messager − WARNING / MANDATORY_WARNING − ERROR: fait échouer la compilation − NOTE − ? OTHER − Avec un élément ou une annotation pour contextualiser l’erreur www.exoplatform.com - Copyright 2012 eXo Platform 19
  • 20. GESTION DE VOS BUGS try { doProcess(annotations, roundEnv); } catch(Exception e) { processingEnv.getMessager().printMessage( Diagnostic.Kind.ERROR, e.getMessage()); } − Sinon erreur compilateur (selon les versions) www.exoplatform.com - Copyright 2012 eXo Platform 20
  • 21. GENERATION − Indiquer un element ou plusieurs elements origines lors de la creation d’un fichier − Etabli une relation de dépendance entre l’origine et le fichier − Utile à l’IDE pour supprimer les fichiers en cascade www.exoplatform.com - Copyright 2012 eXo Platform 21
  • 23. GENERATION − De quoi? − Une source java qui sera compilé − Une classe java (bytecode) − Une resource − Et où? − CLASS_OUTPUT − SOURCE_OUTPUT www.exoplatform.com - Copyright 2012 eXo Platform 23
  • 24. CYCLE DE VIE − Maximum une fois par round  bufferiser les fichiers et les écrire à la fin du round − Ecrase le fichier existant issu d’un round précédent ou d’une précédente compilation − Invoker close() sur le stream www.exoplatform.com - Copyright 2012 eXo Platform 24
  • 25. GENERATION DE SOURCE JAVA − Avant le dernier round − Annoter le source code généré avec javax.annotation.Generated − Indiquer les éléments à l’origine du fichier source crée −  votre code peut utiliser le code généré www.exoplatform.com - Copyright 2012 eXo Platform 25
  • 26. DANS JUZU: TYPE SAFE URL public class Controller { @View @Route(“/show/{id}”) public Response show(String id) { return Response.ok(“<a href=„” + Controller_.update(id) + “„>update</a>”); } @Action @Route(“/update/{id}”) public void update(String id) { // Do the update } } www.exoplatform.com - Copyright 2012 eXo Platform 26
  • 27. GENERATION DE RESOURCE filer.createResource( JavaFileManager.Location location, CharSequence pkg, CharSequence relativeName, Element… originatingElements) − écriture possible dans META-INF − filer.createResource(CLASS_OUTPUT, “”, “META-INF/resource.txt”) www.exoplatform.com - Copyright 2012 eXo Platform 27
  • 28. DANS JUZU: COMPILATION LESS @Application @Less( “assets/bootstrap.less”, minify = true) package my.app; www.exoplatform.com - Copyright 2012 eXo Platform 28
  • 29. AUTRES CAS D’UTILISATION www.exoplatform.com - Copyright 2012 eXo Platform 29
  • 30. AUTRES CAS D’UTILISATION − Etendre une classe − Par une super classe − Par une sous classe  requiert une factory − Cas d’utilisation − static proxy − generation de JavaBean − Classe compagnon − Foo  Foo_ − Cas d’utilisation − Generateur de builder pattern − JPA meta model www.exoplatform.com - Copyright 2012 eXo Platform 30
  • 31. AUTRES CAS D’UTILISATION − Remplacer le scan d’annotations par un descripteur centralisé − Etc… www.exoplatform.com - Copyright 2012 eXo Platform 31
  • 32. FRAMEWORKS BASÉS SUR APT − AndroidAnnotations − Dagger : l’IOC de Square − APTVir : un virus APT (sur mon GitHub) − Type safe queries − JPA2 MetaModel − QueryDSL − JBoss Logging Tooling: logger typé − Storm-gen: generateur de DAO www.exoplatform.com - Copyright 2012 eXo Platform 32
  • 33. ANDROIDANNOTATIONS @Background void searchAsync(String searchString) { Bookmarks bm = client.getBookmarks(searchString); updateBookma rks(bm); } @Override void searchAsync(String searchString) { backgroundExecutor.execute( () -> { super.searchAsync(searchString); } ); } www.exoplatform.com - Copyright 2012 eXo Platform 33
  • 34. L’ARBRE SYNTAXIQUE − L’arme absolue − Compliqué et non portable − Pour javac deux niveaux − Compiler Tree API (javac) : lecture seule − Implementation de la Tree API : ecriture − Utilisé par Lombok www.exoplatform.com - Copyright 2012 eXo Platform 34
  • 35. COMPILATION INCREMENTALE www.exoplatform.com - Copyright 2012 eXo Platform 35
  • 36. COMPILATION INCREMENTALE − Dans Eclipse la compilation est incrémentale − Ergonomie accrue pour l’utilisateur − Tous les unités de compilation (fichiers) ne sont pas disponibles en même temps www.exoplatform.com - Copyright 2012 eXo Platform 36
  • 37. DESIGN DU PROCESSEUR − Peut devoir être adapté quand il existe des relations entre les elements traités − Regardons ensemble un exemple… www.exoplatform.com - Copyright 2012 eXo Platform 37
  • 38. EXEMPLE @Application package myapp; package myapp.controllers; Hello class Controller { {{name}} @Inject @Path(“index.mustache”) myapp/templates/index.mustache Template index; } www.exoplatform.com - Copyright 2012 eXo Platform 38
  • 39. LE METAMODELE Model = { } Model = { template: { templateRefs:[”index.mustache”] } @Path(“index.mustache”) } Model = { package: “myapp” template: { templateRefs:[”index.mustache”] } @Application } index.mustache est résolu myapp/templates/index.mustache www.exoplatform.com - Copyright 2012 eXo Platform 39
  • 40. CYCLE D’UNE COMPILATION Metamodele existe ? Créer metamodel vide Charger le metamodel Traiter les annotations MAJ du metamodele Sauver le metamodele www.exoplatform.com - Copyright 2012 eXo Platform 40
  • 41. MAIS AU FAIT − Pourquoi analyser un template à la compilation ? − Vérifier les erreurs − Précalculer − Pour Juzu : générer une sous classe pour l’injection de dépendance @Path(“index.gtmpl”) Public class index extends juzu.Template { } − Question bonus : quid de @Path ? www.exoplatform.com - Copyright 2012 eXo Platform 41
  • 42. TESTER SON PROCESSEUR www.exoplatform.com - Copyright 2012 eXo Platform 42
  • 43. AVEC L’API JAVAX.TOOLS 1 − Obtenir le compilateur et file manager − ToolProvider.getSystemJavaCompiler() − compiler.getStandardFileManager(…) 2 − Configurer le file manager − mgr.setLocation(SOURCE_OUTPUT, sourceOut); − mgr.setLocation(CLASS_OUTPUT, classOut); 3 − Créer et configurer une tâche de compilation − CompilationTask task = compiler.getTask(…) − task.setProcessors(processors) 4 − Compiler − assertEquals(Boolean.TRUE, task.call()); www.exoplatform.com - Copyright 2012 eXo Platform 43
  • 44. VERIFICATION D’UN ECHEC interface Diagnostic<S> { Kind getKind(); S getSource(); long getPosition(); long getStartPosition(); long getEndPosition(); long getLineNumber(); long getColumnNumber(); String getMessage(Locale locale); } www.exoplatform.com - Copyright 2012 eXo Platform 44
  • 45. COMPILATION INCRÉMENTALE − Abordable mais un peu plus complexe − Simulation d’un environement incrémental − Exemple 1. Compiler Foo.java  Foo.class 2. Supprimer Foo.java et déplacer Foo.class dans le classpath 3. Compiler Bar.java www.exoplatform.com - Copyright 2012 eXo Platform 45
  • 46. WHAT ELSE ? www.exoplatform.com - Copyright 2012 eXo Platform 46
  • 47. SUPRESSION DE FICHIER − Suppression de fichier − Serait utile pour l’incremental − Fichier Java: utiliser les dépendances − Fichier resource: opération existe mais non supporté Eclipse − Workaround − Remplacer par un fichier vide… www.exoplatform.com - Copyright 2012 eXo Platform 47
  • 48. ACCESS AU SOURCE − Noms des paramètres de méthode − Sinon mode debug − Ou Java 8 − JavaDoc − Elements#getDocComment(Element) − Contenu brut www.exoplatform.com - Copyright 2012 eXo Platform 48
  • 49. MESSAGER − Eclipse Message#printMessage − Sans element  NPE interne − Inopérant pour un package  dirty hack www.exoplatform.com - Copyright 2012 eXo Platform 49
  • 50. SUPPORT DU SOURCE_PATH − Indispensable pour lire les resources − Javac − Doit etre fourni par l’environnement − Mais possible à partir d’un élément avec Compiler Tree API − Eclipse − Non fourni (bug) − Peut etre obtenu avec l’API interne www.exoplatform.com - Copyright 2012 eXo Platform 50
  • 51. LES RESOURCES − Javac − getResource pour lire et createResource pour écrire − ECJ − Même resource pour lire / écrire  cacher la resource www.exoplatform.com - Copyright 2012 eXo Platform 51
  • 52. COMPLETION − Pour les IDE, semble supporté uniquement par Netbeans www.exoplatform.com - Copyright 2012 eXo Platform 52
  • 53. MA CONCLUSION Q&A www.exoplatform.com - Copyright 2012 eXo Platform 53
  • 54. MA CONCLUSION − Ecrire un processeur est simple − Mais peut devenir compliqué − Très bon support du compilateur − Support des IDE à améliorer − Eclipse sauve les honneurs − Intellij et netbeans mention passable www.exoplatform.com - Copyright 2012 eXo Platform 54