annotations pour les geeks

54
Annotation pour les g33ks THE ENTERPRISE SOCIAL PLATFORM FEBRUARY 2013 Julien Viet

Upload: jviet

Post on 14-Jun-2015

277 views

Category:

Technology


0 download

DESCRIPTION

Traitement d'annotation pour les geeks.

TRANSCRIPT

Page 1: Annotations pour les Geeks

Annotation pour les g33ksT 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

F E B R U A R Y 2 0 1 3

Julien Viet

Page 2: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 2

JULIEN VIET

−Contact

[email protected]− @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

Page 3: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 4: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 4

EXOPLATFORM

−The Enterprise Social Platform−Social collaboration Solution−Open Source and Enterprise Ready−Highly extensible platform

−Notre blog−http://blog.exoplatform.com

Page 5: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 5

FEATURES

All in a Single Platform

Page 6: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 6

INTRO A JUZU

Page 7: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 8: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 8

Page 9: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 10: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 10

INJECTION: JSR-330

−Supporte Spring, Guice 3.0 ou CDI

Controllerplugin

class Controller {

@Inject Template index;

@Inject Service service} Service

Templateplugin

index

Assetplugin

Routerplugin

…Bindingplugin

AssetManager

Router

Page 11: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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!

Annotations

Config ModelCompilation Execution

Config ModelExecution

Modifications

Page 12: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 12

TRAITEMENT D’ANNOTATION

Page 13: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 13

MAIS AVANT UN PETIT SONDAGE

Page 14: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 14

LES OUTILS

Page 15: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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 ?

Page 16: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 16

ET LES IDES ?

1

32

Page 17: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 17

AVANT TOUT, QUELQUES BONNES PRATIQUES

Page 18: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 19: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 20: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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)

Page 21: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 22: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 22

GENERATION

Page 23: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 23

GENERATION

−De quoi?

−Une source java qui sera compilé−Une classe java (bytecode)−Une resource

−Et où?

−CLASS_OUTPUT−SOURCE_OUTPUT

Page 24: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 25: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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é

Page 26: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

}

}

Page 27: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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”)

Page 28: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 28

DANS JUZU: COMPILATION LESS

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

Page 29: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 29

AUTRES CAS D’UTILISATION

Page 30: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 31: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 31

AUTRES CAS D’UTILISATION

−Remplacer le scan d’annotations par un descripteur centralisé

−Etc…

Page 32: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 33: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 33

ANDROIDANNOTATIONS

@Background

void searchAsync(String searchString) {

Bookmarks bm = client.getBookmarks(searchString);    updateBookmarks(bm); 

}

@Override

void searchAsync(String searchString) {

backgroundExecutor.execute(

() -> { super.searchAsync(searchString); }

);

}

Page 34: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 35: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 35

COMPILATION INCREMENTALE

Page 36: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 37: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 37

DESIGN DU PROCESSEUR

−Peut devoir être adapté quand il existe des relations entre les elements traités

−Regardons ensemble un exemple…

Page 38: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 38

EXEMPLE

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

Hello {{name}}

myapp/templates/index.mustache

@Applicationpackage myapp;

Page 39: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 39

LE METAMODELE

Model = { }

Model = { template: { templateRefs:[”index.mustache”] } }

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

index.mustache est résolumyapp/templates/index.mustache

@Path(“index.mustache”)

@Application

Page 40: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 40

CYCLE D’UNE COMPILATION

Metamodele existe ?

Créer metamodel vide Charger le metamodel

Traiter les annotations

MAJ du metamodele

Sauver le metamodele

Page 41: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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 ?

Page 42: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 42

TESTER SON PROCESSEUR

Page 43: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 43

1

2

3

4

AVEC L’API JAVAX.TOOLS

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

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

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

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

Page 44: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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);

}

Page 45: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 46: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 46

WHAT ELSE ?

Page 47: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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…

Page 48: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 48

ACCESS AU SOURCE

−Noms des paramètres de méthode

−Sinon mode debug−Ou Java 8

−JavaDoc

−Elements#getDocComment(Element)−Contenu brut

Page 49: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 49

MESSAGER

−Eclipse Message#printMessage

−Sans element NPE interne−Inopérant pour un package dirty hack

Page 50: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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

Page 51: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 51

LES RESOURCES

−Javac

−getResource pour lire et createResource pour écrire

−ECJ

−Même resource pour lire / écrire cacher la resource

Page 52: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 52

COMPLETION

−Pour les IDE, semble supporté uniquement par Netbeans

Page 53: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 53

MA CONCLUSIONQ&A

Page 54: Annotations pour les Geeks

www.exoplatform.com - Copyright 2012 eXo Platform 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