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
} |
Partager