IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Java Discussion :

Comment lister toutes les classes annotées ?


Sujet :

Java

  1. #1
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut Comment lister toutes les classes annotées ?
    Bonjour,

    J'ai une annotation @SessionBean qui possède un paramètre name, et je voudrais placer en session des instances de toutes les classes annotées.

    Je voudrais savoir comment, à partir de l'attribut name, je peux retrouver la classe annotée. Il me semble que pour cela, j'aurais besoin de lister toutes les classes chargées à partir du classpath, puis retenir celles qui sont annotées.

    Savez-vous comment je peux lister les classes chargées par le classloader ?
    Ou avez-vous une autre solution ?

  2. #2
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 557
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 557
    Points : 21 616
    Points
    21 616
    Par défaut
    Citation Envoyé par verbose Voir le message
    Savez-vous comment je peux lister les classes chargées par le classloader ?
    En créant, et utilisant, ton propre ClassLoader, qui te permette de faire cela.

    En principe, on est pas censé faire de recherche sur les classes "qui héritent de" ou "qui ont telles méthodes" ou "qui ont telles annotations" et encore moins "toutes les classes."
    C'est le contraire : quand on a une classe, on peut regarder quelles sont ses méthodes, ses annotations, ce qu'elle étend et implémente...
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  3. #3
    Expert confirmé

    Homme Profil pro
    SDE
    Inscrit en
    Août 2007
    Messages
    2 013
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : SDE

    Informations forums :
    Inscription : Août 2007
    Messages : 2 013
    Points : 4 324
    Points
    4 324
    Par défaut
    Attention à ce que tu veux mettre dans la session

    Sinon nous on passe par une processeur d'annotation au build time afin d’indexer certaines classes mais le projet est une peu spécifique, peut être que ça te donneras des voies de réflexion
    http://alaindefrance.wordpress.com
    Certifications : SCJP6 - SCWCD5 - SCBCD5 - SCMAD1
    SDE at BitTitan

  4. #4
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    Citation Envoyé par thelvin Voir le message
    En créant, et utilisant, ton propre ClassLoader, qui te permette de faire cela.

    En principe, on est pas censé faire de recherche sur les classes "qui héritent de" ou "qui ont telles méthodes" ou "qui ont telles annotations" et encore moins "toutes les classes."
    C'est le contraire : quand on a une classe, on peut regarder quelles sont ses méthodes, ses annotations, ce qu'elle étend et implémente...
    Je veux bien écrire mon propre ClassLoader, mais je n'ai pas l'impression que cela me permettra de contourner mon problème : comment lister toutes mes classes annotées ?

    J'ai bien repéré findClass(). Je peux redéfinir cette méthode et vérifier si la classe trouvée est annotée. Mais cette méthode n'est appelée que lorsqu'on sait le nom de la classe que l'on veut instancier, ce qui n'est pas le cas pour moi.

    Donc je retombe sur mon problème de départ, comment trouver une classe annotée à partir de son paramètre name ?

  5. #5
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    Citation Envoyé par Alain Defrance Voir le message
    Attention à ce que tu veux mettre dans la session

    Sinon nous on passe par une processeur d'annotation au build time afin d’indexer certaines classes mais le projet est une peu spécifique, peut être que ça te donneras des voies de réflexion
    C'est une solution un peu lourde à mon goût.

  6. #6
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 557
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 557
    Points : 21 616
    Points
    21 616
    Par défaut
    Citation Envoyé par verbose Voir le message
    Je veux bien écrire mon propre ClassLoader, mais je n'ai pas l'impression que cela me permettra de contourner mon problème : comment lister toutes mes classes annotées ?

    J'ai bien repéré findClass(). Je peux redéfinir cette méthode et vérifier si la classe trouvée est annotée. Mais cette méthode n'est appelée que lorsqu'on sait le nom de la classe que l'on veut instancier, ce qui n'est pas le cas pour moi.

    Donc je retombe sur mon problème de départ, comment trouver une classe annotée à partir de son paramètre name ?
    Il faut, bien entendu, que le nouveau ClassLoader fournisse de nouvelles méthodes, telles que List<Class<?>> getAnnotedClasses(String name)

    En gros, à chaque fois qu'il charge une classe, il vérifie si elle a cette annotation, et l'ajoute à sa liste de classes ayant le name en question.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  7. #7
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    Citation Envoyé par thelvin Voir le message
    Il faut, bien entendu, que le nouveau ClassLoader fournisse de nouvelles méthodes, telles que List<Class<?>> getAnnotedClasses(String name)

    En gros, à chaque fois qu'il charge une classe, il vérifie si elle a cette annotation, et l'ajoute à sa liste de classes ayant le name en question.
    Il me semble que le ClassLoader ne charge les classes qu'à la demande. Donc si le ClassLoader n'est pas appelé avec le nom de la classe, il ne la charge pas. A moins que je me trompe.

  8. #8
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Points : 48 807
    Points
    48 807
    Par défaut
    il ne faut au contraire surtout pas passer par un classloader. En effet, charger toutes les classes dans un classloader peut avoir tout un tas d'effet de bord, dont l'un des plus important est qu'on arrivera à court de mémoire (en pratique, en général, on n'utilise qu'un faible pourcentage des classes présentes dans une librairies qu'on importe!). Le plus "sain", c'est de récupérer l'ensemble des données du classpath. Une voie d'exploration, c'est d'utiliser getClass().getProtectionDomain().getCodesSources().getLocation(). Mais ce n'est probablement suffisant. Une fois qu'on a la liste des .class, les ouvrir avec un parseur quelconque pour y lire les annotations sans les charger dans le classloader.

    Pour info, des librairies comme Spring font déjà ce genre de choses (scanner toutes les annotation JSF etc au démarrage), ce qui peut être une voie à explorer

  9. #9
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    Citation Envoyé par tchize_ Voir le message
    il ne faut au contraire surtout pas passer par un classloader. En effet, charger toutes les classes dans un classloader peut avoir tout un tas d'effet de bord, dont l'un des plus important est qu'on arrivera à court de mémoire (en pratique, en général, on n'utilise qu'un faible pourcentage des classes présentes dans une librairies qu'on importe!). Le plus "sain", c'est de récupérer l'ensemble des données du classpath. Une voie d'exploration, c'est d'utiliser getClass().getProtectionDomain().getCodesSources().getLocation(). Mais ce n'est probablement suffisant. Une fois qu'on a la liste des .class, les ouvrir avec un parseur quelconque pour y lire les annotations sans les charger dans le classloader.

    Pour info, des librairies comme Spring font déjà ce genre de choses (scanner toutes les annotation JSF etc au démarrage), ce qui peut être une voie à explorer
    Voilà exactement ce qu'il me faut

    Est-ce que tu sais dans quel sous-projet Spring je vais pouvoir trouver cet utilitaire ? Sais-tu éventuellement quelle class je vais devoir appeler en façade ?

  10. #10
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Points : 48 807
    Points
    48 807
    Par défaut
    Spring scanne le classpath pour son usage interne (recherche de ses propres annotation), donc il va falloir explorer les sources pour savoir comment c'est réalisé au final.

    AnnotationSessionFactoryBean serait un point de départ de vos recherches, je pense.

  11. #11
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    OK, je te remercie tchize, je vais regarder de côté

  12. #12
    Expert confirmé
    Homme Profil pro
    Inscrit en
    Septembre 2006
    Messages
    2 951
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 2 951
    Points : 4 376
    Points
    4 376
    Par défaut
    Citation Envoyé par verbose Voir le message
    OK, je te remercie tchize, je vais regarder de côté
    De mémoire Spring utilise javassist.jar.

  13. #13
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    Après quelques recherche, j'ai trouvé une classe qui fait exactement ce que je veux, à savoir scanner toutes les classes annotées dans WEB-INF/classes et WEB-INF/lib.

    Pour ceux que cela pourrait aidé, voici la classe en question. Il est néanmoins nécessaire de faire quelques petite retouche car cette classe est conçue pour scanner uniquement les annotations JSF.

    http://grepcode.com/file/repository....onScanner.java

  14. #14
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Points : 48 807
    Points
    48 807
    Par défaut
    attention la license si tu réutilise ce code

  15. #15
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    Citation Envoyé par tchize_ Voir le message
    attention la license si tu réutilise ce code
    Oui, tu as raison. Pour l'instant, je n'ai pas l'intention de redistribuer ce code, c'est pour un usage personnel. Toutefois, je n'exclue pas de rendre mon code public. Dans ce cas je ne manquerai pas de mentionner la licence

  16. #16
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut Mon Scanner me fait des misères :(((
    J'ai modifié un peu le code source pour lire des annotations quelconques, et après ces modifs, j'avais réalisé quelques tests rapides qui se sont bien déroulés.

    Maintenant, je suis en phase de qualification de mon code, et mon AnnotationScanner ne marche plus. Comme un idiot j'ai supprimé le code qui m'avait servit à le tester au début. Je n'arrive pas à comprendre pourquoi ça ne marche plus.

    Pour vous replacer dans le contexte, voici le code tel que je l'ai modifié. Ce sont juste des modifications superficielles qui ne concernent pas la méthode de scanning des classes annotées.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
     
    /*
     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     * 
     * Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
     * 
     * The contents of this file are subject to the terms of either the GNU
     * General Public License Version 2 only ("GPL") or the Common Development
     * and Distribution License("CDDL") (collectively, the "License").  You
     * may not use this file except in compliance with the License. You can obtain
     * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
     * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
     * language governing permissions and limitations under the License.
     * 
     * When distributing the software, include this License Header Notice in each
     * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
     * Sun designates this particular file as subject to the "Classpath" exception
     * as provided by Sun in the GPL Version 2 section of the License file that
     * accompanied this code.  If applicable, add the following below the License
     * Header, with the fields enclosed by brackets [] replaced by your own
     * identifying information: "Portions Copyrighted [year]
     * [name of copyright owner]"
     * 
     * Contributor(s):
     * 
     * If you wish your version of this file to be governed by only the CDDL or
     * only the GPL Version 2, indicate your decision by adding "[Contributor]
     * elects to include this software in this distribution under the [CDDL or GPL
     * Version 2] license."  If you don't indicate a single choice of license, a
     * recipient has the option to distribute your version of this file under
     * either the CDDL, the GPL Version 2 or to extend the choice of license to
     * its licensees as provided above.  However, if you add GPL Version 2 code
     * and therefore, elected the GPL Version 2 license, then the option applies
     * only if the new code is made subject to such option by the copyright
     * holder.
     */
     
    package com.sun.faces.config;
     
    import java.io.IOException;
    import java.lang.annotation.Annotation;
    import java.net.JarURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.nio.ByteBuffer;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
     
    import javax.servlet.ServletContext;
     
    /**
     * This class is responsible for scanning the class file bytes of
     * annotated classes contained within the web application.
     * 
     * @see http://grepcode.com/file/repository.jboss.org/maven2/javax.faces/jsf-impl/2.0.0-RC/com/sun/faces/config/AnnotationScanner.java
     */
    public class AnnotationScanner {
     
        private static final String WEB_INF_CLASSES = "/WEB-INF/classes/";
        private static final String WEB_INF_LIB = "/WEB-INF/lib/";
        private static final String WILDCARD = "*";
     
        private Set<String> annotation_strings;
        private Set<Class<? extends Annotation>> annotation_classes;
     
        private ClassFile classFileScanner;
        private String[] webInfClassesPackages;
        private Map<String,String[]> webInfLibPackages;
     
     
        // ------------------------------------------------------------ Constructors
     
        private ServletContext context;
     
        /**
         * Creates a new <code>AnnotationScanner</code> instance.
         *
         * @param context the <code>ServletContext</code> for the application to be
         *  scanned
         */
        public AnnotationScanner(ServletContext context, Class<? extends Annotation> ... annotations) {
            this.context = context;
            classFileScanner = new ClassFile();
     
    	    webInfClassesPackages = new String[] {WILDCARD};
            webInfLibPackages = new HashMap<String,String[]>();
            webInfLibPackages.put(WILDCARD, new String[]{WILDCARD});
     
            annotation_classes = new HashSet<Class<? extends Annotation>>(annotations.length, 1.0f);
            Collections.addAll(annotation_classes, annotations);
     
            annotation_strings = new HashSet<String>(annotations.length, 1.0f);
            for (Class<? extends Annotation> annotation : annotations) {
            	String clazz = 'L' + annotation.getName().replace('.', '/');
            	annotation_strings.add(clazz);
            }
        }
     
     
        // ---------------------------------------------------------- Public Methods
     
     
        /**
         * @return a <code>Map</code> of classes mapped to a specific annotation type.
         *  If no annotations are present, or the application is considered
         * <code>metadata-complete</code> <code>null</code> will be returned.
         */
        public Map<Class<? extends Annotation>,Set<Class<?>>> getAnnotatedClasses() {
     
            Set<String> classList = new HashSet<String>();
     
            processWebInfClasses(context, classList);
            processWebInfLib(context, classList);
     
            Map<Class<? extends Annotation>,Set<Class<?>>> annotatedClasses = null;
            if (classList.size() > 0) {
                annotatedClasses = new HashMap<Class<? extends Annotation>,Set<Class<?>>>(6, 1.0f);
                for (String className : classList) {
                    try {
                        Class<?> clazz = Class.forName(className);
                        Annotation[] annotations = clazz.getAnnotations();
                        for (Annotation annotation : annotations) {
                            Class<? extends Annotation> annoType =
                                  annotation.annotationType();
                            if (annotation_classes.contains(annoType)) {
                                Set<Class<?>> classes = annotatedClasses.get(annoType);
                                if (classes == null) {
                                    classes = new HashSet<Class<?>>();
                                    annotatedClasses.put(annoType, classes);
                                }
                                classes.add(clazz);
                            }
                        }
                    } catch (ClassNotFoundException cnfe) {}
                }
            }
     
            return ((annotatedClasses != null)
                    ? annotatedClasses
                    : Collections.<Class<? extends Annotation>, Set<Class<?>>>emptyMap());
     
        }
     
     
        // --------------------------------------------------------- Private Methods
     
     
        /**
         * Called by {@link ConstantPoolInfo} when processing the bytes of the
         * class file.
         *
         * @String the String value as provided from {@link ConstantPoolInfo}
         * @return <code>true</code> if the value is one of the known
         *  Faces annotations, otherwise <code>false</code>
         */
        private boolean isAnnotation(String value) {
     
            return annotation_strings.contains(value);
     
        }
     
     
        /**
         * Process JAR files within <code>WEB-INF/lib</code>.
         *
         * @param sc the <code>ServletContext</code> for the application being
         *  scanned
         * @param classList the <code>Set</code> to which annotated classes
         *  will be added
         */
        @SuppressWarnings("unchecked")
    	private void processWebInfLib(ServletContext sc, Set<String> classList) {
     
            //noinspection unchecked
            Set<String> entries = sc.getResourcePaths(WEB_INF_LIB);
            Map<String,JarFile> jars = getJars(sc, entries);
            if (jars != null) {
                for (Map.Entry<String,JarFile> entry : jars.entrySet()) {
                    processJarEntries(entry.getValue(),
                                      ((webInfLibPackages != null)
                                       ? webInfLibPackages.get(entry.getKey())
                                       : null),
                                      classList);
                }
            }
     
        }
     
     
        /**
         * Process the entries in the provided <code>JarFile</code> looking for
         * class files that may be annotated with any of the Faces configuration
         * annotations.
         *
         * @param jarFile the JAR to process
         * @param allowedPackages the packages that should be scanned within the jar
         * @param classList the <code>Set</code> to which annotated classes
         *  will be added
         */
        private void processJarEntries(JarFile jarFile, String[] allowedPackages, Set<String> classList) {
            for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
                JarEntry entry = entries.nextElement();
                if (entry.isDirectory()) {
                    continue;
                }
     
                String name = entry.getName();
                if (name.startsWith("META-INF")) {
                    continue;
                }
     
                if (name.endsWith(".class")) {
                    String cname = convertToClassName(name);
                    if (!processClass(cname, allowedPackages)) {
                        continue;
                    }
                    ReadableByteChannel channel = null;
                    try {
                        channel = Channels.newChannel(jarFile.getInputStream(entry));
                        if (classFileScanner.containsAnnotation(channel, entry.getSize())) {
                            classList.add(cname);
                        }
                    }
                    catch (IOException e) {}
                    finally {
                        if (channel != null) {
                            try {
                                channel.close();
                            } catch (IOException ignored) {}
                        }
                    }
                }
            }
     
        }
     
     
        /**
         * <p>
         * Return any JARs in <code>WEB-INF/lib</code> that contain
         * a <code>META-INF/faces-config.xml</code> file.
         * </p>
         *
         * @param sc the <code>ServletContext</code> for the application being
         *  scanned
         * @param entries the <code>Set</code> to which annotated classes
         *  will be added
         * @return a <code>Map</code> of JAR files that should be scanned
         *  for annotations mapped to their jar name.
         */
        private Map<String,JarFile> getJars(ServletContext sc, Set<String> entries) {
            Map<String,JarFile> jars = null;
            if (entries != null && !entries.isEmpty()) {
                for (String entry : entries) {
                    if (entry.endsWith(".jar")) {
                        String jarName = entry.substring(entry.lastIndexOf('/') + 1);
                        if (!processJar(jarName)) {
                            continue;
                        }
                        webInfLibPackages.put(jarName, new String[]{WILDCARD});
                        URL url;
                        try {
                            url = sc.getResource(entry);
                            StringBuilder sb = new StringBuilder(32);
                            sb.append("jar:").append(url.toString()).append("!/");
                            url = new URL(sb.toString());
                            JarFile jarFile =
                                  ((JarURLConnection) url.openConnection())
                                        .getJarFile();
                                if (jars == null) {
                                    jars = new HashMap<String,JarFile>();
                                }
                                jars.put(jarName, jarFile);
                        } catch (Exception e) {
                        	continue;
                        }
                    }
                }
            }
            return jars;
     
        }
     
     
        /**
         * Scan <code>WEB-INF/classes</code> for classes that may be annotated
         * with any of the Faces configuration annotations.
         *
         * @param sc the <code>ServletContext</code> for the application being
         *  scanned
         * @param classList the <code>Set</code> to which annotated classes
         *  will be added
         */
        private void processWebInfClasses(ServletContext sc, Set<String> classList) {
     
            processWebInfClasses(sc, WEB_INF_CLASSES, classList);
     
        }
     
     
        /**
         * Scan <code>WEB-INF/classes</code> for classes that may be annotated
         * with any of the Faces configuration annotations.
         *
         * @param sc the <code>ServletContext</code> for the application being
         *  scanned
         * @param path the path to start the scan from
         * @param classList the <code>Set</code> to which annotated classes
         *  will be added
         */
        @SuppressWarnings("unchecked")
    	private void processWebInfClasses(ServletContext sc,
                                          String path,
                                          Set<String> classList) {
     
            //noinspection unchecked
            Set<String> paths = sc.getResourcePaths(path);
            processWebInfClasses(sc, paths, classList);
     
        }
     
     
        /**
         * Scan <code>WEB-INF/classes</code> for classes that may be annotated
         * with any of the Faces configuration annotations.
         *
         * @param sc the <code>ServletContext</code> for the application being
         *  scanned
         * @param paths a set of paths to process
         * @param classList the <code>Set</code> to which annotated classes
         *  will be added
         */
        private void processWebInfClasses(ServletContext sc,
                                          Set<String> paths,
                                          Set<String> classList) {
     
            if (paths != null && !paths.isEmpty()) {
                for (String pathElement : paths) {
                    if (pathElement.endsWith("/")) {
                        processWebInfClasses(sc, pathElement, classList);
                    } else {
                        if (pathElement.endsWith(".class")) {
                            String cname = convertToClassName(WEB_INF_CLASSES,
                                                                  pathElement);
                            if (!processClass(cname, webInfClassesPackages)) {
                                continue;
                            }
                            if (containsAnnotation(sc, pathElement)) {
                                classList.add(cname);
                            }
                        }
                    }
                }
            }
     
        }
     
     
        /**
         * @param sc the <code>ServletContext</code> for the application being
         *  scanned
         * @param pathElement the full path to the classfile to be scanned
         * @return <code>true</code> if the class contains one of the Faces
         *  configuration annotations
         */
        private boolean containsAnnotation(ServletContext sc, String pathElement) {
     
            ReadableByteChannel channel = null;
            try {
                URL url = sc.getResource(pathElement);
                URLConnection conn = url.openConnection();
                conn.setUseCaches(false);
                channel = Channels.newChannel(url.openStream());
                return classFileScanner.containsAnnotation(channel,
                                                           conn.getContentLength());
            }
            catch (MalformedURLException e) {}
            catch (IOException ioe) {}
            finally {
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (IOException ignored) {}
                }
            }
            return false;
     
        }
     
     
        /**
         * Utility method for converting paths to fully qualified class names.
         */
        private String convertToClassName(String pathEntry) {
     
            return convertToClassName(null, pathEntry);
     
        }
     
     
        /**
         * Utility method for converting paths to fully qualified class names.
         */
        private String convertToClassName(String prefix, String pathEntry) {
     
            String className = pathEntry;
     
            if (prefix != null) {
                // remove the prefix
                className = className.substring(prefix.length());
            }
            // remove the .class suffix
            className = className.substring(0, (className.length() - 6));
     
            return className.replace('/', '.');
     
        }
     
     
        private boolean processJar(String entry) {
     
            return (webInfLibPackages == null
                      || (webInfLibPackages.containsKey(entry)
                             || webInfLibPackages.containsKey(WILDCARD)));
     
        }
     
     
        private boolean processClass(String candidate, String[] packages) {
     
            if (packages == null) {
                return true;
            }
     
            for (String packageName : packages) {
                if (candidate.startsWith(packageName) || WILDCARD.equals(packageName)) {
                    return true;
                }
            }
            return false;
     
        }
     
     
        // ----------------------------------------------------------- Inner Classes
     
     
        /**
         * This class is encapsulating binary .class file information as defined at
         * http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html
         * <p/>
         * This is used by the annotation frameworks to quickly scan .class files
         * for the presence of annotations. This avoid the annotation framework
         * having to load each .class file in the class loader.
         * <p/>
         * Taken from the GlassFish V2 source base.
         */
        private final class ClassFile {
     
            private static final int magic = 0xCAFEBABE;
     
            /**
             * bunch of stuff I really don't care too much for now.
             * <p/>
             * FieldInfo           fields[]; MethodInfo          methods[];
             * AttributeInfo       attributes[];
             */
     
            ByteBuffer header;
            ConstantPoolInfo constantPoolInfo = new ConstantPoolInfo();
     
            // ------------------------------------------------------------ Constructors
     
     
            /**
             * Creates a new instance of ClassFile
             */
            public ClassFile() {
                header = ByteBuffer.allocate(12000);
            }
     
            // ---------------------------------------------------------- Public Methods
     
     
            /**
             * Read the input channel and initialize instance data structure.
             */
            public boolean containsAnnotation(ReadableByteChannel in, long size)
                  throws IOException {
     
                /**
                 * this is the .class file layout
                 *
                 ClassFile {
                 u4 magic;
                 u2 minor_version;
                 u2 major_version;
                 u2 constant_pool_count;
                 cp_info constant_pool[constant_pool_count-1];
                 u2 access_flags;
                 u2 this_class;
                 u2 super_class;
                 u2 interfaces_count;
                 u2 interfaces[interfaces_count];
                 u2 fields_count;
                 field_info fields[fields_count];
                 u2 methods_count;
                 method_info methods[methods_count];
                 u2 attributes_count;
                 attribute_info attributes[attributes_count];
                 }
                 **/
                header.clear();
                if (size != -1 && size > header.capacity()) {
                    // time to expand...
                    header = ByteBuffer.allocate((int) size);
                }
                long read = (long) in.read(header);
                if (size != -1 && read != size) {
                    return false;
                }
                header.rewind();
     
                if (header.getInt() != magic) {
                    return false;
                }
     
                int constantPoolSize = header.getShort();
     
                return constantPoolInfo
                      .containsAnnotation(constantPoolSize, header);
     
            }
     
        } // END ClassFile
     
     
        private class ConstantPoolInfo {
            public static final byte CLASS = 7;
            public static final int FIELDREF = 9;
            public static final int METHODREF = 10;
            public static final int STRING = 8;
            public static final int INTEGER = 3;
            public static final int FLOAT = 4;
            public static final int LONG = 5;
            public static final int DOUBLE = 6;
            public static final int INTERFACEMETHODREF = 11;
            public static final int NAMEANDTYPE = 12;
            public static final int ASCIZ = 1;
            public static final int UNICODE = 2;
     
            byte[] bytes = new byte[Short.MAX_VALUE];
     
     
            // ------------------------------------------------------------ Constructors
     
     
            /**
             * Creates a new instance of ConstantPoolInfo
             */
            public ConstantPoolInfo() {
            }
     
     
            // ---------------------------------------------------------- Public Methods
     
     
            /**
             * Read the input channel and initialize instance data structure.
             */
            public boolean containsAnnotation(int constantPoolSize,
                                              final ByteBuffer buffer)
                  throws IOException {
     
                for (int i = 1; i < constantPoolSize; i++) {
                    final byte type = buffer.get();
                    switch (type) {
                        case ASCIZ:
                        case UNICODE:
                            final short length = buffer.getShort();
                            if (length < 0 || length > Short.MAX_VALUE) {
                                return true;
                            }
                            buffer.get(bytes, 0, length);
                            /* to speed up the process, I am comparing the first few
                             * bytes to Ljava since all annotations are in the java
                             * package, the reduces dramatically the number or String
                             * construction
                             */
                            if (bytes[0] == 'L' && bytes[1] == 'f' && bytes[2] == 'r') {
                                String stringValue;
                                if (type == ASCIZ) {
                                    stringValue =
                                          new String(bytes, 0, length, "US-ASCII");
                                } else {
                                    stringValue = new String(bytes, 0, length);
                                }
                                if (isAnnotation(stringValue)) {
                                    return true;
                                }
                            }
                            break;
                        case CLASS:
                        case STRING:
                            buffer.getShort();
                            break;
                        case FIELDREF:
                        case METHODREF:
                        case INTERFACEMETHODREF:
                        case INTEGER:
                        case FLOAT:
                            buffer.position(buffer.position() + 4);
                            break;
                        case LONG:
                        case DOUBLE:
                            buffer.position(buffer.position() + 8);
                            // for long, and double, they use 2 constantPool
                            i++;
                            break;
                        case NAMEANDTYPE:
                            buffer.getShort();
                            buffer.getShort();
                            break;
                        default:
                            break;
                    }
                }
                return false;
            }
     
        } // END ConstantPoolInfo
     
    }
    J'ai débuggé ma classe, et j'ai identifié l'origine du problème.
    Le problème vient de cette portion de code (Le ReadableByteChannel pointe sur le fichier .class de la classe annotée) :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
     
            public boolean containsAnnotation(ReadableByteChannel in, long size)
                  throws IOException {
     
                header.clear();
                if (size != -1 && size > header.capacity()) {
                    // time to expand...
                    header = ByteBuffer.allocate((int) size);
                }
                long read = (long) in.read(header);
                if (size != -1 && read != size) {
                    return false;
                }
                header.rewind();
     
                if (header.getInt() != magic) {
                    return false;
                }
     
               int constantPoolSize = header.getShort();
     
                return constantPoolInfo
                      .containsAnnotation(constantPoolSize, header);
    Le problème vient de la ligne 20. Le nombre (short) qui est lu est égal à zéro. Je ne sais pas à quoi correspond ce nombre mais il devrait être supérieur à zéro pour que le scan puisse se poursuivre.

    J'ai testé avec cette classe et cette annotation placés dans un projet web et compilés dans le répertoire /WEB-INF/classes :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MonAnnotation {
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    @MonAnnotation
    public class Test {
     
    }
    Avez-vous une idée sur mon problème. En particulier, savez-vous à quoi correspond le deuxième nombre (short) qui est lu dans le .class et qui est égal à zéro chez moi ?

  17. #17
    Membre éclairé
    Profil pro
    Inscrit en
    Juillet 2007
    Messages
    802
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2007
    Messages : 802
    Points : 653
    Points
    653
    Par défaut
    J'allais oublier. Si vous voulez utiliser la classe AnnotationScanner tel que je l'ai modifiée :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    public class ScanServlet extends HttpServlet {
        @Override
        public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
            AnnotationScanner scanner = new AnnotationScanner(this.getServletContext(), MonAnnotation.class);
            Map<Class<? extends Annotation>, Set<Class<?>> result = scanner.getAnnotatedClasses();
            Set<Class<?>> annotated = result.get(MonAnnotation.class);
            [...]
        }
    }

Discussions similaires

  1. Comment lister toutes les tables d'une BD ?
    Par jmulans dans le forum Bases de données
    Réponses: 3
    Dernier message: 04/11/2007, 19h29
  2. Réponses: 2
    Dernier message: 14/08/2006, 19h23
  3. [D7][Infos système] Comment lister toutes les classes WMI ?
    Par phplive dans le forum API, COM et SDKs
    Réponses: 2
    Dernier message: 03/05/2006, 23h51
  4. Réponses: 2
    Dernier message: 17/06/2005, 23h03

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo