libjboss-aop-java-2.0.1.GA.orig/0000755000175000017500000000000011145122072016173 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/jbossorg-eula.txt0000644000175000017500000002002111145122070021501 0ustar twernertwernerLICENSE AGREEMENT JBOSS(r) This License Agreement governs the use of the Software Packages and any updates to the Software Packages, regardless of the delivery mechanism. Each Software Package is a collective work under U.S. Copyright Law. Subject to the following terms, Red Hat, Inc. ("Red Hat") grants to the user ("Client") a license to the applicable collective work(s) pursuant to the GNU Lesser General Public License v. 2.1 except for the following Software Packages: (a) JBoss Portal Forums and JBoss Transactions JTS, each of which is licensed pursuant to the GNU General Public License v.2; (b) JBoss Rules, which is licensed pursuant to the Apache License v.2.0; (c) an optional download for JBoss Cache for the Berkeley DB for Java database, which is licensed under the (open source) Sleepycat License (if Client does not wish to use the open source version of this database, it may purchase a license from Sleepycat Software); and (d) the BPEL extension for JBoss jBPM, which is licensed under the Common Public License v.1, and, pursuant to the OASIS BPEL4WS standard, requires parties wishing to redistribute to enter various royalty-free patent licenses. Each of the foregoing licenses is available at http://www.opensource.org/licenses/index.php. 1. The Software. "Software Packages" refer to the various software modules that are created and made available for distribution by the JBoss.org open source community at http://www.jboss.org. Each of the Software Packages may be comprised of hundreds of software components. The end user license agreement for each component is located in the component's source code. With the exception of certain image files identified in Section 2 below, the license terms for the components permit Client to copy, modify, and redistribute the component, in both source code and binary code forms. This agreement does not limit Client's rights under, or grant Client rights that supersede, the license terms of any particular component. 2. Intellectual Property Rights. The Software Packages are owned by Red Hat and others and are protected under copyright and other laws. Title to the Software Packages and any component, or to any copy, modification, or merged portion shall remain with the aforementioned, subject to the applicable license. The "JBoss" trademark, "Red Hat" trademark, the individual Software Package trademarks, and the "Shadowman" logo are registered trademarks of Red Hat and its affiliates in the U.S. and other countries. This agreement permits Client to distribute unmodified copies of the Software Packages using the Red Hat trademarks that Red Hat has inserted in the Software Packages on the condition that Client follows Red Hat's trademark guidelines for those trademarks located at http://www.redhat.com/about/corporate/trademark/. Client must abide by these trademark guidelines when distributing the Software Packages, regardless of whether the Software Packages have been modified. If Client modifies the Software Packages, then Client must replace all Red Hat trademarks and logos identified at http://www.jboss.com/company/logos, unless a separate agreement with Red Hat is executed or other permission granted. Merely deleting the files containing the Red Hat trademarks may corrupt the Software Packages. 3. Limited Warranty. Except as specifically stated in this Paragraph 3 or a license for a particular component, to the maximum extent permitted under applicable law, the Software Packages and the components are provided and licensed "as is" without warranty of any kind, expressed or implied, including the implied warranties of merchantability, non-infringement or fitness for a particular purpose. Red Hat warrants that the media on which Software Packages may be furnished will be free from defects in materials and manufacture under normal use for a period of 30 days from the date of delivery to Client. Red Hat does not warrant that the functions contained in the Software Packages will meet Client's requirements or that the operation of the Software Packages will be entirely error free or appear precisely as described in the accompanying documentation. This warranty extends only to the party that purchases the Services pertaining to the Software Packages from Red Hat or a Red Hat authorized distributor. 4. Limitation of Remedies and Liability. To the maximum extent permitted by applicable law, the remedies described below are accepted by Client as its only remedies. Red Hat's entire liability, and Client's exclusive remedies, shall be: If the Software media is defective, Client may return it within 30 days of delivery along with a copy of Client's payment receipt and Red Hat, at its option, will replace it or refund the money paid by Client for the Software. To the maximum extent permitted by applicable law, Red Hat or any Red Hat authorized dealer will not be liable to Client for any incidental or consequential damages, including lost profits or lost savings arising out of the use or inability to use the Software, even if Red Hat or such dealer has been advised of the possibility of such damages. In no event shall Red Hat's liability under this agreement exceed the amount that Client paid to Red Hat under this Agreement during the twelve months preceding the action. 5. Export Control. As required by U.S. law, Client represents and warrants that it: (a) understands that the Software Packages are subject to export controls under the U.S. Commerce Department's Export Administration Regulations ("EAR"); (b) is not located in a prohibited destination country under the EAR or U.S. sanctions regulations (currently Cuba, Iran, Iraq, Libya, North Korea, Sudan and Syria); (c) will not export, re-export, or transfer the Software Packages to any prohibited destination, entity, or individual without the necessary export license(s) or authorizations(s) from the U.S. Government; (d) will not use or transfer the Software Packages for use in any sensitive nuclear, chemical or biological weapons, or missile technology end-uses unless authorized by the U.S. Government by regulation or specific license; (e) understands and agrees that if it is in the United States and exports or transfers the Software Packages to eligible end users, it will, as required by EAR Section 740.17(e), submit semi-annual reports to the Commerce Department's Bureau of Industry & Security (BIS), which include the name and address (including country) of each transferee; and (f) understands that countries other than the United States may restrict the import, use, or export of encryption products and that it shall be solely responsible for compliance with any such import, use, or export restrictions. 6. Third Party Programs. Red Hat may distribute third party software programs with the Software Packages that are not part of the Software Packages and which Client must install separately. These third party programs are subject to their own license terms. The license terms either accompany the programs or can be viewed at http://www.redhat.com/licenses/. If Client does not agree to abide by the applicable license terms for such programs, then Client may not install them. If Client wishes to install the programs on more than one system or transfer the programs to another party, then Client must contact the licensor of the programs. 7. General. If any provision of this agreement is held to be unenforceable, that shall not affect the enforceability of the remaining provisions. This License Agreement shall be governed by the laws of the State of North Carolina and of the United States, without regard to any conflict of laws provisions, except that the United Nations Convention on the International Sale of Goods shall not apply. Copyright 2006 Red Hat, Inc. All rights reserved. "JBoss" and the JBoss logo are registered trademarks of Red Hat, Inc. All other trademarks are the property of their respective owners. Page 1 of 1 18 October 2006 libjboss-aop-java-2.0.1.GA.orig/jboss-40-install/0000755000175000017500000000000011145122070021176 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/jboss-40-install/jboss-aop-jdk50.deployer/0000755000175000017500000000000011145122072025632 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/jboss-40-install/jboss-aop-jdk50.deployer/META-INF/0000755000175000017500000000000011145122072026772 5ustar twernertwerner././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/jboss-40-install/jboss-aop-jdk50.deployer/META-INF/jboss-service.xmllibjboss-aop-java-2.0.1.GA.orig/jboss-40-install/jboss-aop-jdk50.deployer/META-INF/jboss-service.xml0000644000175000017500000000567711145122072032311 0ustar twernertwerner false true true org.jboss.test, org.jboss.injbossaop org.jboss. true false jboss.aop:service=JBoss4IntegrationWrapper jboss.system:service=MainDeployer libjboss-aop-java-2.0.1.GA.orig/jboss-40-install/jboss-aop-jdk50.deployer/jboss.properties0000644000175000017500000000041511145122070031066 0ustar twernertwerner# Properties file for the ant install scripts # Set the root of your jboss installation here jboss.home=/Users/kabir/sourcecontrol/jboss-head/build/output/jboss-5.0.0.GA/ #Set the server configuration you want to patch here (e.g, all or default) jboss.config=all libjboss-aop-java-2.0.1.GA.orig/jboss-40-install/jboss-aop-jdk50.deployer/build.xml0000644000175000017500000004427611145122070027466 0ustar twernertwerner JBoss AS Version is '${AS-Specification-Version}' The server ${jboss.home} lacks a jboss-aspect-library.jdk50.jar library. Downloading jar... Backing up existing jbossall-client.jar to ${bak.jbossall-client} Backing up existing ${lib.jbossaop-client.injboss} to ${bak.jbossaop-client} Backing up existing aop deployer to ${old.deployer} libjboss-aop-java-2.0.1.GA.orig/jboss-40-install/jboss-aop-jdk50.deployer/ReadMe-AS4.txt0000644000175000017500000000320411145122070030112 0ustar twernertwernerNOTE: from the 2.0 release of JBoss AOP only JDK1.5 is supported. This means that that both JBoss AS and AOP need to be compiled with JDK1.5 before you upgrade JBoss AOP. To upgrade your jboss instance: * If installing in a version before JBoss 4.0.4, you should leave javassist.jar in place in this folder. *If installing in jboss 4.0.4 or later, the classes contained in javassist.jar will already be available, and you should do the following to avoid versioning conflicts: -move javassist.jar to ../../lib/javassist.jar *On JBoss 4.0.4 or later, and if using JDK 1.4, you should upgrade the version of jbossretro-rt.jar by moving it from the jboss-aop-jdk14.deployer to ../../lib/jbossretro-rt.jar * Note that this will not replace the jboss-aspect-library(-jdk50).jar, which is tied to application server version. If you are upgrading from JBoss AOP 1.5.x, you should remove the following packages and classes contained therein from your jboss-aspect-library(-jdk50).jar: -org.jboss.aop -org.jboss.aop.deployment *Also, in the existing jboss-aspect-library(-jdk50).jar you should delete the classes that exist in jboss-standalone-aspect-library-jdkxx.jar * If you are deploying the jdk 1.4 deployer and upgrading from JDK 1.5, we need to modify the interfaces specifying the simulated annotations in jboss-aspect-library.jar. The build.xml file does this as part of the install step. Alternatively, you can use the ant script, which will automate all these tasks for you: 1) Edit jboss.properties file, setting the root of the jboss installation and the server configuration you wish to patch. 2) Run the command: $ ant libjboss-aop-java-2.0.1.GA.orig/docs/0000755000175000017500000000000011145122070017121 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/RELEASE_NOTES.html0000644000175000017500000013056511145122072021123 0ustar twernertwerner Release Notes - JBoss AOP - Version 2.0.0.SP1

Release Notes - JBoss AOP - Version 2.0.1.GA

Bug

Feature Request

Thirdparty Change

Release Notes - JBoss AOP - Version 2.0.0.SP1

Bug

Sub-task

Release Notes - JBoss AOP - Version 2.0.0.GA

Bug

Feature Request

Task

Thirdparty Change

Release Notes - JBoss AOP - Version 2.0.0.CR20

Feature Request

Release Notes - JBoss AOP - Version 2.0.0.CR19

Bug

Feature Request

Thirdparty Change

Release Notes - JBoss AOP - Version 2.0.0.CR18

Bug

Feature Request

Task

Sub-task

Release Notes - JBoss AOP - Version 2.0.0.CR17

Bug

Feature Request

Release Notes - JBoss AOP - Version 2.0.0.CR16

Bug

Feature Request

Release Notes - JBoss AOP - Version 2.0.0.CR15

Bug

Feature Request

Release Notes - JBoss AOP - Version 2.0.0.CR14

Bug

Feature Request

Thirdparty Change

Release Notes - JBoss AOP - Version 2.0.0.CR13

Bug

Feature Request

Release Notes - JBoss AOP - Version 2.0.0.CR12

Bug

Feature Request

Task

Thirdparty Change

Release Notes - JBoss AOP - Version 2.0.0.CR11

Bug

Task

Release Notes - JBoss AOP - Version 2.0.0.CR10

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.CR9

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.CR8

Bug

Feature Request

Task

Thirdparty Change

Release Notes - JBoss AOP - Version 2.0.0.CR7

Feature Request

Release Notes - JBoss AOP - Version 2.0.0.CR6

Bug

Release Notes - JBoss AOP - Version 2.0.0.CR5

Feature Request

Release Notes - JBoss AOP - Version 2.0.0.CR4

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.CR3

Bug

Release Notes - JBoss AOP - Version 2.0.0.CR2

Bug

Release Notes - JBoss AOP - Version 2.0.0.CR1

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.beta2

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.beta1

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.alpha5

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.alpha4

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.alpha3

Bug

Feature Request

Task

Release Notes - JBoss AOP - Version 2.0.0.alpha2

Bug

Task

Release Notes - JBoss AOP - Version 2.0.0.alpha1

Bug

Feature Request

Task

libjboss-aop-java-2.0.1.GA.orig/jboss-50-install/0000755000175000017500000000000011145122072021201 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/jboss-50-install/ReadMe-AS5.txt0000644000175000017500000000112611145122072023465 0ustar twernertwernerTo upgrade your jboss instance: 1) Copy the contents of the lib folder into the JBoss-5.x/lib/ folder 2) Copy the jboss-aop-jdk50.deployer over the JBoss-5.x/server/xxx/deployers/jboss-aop-jboss5.deployer/ folder 3) Copy the jboss-aop-client.jar (located at ../lib) into the JBoss-5.x/client/ folder. Note that this will not replace the jboss-aspect-library.jar, which is tied to application server version Alternatively, you can use the ant script: 1) Edit jboss.properties file, setting the root of the jboss installation and the server configuration you wish to patch. 2) Run the command: $ ant libjboss-aop-java-2.0.1.GA.orig/jboss-50-install/jboss.properties0000644000175000017500000000041511145122072024437 0ustar twernertwerner# Properties file for the ant install scripts # Set the root of your jboss installation here jboss.home=/Users/kabir/sourcecontrol/jboss-head/build/output/jboss-5.0.0.GA/ #Set the server configuration you want to patch here (e.g, all or default) jboss.config=all libjboss-aop-java-2.0.1.GA.orig/jboss-50-install/build.xml0000644000175000017500000001323311145122072023024 0ustar twernertwerner Backing up existing lib directory to ${old.lib} Backing up existing aop deployer to ${old.deployer} Backing up existing ${lib.jbossaop-client.injboss} to ${bak.jbossaop-client} libjboss-aop-java-2.0.1.GA.orig/jboss-50-install/jboss-aop-jboss5.deployer/0000755000175000017500000000000011145122072026123 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/jboss-50-install/lib/0000755000175000017500000000000011145122072021747 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/build.xml0000644000175000017500000003632311145122046020024 0ustar twernertwerner ${module.Name} Final User API Documentation]]>
Copyright © 2004 JBoss Inc. All Rights Reserved.
]]>
Running ${test} with instrumentor ${instrumentor}
libjboss-aop-java-2.0.1.GA.orig/bin/0000755000175000017500000000000011145122046016744 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/bin/aopc.bat0000644000175000017500000000506111145122046020360 0ustar twernertwerner@echo off set LIB_DIR=%~dp0..\lib\ IF %1a==a goto display_usage IF %2a==a goto display_usage IF %3a==a goto display_usage IF %4a==a goto display_usage IF %2==%4 goto display_usage SET USER_CLASSPATH=%1 SET AOPPATH= SET AOPCLASSPATH= IF %2==-aoppath SET AOPPATH=-Djboss.aop.path=%3 IF %2==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%3 IF %4%5==-aoppath goto display_usage IF %4%5==-aopclasspath goto display_usage IF %4==-aoppath SET AOPPATH=-Djboss.aop.path=%5 IF %4==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%5 IF %4==-aoppath shift IF %3==-aoppath shift IF %4==-aopclasspath shift IF %3==-aopclasspath shift shift shift shift set ARGS_AND_FILES= REM get all the command line args :setupArgs if %1a==a goto doneStart set ARGS_AND_FILES=%ARGS_AND_FILES% %1 shift goto setupArgs :doneStart REM Setup AOP classpath SET AOPC_CLASSPATH=%LIB_DIR%javassist.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop-client.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-reflect.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-mdr.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-spi.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-standalone-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%pluggable-instrumentor.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-common-core.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%trove.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%USER_CLASSPATH% java -classpath %AOPC_CLASSPATH% %AOPPATH% %AOPCLASSPATH% org.jboss.aop.standalone.Compiler %ARGS_AND_FILES% goto end :display_usage echo Batch file for running the aop precopiler echo Usage: echo aopc.bat classpath [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] [-report] [-verbose] dir_or_file+ echo classpath: Classpath of your sourcefiles and all required libraries echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo dir_or_file: Directory containing files to be aop precompiled echo -verbose: Specify if you want verbose output echo -report: If specified, classes do not get instrumented. Instead you get an xml file containing the bindings applied :end libjboss-aop-java-2.0.1.GA.orig/bin/run-loadHotSwap.sh0000644000175000017500000000541211145122046022331 0ustar twernertwerner#!/bin/sh usage(){ echo Script file for running loadtime instrumented aop applications with hot swap enabled echo Usage: echo run-loadHotSwap.sh classpath [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] [-verbose] Main.class [args] echo echo classpath: Classpath of your source files and all required libraries echo echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo echo -verbose: Specify if you want verbose output echo echo Main.class: Your main class echo echo args: The args to Main.class exit 1 } #Make sure have $1, $2, $3, and $4 if [ "x$1" = "x" ]; then usage fi if [ "x$2" = "x" ]; then usage fi if [ "x$3" = "x" ]; then usage fi if [ "x$4" = "x" ]; then usage fi if [ "$2" = "$4" ]; then usage fi USER_CLASSPATH=$1 AOPPATH= AOPCLASSPATH= if [ "$2" = "-aoppath" ]; then AOPPATH=-Djboss.aop.path=$3 FILESTART=3 fi if [ "$4" = "-aoppath" ]; then if [ "x$5" = "x" ]; then usage fi AOPPATH=-Djboss.aop.path=$5 FILESTART=5 fi if [ "$2" = "-aopclasspath" ]; then AOPCLASSPATH=-Djboss.aop.class.path=$3 FILESTART=3 fi if [ "$4" = "-aopclasspath" ]; then if [ "x$5" = "x" ]; then usage fi AOPCLASSPATH=-Djboss.aop.class.path=$5 FILESTART=5 fi SCRIPT_DIR=$(dirname $(which $0)); AOPC_CLASSPATH=$SCRIPT_DIR/../lib/javassist.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop-client.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-reflect.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-mdr.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-spi.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-standalone-aspect-library.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/pluggable-instrumentor.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-common-core.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/trove.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$USER_CLASSPATH CTR=0 for param in $*; do CTR=`expr $CTR + 1` if [ $CTR -gt $FILESTART ]; then MAINCLASS_AND_ARGS=$MAINCLASS_AND_ARGS" "$param fi done #Check for cygwin and convert path if necessary if (cygpath --version) >/dev/null 2>/dev/null; then AOPC_CLASSPATH=`cygpath --path --windows $AOPC_CLASSPATH` fi java -javaagent:$SCRIPT_DIR/../lib/jboss-aop.jar=-hotSwap -classpath $AOPC_CLASSPATH $AOPPATH $AOPCLASSPATH $MAINCLASS_AND_ARGS libjboss-aop-java-2.0.1.GA.orig/bin/run-load.bat0000644000175000017500000000477511145122046021172 0ustar twernertwerner@echo off set LIB_DIR=%~dp0..\lib\ IF %1a==a goto display_usage IF %2a==a goto display_usage IF %3a==a goto display_usage IF %4a==a goto display_usage IF %2==%4 goto display_usage SET USER_CLASSPATH=%1 SET AOPPATH= SET AOPCLASSPATH= IF %2==-aoppath SET AOPPATH=-Djboss.aop.path=%3 IF %2==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%3 IF %4%5==-aoppath goto display_usage IF %4%5==-aopclasspath goto display_usage IF %4==-aoppath SET AOPPATH=-Djboss.aop.path=%5 IF %4==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%5 IF %4==-aoppath shift IF %3==-aoppath shift IF %4==-aopclasspath shift IF %3==-aopclasspath shift shift shift shift set ARGS_AND_FILES= REM get all the command line args :setupArgs if %1a==a goto doneStart set ARGS_AND_FILES=%ARGS_AND_FILES% %1 shift set MAINCLASS_AND_ARGS=%ARGS_AND_FILES% goto setupArgs :doneStart REM Setup AOP classpath SET AOPC_CLASSPATH=%LIB_DIR%javassist.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop-client.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-reflect.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-mdr.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-spi.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-standalone-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%pluggable-instrumentor.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-common-core.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%trove.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%USER_CLASSPATH% java -javaagent:%LIB_DIR%jboss-aop.jar -classpath %AOPC_CLASSPATH% %AOPPATH% %AOPCLASSPATH% %MAINCLASS_AND_ARGS% goto end :display_usage echo Script file for running loadtime instrumented aop applications echo Usage: echo run-load.bat classpath [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] [-verbose] Main.class [args] echo classpath: Classpath of your sourcefiles and all required libraries echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo -verbose: Specify if you want verbose output echo Main.class: Your main class echo args: The args to Main.class :end libjboss-aop-java-2.0.1.GA.orig/bin/run-precompiled.sh0000644000175000017500000000516011145122046022407 0ustar twernertwerner#!/bin/sh usage(){ echo Script file for running compile time instrumented aop applications echo Usage: echo run-precompiled.sh classpath [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] Main.class [args] echo echo classpath: Classpath of your sourcefiles and all required libraries echo echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo echo Main.class: Your main class echo echo args: The args to Main.class exit 1 } #Make sure have $1, $2, $3, and $4 if [ "x$1" = "x" ]; then usage fi if [ "x$2" = "x" ]; then usage fi if [ "x$3" = "x" ]; then usage fi if [ "x$4" = "x" ]; then usage fi if [ "$2" = "$4" ]; then usage fi USER_CLASSPATH=$1 AOPPATH= AOPCLASSPATH= if [ "$2" = "-aoppath" ]; then AOPPATH=-Djboss.aop.path=$3 FILESTART=3 fi if [ "$4" = "-aoppath" ]; then if [ "x$5" = "x" ]; then usage fi AOPPATH=-Djboss.aop.path=$5 FILESTART=5 fi if [ "$2" = "-aopclasspath" ]; then AOPCLASSPATH=-Djboss.aop.class.path=$3 FILESTART=3 fi if [ "$4" = "-aopclasspath" ]; then if [ "x$5" = "x" ]; then usage fi AOPCLASSPATH=-Djboss.aop.class.path=$5 FILESTART=5 fi SCRIPT_DIR=$(dirname $(which $0)); AOPC_CLASSPATH=$SCRIPT_DIR/../lib/javassist.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop-client.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-reflect.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-mdr.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-spi.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-standalone-aspect-library.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/pluggable-instrumentor.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-common-core.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/trove.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$USER_CLASSPATH CTR=0 for param in $*; do CTR=`expr $CTR + 1` if [ $CTR -gt $FILESTART ]; then MAINCLASS_AND_ARGS=$MAINCLASS_AND_ARGS" "$param fi done #Check for cygwin and convert path if necessary if (cygpath --version) >/dev/null 2>/dev/null; then AOPC_CLASSPATH=`cygpath --path --windows $AOPC_CLASSPATH` fi java -classpath $AOPC_CLASSPATH $AOPPATH $AOPCLASSPATH $MAINCLASS_AND_ARGS libjboss-aop-java-2.0.1.GA.orig/bin/run-precompiled.bat0000644000175000017500000000474711145122046022555 0ustar twernertwerner@echo off set LIB_DIR=%~dp0..\lib\ IF %1a==a goto display_usage IF %2a==a goto display_usage IF %3a==a goto display_usage IF %4a==a goto display_usage IF %2==%4 goto display_usage SET USER_CLASSPATH=%1 SET AOPPATH= SET AOPCLASSPATH= IF %2==-aoppath SET AOPPATH=-Djboss.aop.path=%3 IF %2==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%3 IF %4%5==-aoppath goto display_usage IF %4%5==-aopclasspath goto display_usage IF %4==-aoppath SET AOPPATH=-Djboss.aop.path=%5 IF %4==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%5 IF %4==-aoppath shift IF %3==-aoppath shift IF %4==-aopclasspath shift IF %3==-aopclasspath shift shift shift shift set ARGS_AND_FILES= REM get all the command line args :setupArgs if %1a==a goto doneStart set ARGS_AND_FILES=%ARGS_AND_FILES% %1 shift set MAINCLASS_AND_ARGS=%ARGS_AND_FILES% goto setupArgs :doneStart REM Setup AOP classpath SET AOPC_CLASSPATH=%LIB_DIR%javassist.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop-client.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-reflect.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-mdr.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-spi.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-standalone-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%pluggable-instrumentor.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-common-core.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%trove.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%USER_CLASSPATH% java -classpath %AOPC_CLASSPATH% %AOPPATH% %AOPCLASSPATH% %MAINCLASS_AND_ARGS% goto end :display_usage echo Script file for running compile time instrumented aop applications echo Usage: echo run-precompiled.bat classpath [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] [-verbose] Main.class [args] echo classpath: Classpath of your sourcefiles and all required libraries echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo -verbose: Specify if you want verbose output echo Main.class: Your main class echo args: The args to Main.class :end libjboss-aop-java-2.0.1.GA.orig/bin/run-loadHotSwap.bat0000644000175000017500000000501411145122046022463 0ustar twernertwerner@echo off set LIB_DIR=%~dp0..\lib\ IF %1a==a goto display_usage IF %2a==a goto display_usage IF %3a==a goto display_usage IF %4a==a goto display_usage IF %2==%4 goto display_usage SET USER_CLASSPATH=%1 SET AOPPATH= SET AOPCLASSPATH= IF %2==-aoppath SET AOPPATH=-Djboss.aop.path=%3 IF %2==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%3 IF %4%5==-aoppath goto display_usage IF %4%5==-aopclasspath goto display_usage IF %4==-aoppath SET AOPPATH=-Djboss.aop.path=%5 IF %4==-aopclasspath SET AOPCLASSPATH=-Djboss.aop.class.path=%5 IF %4==-aoppath shift IF %3==-aoppath shift IF %4==-aopclasspath shift IF %3==-aopclasspath shift shift shift shift set ARGS_AND_FILES= REM get all the command line args :setupArgs if %1a==a goto doneStart set ARGS_AND_FILES=%ARGS_AND_FILES% %1 shift set MAINCLASS_AND_ARGS=%ARGS_AND_FILES% goto setupArgs :doneStart REM Setup AOP classpath SET AOPC_CLASSPATH=%LIB_DIR%javassist.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop-client.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-reflect.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-mdr.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-logging-spi.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-standalone-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%log4j.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%pluggable-instrumentor.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aop.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-aspect-library.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%jboss-common-core.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%LIB_DIR%trove.jar SET AOPC_CLASSPATH=%AOPC_CLASSPATH%;%USER_CLASSPATH% java -javaagent:%LIB_DIR%jboss-aop.jar=-hotSwap -classpath %AOPC_CLASSPATH% %AOPPATH% %AOPCLASSPATH% %MAINCLASS_AND_ARGS% goto end :display_usage echo Script file for running loadtime instrumented aop applications echo Usage: echo run-loadHotSwap.bat classpath [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] [-verbose] Main.class [args] echo classpath: Classpath of your sourcefiles and all required libraries echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo -verbose: Specify if you want verbose output echo Main.class: Your main class echo args: The args to Main.class :end libjboss-aop-java-2.0.1.GA.orig/bin/aopc.sh0000644000175000017500000000534711145122046020233 0ustar twernertwerner#!/bin/sh usage(){ echo Batch file for running the aop precompiler echo Usage: echo aopc.sh [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] [-report] [-verbose] dir_or_file+ echo echo classpath: Classpath of your sourcefiles and all required libraries echo echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo echo dir_or_file: Directory containing files to be aop precompiled echo echo -verbose: Specify if you want verbose output echo echo -report: If specified, classes do not get instrumented. Instead you get an xml file containing the bindings applied exit 1 } #Make sure have $1, $2 and $3 if [ "x$1" = "x" ]; then usage fi if [ "x$2" = "x" ]; then usage fi if [ "x$3" = "x" ]; then usage fi if [ "$1" = "$3" ]; then usage fi AOPPATH= AOPCLASSPATH= if [ "$1" = "-aoppath" ]; then AOPPATH=-Djboss.aop.path=$2 FILESTART=2 fi if [ "$3" = "-aoppath" ]; then if [ "x$4" = "x" ]; then usage fi AOPPATH=-Djboss.aop.path=$4 FILESTART=4 fi if [ "$1" = "-aopclasspath" ]; then AOPCLASSPATH=-Djboss.aop.class.path=$2 FILESTART=2 fi if [ "$3" = "-aopclasspath" ]; then if [ "x$4" = "x" ]; then usage fi AOPCLASSPATH=-Djboss.aop.class.path=$4 FILESTART=4 fi SCRIPT_DIR=$(dirname $(which $0)); AOPC_CLASSPATH=$SCRIPT_DIR/../lib/javassist.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop-client.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-reflect.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-mdr.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-spi.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-standalone-aspect-library.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/pluggable-instrumentor.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-common-core.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/trove.jar CTR=0 for param in $*; do CTR=`expr $CTR + 1` if [ $CTR -gt $FILESTART ]; then ARGS_AND_FILES=$ARGS_AND_FILES" "$param AOPC_CLASSPATH=$AOPC_CLASSPATH:$param fi done #Check for cygwin and convert path if necessary if (cygpath --version) >/dev/null 2>/dev/null; then AOPC_CLASSPATH=`cygpath --path --windows $AOPC_CLASSPATH` fi java -classpath $AOPC_CLASSPATH $AOPPATH $AOPCLASSPATH org.jboss.aop.standalone.Compiler $ARGS_AND_FILES libjboss-aop-java-2.0.1.GA.orig/bin/run-load.sh0000644000175000017500000000534411145122046021027 0ustar twernertwerner#!/bin/sh usage(){ echo Script file for running loadtime instrumented aop applications echo Usage: echo run-load.sh classpath [-aoppath path_to_aop.xml] [-aopclasspath path_to_annotated] [-verbose] Main.class [args] echo echo classpath: Classpath of your source files and all required libraries echo echo path_to_.aop.xml: Path to your *-aop.xml files (separated by colon) echo echo path_to_annotated: Path to jars/directories that have annotated aspects (separated by colon) echo echo -verbose: Specify if you want verbose output echo echo Main.class: Your main class echo echo args: The args to Main.class exit 1 } #Make sure have $1, $2, $3 and $4 if [ "x$1" = "x" ]; then usage fi if [ "x$2" = "x" ]; then usage fi if [ "x$3" = "x" ]; then usage fi if [ "x$4" = "x" ]; then usage fi if [ "$2" = "$4" ]; then usage fi USER_CLASSPATH=$1 AOPPATH= AOPCLASSPATH= if [ "$2" = "-aoppath" ]; then AOPPATH=-Djboss.aop.path=$3 FILESTART=3 fi if [ "$4" = "-aoppath" ]; then if [ "x$5" = "x" ]; then usage fi AOPPATH=-Djboss.aop.path=$5 FILESTART=5 fi if [ "$2" = "-aopclasspath" ]; then AOPCLASSPATH=-Djboss.aop.class.path=$3 FILESTART=3 fi if [ "$4" = "-aopclasspath" ]; then if [ "x$5" = "x" ]; then usage fi AOPCLASSPATH=-Djboss.aop.class.path=$5 FILESTART=5 fi SCRIPT_DIR=$(dirname $(which $0)); AOPC_CLASSPATH=$SCRIPT_DIR/../lib/javassist.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop-client.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-reflect.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-mdr.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-logging-spi.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-standalone-aspect-library.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/log4j.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/pluggable-instrumentor.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-aop.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/jboss-common-core.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$SCRIPT_DIR/../lib/trove.jar AOPC_CLASSPATH=$AOPC_CLASSPATH:$USER_CLASSPATH CTR=0 for param in $*; do CTR=`expr $CTR + 1` if [ $CTR -gt $FILESTART ]; then MAINCLASS_AND_ARGS=$MAINCLASS_AND_ARGS" "$param fi done #Check for cygwin and convert path if necessary if (cygpath --version) >/dev/null 2>/dev/null; then AOPC_CLASSPATH=`cygpath --path --windows $AOPC_CLASSPATH` fi java -javaagent:$SCRIPT_DIR/../lib/jboss-aop.jar -classpath $AOPC_CLASSPATH $AOPPATH $AOPCLASSPATH $MAINCLASS_AND_ARGS libjboss-aop-java-2.0.1.GA.orig/etc/0000755000175000017500000000000011145122046016747 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/etc/jbossorg-eula.txt0000644000175000017500000002002111145122046022257 0ustar twernertwernerLICENSE AGREEMENT JBOSS(r) This License Agreement governs the use of the Software Packages and any updates to the Software Packages, regardless of the delivery mechanism. Each Software Package is a collective work under U.S. Copyright Law. Subject to the following terms, Red Hat, Inc. ("Red Hat") grants to the user ("Client") a license to the applicable collective work(s) pursuant to the GNU Lesser General Public License v. 2.1 except for the following Software Packages: (a) JBoss Portal Forums and JBoss Transactions JTS, each of which is licensed pursuant to the GNU General Public License v.2; (b) JBoss Rules, which is licensed pursuant to the Apache License v.2.0; (c) an optional download for JBoss Cache for the Berkeley DB for Java database, which is licensed under the (open source) Sleepycat License (if Client does not wish to use the open source version of this database, it may purchase a license from Sleepycat Software); and (d) the BPEL extension for JBoss jBPM, which is licensed under the Common Public License v.1, and, pursuant to the OASIS BPEL4WS standard, requires parties wishing to redistribute to enter various royalty-free patent licenses. Each of the foregoing licenses is available at http://www.opensource.org/licenses/index.php. 1. The Software. "Software Packages" refer to the various software modules that are created and made available for distribution by the JBoss.org open source community at http://www.jboss.org. Each of the Software Packages may be comprised of hundreds of software components. The end user license agreement for each component is located in the component's source code. With the exception of certain image files identified in Section 2 below, the license terms for the components permit Client to copy, modify, and redistribute the component, in both source code and binary code forms. This agreement does not limit Client's rights under, or grant Client rights that supersede, the license terms of any particular component. 2. Intellectual Property Rights. The Software Packages are owned by Red Hat and others and are protected under copyright and other laws. Title to the Software Packages and any component, or to any copy, modification, or merged portion shall remain with the aforementioned, subject to the applicable license. The "JBoss" trademark, "Red Hat" trademark, the individual Software Package trademarks, and the "Shadowman" logo are registered trademarks of Red Hat and its affiliates in the U.S. and other countries. This agreement permits Client to distribute unmodified copies of the Software Packages using the Red Hat trademarks that Red Hat has inserted in the Software Packages on the condition that Client follows Red Hat's trademark guidelines for those trademarks located at http://www.redhat.com/about/corporate/trademark/. Client must abide by these trademark guidelines when distributing the Software Packages, regardless of whether the Software Packages have been modified. If Client modifies the Software Packages, then Client must replace all Red Hat trademarks and logos identified at http://www.jboss.com/company/logos, unless a separate agreement with Red Hat is executed or other permission granted. Merely deleting the files containing the Red Hat trademarks may corrupt the Software Packages. 3. Limited Warranty. Except as specifically stated in this Paragraph 3 or a license for a particular component, to the maximum extent permitted under applicable law, the Software Packages and the components are provided and licensed "as is" without warranty of any kind, expressed or implied, including the implied warranties of merchantability, non-infringement or fitness for a particular purpose. Red Hat warrants that the media on which Software Packages may be furnished will be free from defects in materials and manufacture under normal use for a period of 30 days from the date of delivery to Client. Red Hat does not warrant that the functions contained in the Software Packages will meet Client's requirements or that the operation of the Software Packages will be entirely error free or appear precisely as described in the accompanying documentation. This warranty extends only to the party that purchases the Services pertaining to the Software Packages from Red Hat or a Red Hat authorized distributor. 4. Limitation of Remedies and Liability. To the maximum extent permitted by applicable law, the remedies described below are accepted by Client as its only remedies. Red Hat's entire liability, and Client's exclusive remedies, shall be: If the Software media is defective, Client may return it within 30 days of delivery along with a copy of Client's payment receipt and Red Hat, at its option, will replace it or refund the money paid by Client for the Software. To the maximum extent permitted by applicable law, Red Hat or any Red Hat authorized dealer will not be liable to Client for any incidental or consequential damages, including lost profits or lost savings arising out of the use or inability to use the Software, even if Red Hat or such dealer has been advised of the possibility of such damages. In no event shall Red Hat's liability under this agreement exceed the amount that Client paid to Red Hat under this Agreement during the twelve months preceding the action. 5. Export Control. As required by U.S. law, Client represents and warrants that it: (a) understands that the Software Packages are subject to export controls under the U.S. Commerce Department's Export Administration Regulations ("EAR"); (b) is not located in a prohibited destination country under the EAR or U.S. sanctions regulations (currently Cuba, Iran, Iraq, Libya, North Korea, Sudan and Syria); (c) will not export, re-export, or transfer the Software Packages to any prohibited destination, entity, or individual without the necessary export license(s) or authorizations(s) from the U.S. Government; (d) will not use or transfer the Software Packages for use in any sensitive nuclear, chemical or biological weapons, or missile technology end-uses unless authorized by the U.S. Government by regulation or specific license; (e) understands and agrees that if it is in the United States and exports or transfers the Software Packages to eligible end users, it will, as required by EAR Section 740.17(e), submit semi-annual reports to the Commerce Department's Bureau of Industry & Security (BIS), which include the name and address (including country) of each transferee; and (f) understands that countries other than the United States may restrict the import, use, or export of encryption products and that it shall be solely responsible for compliance with any such import, use, or export restrictions. 6. Third Party Programs. Red Hat may distribute third party software programs with the Software Packages that are not part of the Software Packages and which Client must install separately. These third party programs are subject to their own license terms. The license terms either accompany the programs or can be viewed at http://www.redhat.com/licenses/. If Client does not agree to abide by the applicable license terms for such programs, then Client may not install them. If Client wishes to install the programs on more than one system or transfer the programs to another party, then Client must contact the licensor of the programs. 7. General. If any provision of this agreement is held to be unenforceable, that shall not affect the enforceability of the remaining provisions. This License Agreement shall be governed by the laws of the State of North Carolina and of the United States, without regard to any conflict of laws provisions, except that the United Nations Convention on the International Sale of Goods shall not apply. Copyright 2006 Red Hat, Inc. All rights reserved. "JBoss" and the JBoss logo are registered trademarks of Red Hat, Inc. All other trademarks are the property of their respective owners. Page 1 of 1 18 October 2006 libjboss-aop-java-2.0.1.GA.orig/etc/jboss-aop_1_0.dtd0000644000175000017500000000635411145122046022010 0ustar twernertwerner libjboss-aop-java-2.0.1.GA.orig/etc/jboss-aop_2_0.xsd0000644000175000017500000005311111145122046022025 0ustar twernertwerner libjboss-aop-java-2.0.1.GA.orig/etc/default.mf0000644000175000017500000000073011145122046020717 0ustar twernertwernerManifest-Version: 1.0 Created-By: @java.vm.version@ (@java.vm.vendor@) Specification-Title: @aop.title@ Specification-Version: @aop.version@ Specification-Vendor: @specification.vendor@ Implementation-Title: @aop.title@ Implementation-URL: @implementation.url@ Implementation-Version: @aop.version@ Implementation-Vendor: @implementation.vendor@ Implementation-Vendor-Id: @implementation.vendor.id@ Premain-Class: org.jboss.aop.standalone.Agent Can-Redefine-Classes: true libjboss-aop-java-2.0.1.GA.orig/aophelper/0000755000175000017500000000000011145122072020152 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/aophelper/README0000644000175000017500000000122511145122072021032 0ustar twernertwernerAophelper is an attempt to make it easier for people to start using aop. It will set up all the different jars and its possible to select different settings. Aophelper has two modes. One compile mode and one run mode; The compile mode will only try to aopcompile already compiled javacode. Run mode will try to run a aopcompiled program. It can also run it with loadtime weaving (which means that no aopcompile step is necessary. Note that Aophelper is still in a early beta stage, please report any issues/ideas to the aop dev team either to our forum or mailling list. TODO: 1. genereate a simple ant script from the settings. 2. rewrite the ui 3. +++ libjboss-aop-java-2.0.1.GA.orig/aophelper/resources/0000755000175000017500000000000011145122072022164 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/aophelper/resources/jboss-aop.xml0000644000175000017500000000034411145122072024604 0ustar twernertwerner libjboss-aop-java-2.0.1.GA.orig/aophelper/aophelper.sh0000644000175000017500000000103011145122072022457 0ustar twernertwerner#!/bin/sh AOP_PATH=$PWD/../lib CLASSPATH=$AOP_PATH/javassist.jar CLASSPATH=$CLASSPATH:$AOP_PATH/jboss-reflect.jar CLASSPATH=$CLASSPATH:$AOP_PATH/jboss-mdr.jar CLASSPATH=$CLASSPATH:$AOP_PATH/jboss-logging-spi.jar CLASSPATH=$CLASSPATH:$AOP_PATH/jboss-common-core.jar CLASSPATH=$CLASSPATH:$AOP_PATH/trove.jar CLASSPATH=$CLASSPATH:$AOP_PATH/jboss-aop.jar CLASSPATH=$CLASSPATH:$PWD/lib/aophelper.jar java -javaagent:$PWD/../lib/jboss-aop.jar -cp $CLASSPATH -Djboss.aop.path=resources/jboss-aop.xml org.jboss.aophelper.ui.AopHelperFrame libjboss-aop-java-2.0.1.GA.orig/aophelper/aophelper.bat0000644000175000017500000000110011145122072022611 0ustar twernertwerner@echo off SET PWD=%cd% SET AOP_PATH=%PWD%\..\lib SET CLASSPATH=%AOP_PATH%\javassist.jar CLASSPATH=%CLASSPATH%;%AOP_PATH%\jboss-reflect.jar CLASSPATH=%CLASSPATH%;%AOP_PATH%\jboss-mdr.jar CLASSPATH=%CLASSPATH%;%AOP_PATH%\jboss-logging-spi.jar CLASSPATH=%CLASSPATH%;%AOP_PATH%\jboss-common-core.jar CLASSPATH=%CLASSPATH%;%AOP_PATH%\trove.jar CLASSPATH=%CLASSPATH%;%AOP_PATH%\jboss-aop.jar CLASSPATH=%CLASSPATH%;%PWD%\lib\aophelper.jar java -javaagent:%PWD%\..\lib\jboss-aop.jar -cp %CLASSPATH% -Djboss.aop.path=resources\jboss-aop.xml org.jboss.aophelper.ui.AopHelperFrame libjboss-aop-java-2.0.1.GA.orig/aophelper/lib/0000755000175000017500000000000011145122072020720 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/0000755000175000017500000000000011145122070016760 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/0000755000175000017500000000000011145122070022423 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/0000755000175000017500000000000011145122070023347 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/0000755000175000017500000000000011145122070024136 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/0000755000175000017500000000000011145122070025256 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/0000755000175000017500000000000011145122070026035 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/domain/0000755000175000017500000000000011145122070027304 5ustar twernertwerner././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/domain/ScopedRepositoryClassLoaderDomain.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/domain/ScopedRepositoryClas0000644000175000017500000001231111145122070033345 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.domain; import org.jboss.aop.AspectManager; import org.jboss.aop.advice.AspectDefinition; import org.jboss.mx.loading.HeirarchicalLoaderRepository3; import org.jboss.mx.loading.LoaderRepository; import org.jboss.mx.loading.RepositoryClassLoader; /** * A domain that is used for scoped classloaders * * @author Kabir Khan * @author adrian@jboss.org * @version $Revision: 1.1 $ */ public class ScopedRepositoryClassLoaderDomain extends ScopedClassLoaderDomain { public ScopedRepositoryClassLoaderDomain(ClassLoader loader, String name, boolean parentDelegation, AspectManager manager, boolean parentFirst) { super(loader, name, parentDelegation, manager, parentFirst); } // FIXME: JBAOP-107 REMOVE THIS HACK public boolean isValid() { RepositoryClassLoader cl = (RepositoryClassLoader) getClassLoader(); if (cl == null) return false; return cl.getLoaderRepository() != null; } protected Object getPerVmAspectWithNoParentDelegation(String def) { Object aspect = myPerVMAspects.get(def); if (aspect != null) { return aspect; } aspect = super.getSuperPerVmAspect(def); if (aspect != null) { synchronized(myPerVMAspects) { LoaderRepository loadingRepository = getAspectRepository(aspect); LoaderRepository myRepository = getScopedRepository(); if (loadingRepository == myRepository) { //The parent does not load this class myPerVMAspects.put(def, aspect); } else { //The class has been loaded by a parent classloader, find out if we also have a copy try { Class clazz = myRepository.loadClass(aspect.getClass().getName()); if (clazz == aspect.getClass()) { notMyPerVMAspects.put(def, Boolean.TRUE); } else { //We have a different version of the class deployed AspectDefinition aspectDefinition = getAspectDefinition(def); //Override the classloader to create the aspect instance aspect = createPerVmAspect(def, aspectDefinition, getClassLoader()); myPerVMAspects.put(def, aspect); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } } return aspect; } private LoaderRepository getAspectRepository(Object aspect) { ClassLoader cl = aspect.getClass().getClassLoader(); ClassLoader parent = cl; while (parent != null) { if (parent instanceof RepositoryClassLoader) { return ((RepositoryClassLoader)parent).getLoaderRepository(); } parent = parent.getParent(); } return null; } private HeirarchicalLoaderRepository3 getScopedRepository() { ClassLoader classloader = getClassLoader(); if (classloader == null) throw new IllegalStateException("ClassLoader no longer exists: " + classLoaderString); if (classloader instanceof RepositoryClassLoader == false) throw new IllegalStateException("ClassLoader is not an instanceof RepositoryClassLoader " + classLoaderString); RepositoryClassLoader repositoryClassLoader = (RepositoryClassLoader) classloader; LoaderRepository loaderRepository = repositoryClassLoader.getLoaderRepository(); if (loaderRepository == null) throw new IllegalStateException("ClassLoader has been undeployed: " + classLoaderString); if (loaderRepository instanceof HeirarchicalLoaderRepository3 == false) throw new IllegalStateException("Repository " + loaderRepository + " for classlaoder " + classLoaderString + " is not an HeirarchicalLoaderRepository3"); return (HeirarchicalLoaderRepository3) loaderRepository; } } libjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployers/0000755000175000017500000000000011145122070030043 5ustar twernertwerner././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployers/AspectManagerJMXRegistrar.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployers/AspectManagerJMXR0000644000175000017500000000576511145122070033216 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployers; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.StandardMBean; import org.jboss.aop.asintegration.core.AspectManagerServiceDelegate; import org.jboss.aop.deployment.AbstractAspectManagerService; import org.jboss.aop.deployment.AbstractAspectManagerServiceMBean; import org.jboss.logging.Logger; /** * MC Bean to register and unregister the AspectManagerService MBean in JMX * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class AspectManagerJMXRegistrar { final static Logger log = Logger.getLogger(AspectManagerJMXRegistrar.class.getName()); final static String ASPECTMANAGER_OBJECTNAME = "jboss.aop:service=AspectManager"; MBeanServer server; AspectManagerServiceDelegate aspectManager; public void setMbeanServer(MBeanServer server) { this.server = server; } public void setAspectManager(AspectManagerServiceDelegate aspectManager) { this.aspectManager = aspectManager; } public void start() throws Exception { try { log.debug("Registering AspectManagerService in JMX under: " + ASPECTMANAGER_OBJECTNAME); server.registerMBean(new StandardMBean(new AbstractAspectManagerService(aspectManager), AbstractAspectManagerServiceMBean.class), new ObjectName(ASPECTMANAGER_OBJECTNAME)); } catch (Exception e) { // AutoGenerated throw new RuntimeException("Error starting AspectManagerJMXWrapper", e); } } public void stop() { try { log.debug("Unregistering AspectManagerService in JMX under: " + ASPECTMANAGER_OBJECTNAME); server.unregisterMBean(new ObjectName(ASPECTMANAGER_OBJECTNAME)); } catch (Exception e) { // AutoGenerated throw new RuntimeException("Error stopping AspectManagerJMXWrapper", e); } } } libjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/0000755000175000017500000000000011145122070030704 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/0000755000175000017500000000000011145122070032110 5ustar twernertwerner././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/JBossClassPool.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/JBossC0000644000175000017500000001034311145122070033157 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.security.ProtectionDomain; import org.jboss.aop.classpool.AOPClassPool; import org.jboss.mx.loading.RepositoryClassLoader; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.scopedpool.ScopedClassPoolRepository; /** * Comment * * @author Bill Burke * @author adrian@jboss.org * @version $Revision: 79518 $ */ public class JBossClassPool extends AOPClassPool { /** * Used for dynamically created classes (see loadClass(String, byte[]), ClassLoader) */ protected File tempdir = null; protected URL tempURL = null; // For loadClass tmpdir creation for UCL protected final Object tmplock = new Object(); protected JBossClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository, File tmp, URL tmpURL) { super(cl, src, repository); tempdir = tmp; tempURL = tmpURL; } protected JBossClassPool(ClassPool src, ScopedClassPoolRepository repository) { super(src, repository); } public boolean isUnloadedClassLoader() { if (getClassLoader() instanceof RepositoryClassLoader) { RepositoryClassLoader rcl = (RepositoryClassLoader) getClassLoader(); return rcl.getLoaderRepository() == null; } return false; } public Class toClass(CtClass cc, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException { lockInCache(cc); if (getClassLoader() == null || tempdir == null) { return super.toClass(cc, loader, domain); } Class dynClass = null; try { File classFile = null; String classFileName = getResourceName(cc.getName()); // Write the clas file to the tmpdir synchronized (tmplock) { classFile = new File(tempdir, classFileName); File pkgDirs = classFile.getParentFile(); pkgDirs.mkdirs(); FileOutputStream stream = new FileOutputStream(classFile); stream.write(cc.toBytecode()); stream.flush(); stream.close(); classFile.deleteOnExit(); } // We have to clear Blacklist caches or the class will never // be found //((UnifiedClassLoader)dcl).clearBlacklists(); // To be backward compatible RepositoryClassLoader rcl = (RepositoryClassLoader) getClassLoader(); rcl.clearClassBlackList(); rcl.clearResourceBlackList(); // Now load the class through the cl dynClass = getClassLoader().loadClass(cc.getName()); } catch (Exception ex) { ClassFormatError cfe = new ClassFormatError("Failed to load dyn class: " + cc.getName()); cfe.initCause(ex); throw cfe; } return dynClass; } @Override protected boolean isLocalResource(String resourceName) { if (super.isLocalResource(resourceName)) { return true; } File file = new File(tempdir, resourceName); if (file.exists()) { return true; } return false; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/SecurityActions.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/Securi0000644000175000017500000000516711145122070033276 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ class SecurityActions { interface GetParentAction { ClassLoader getParent(ClassLoader loader); GetParentAction NON_PRIVILEGED = new GetParentAction() { public ClassLoader getParent(ClassLoader loader) { return loader.getParent(); } }; GetParentAction PRIVILEGED = new GetParentAction() { public ClassLoader getParent(final ClassLoader loader) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public ClassLoader run() throws Exception { return loader.getParent(); } }); } catch (PrivilegedActionException e) { throw new RuntimeException(e.getException()); } } }; } public static ClassLoader getParent(ClassLoader loader) { if (loader == null) { return null; } if (System.getSecurityManager() == null) { return GetParentAction.NON_PRIVILEGED.getParent(loader); } else { return GetParentAction.PRIVILEGED.getParent(loader); } } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/JBoss4Integration.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/JBoss40000644000175000017500000001320111145122070033134 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import java.io.File; import javassist.ClassPool; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolFactory; import javassist.scopedpool.ScopedClassPoolRepository; import javax.management.Attribute; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.InvalidAttributeValueException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.ReflectionException; import org.jboss.aop.AspectManager; import org.jboss.aop.asintegration.JBossIntegration; import org.jboss.aop.classpool.AOPClassLoaderScopingPolicy; import org.jboss.aop.domain.ScopedRepositoryClassLoaderDomain; import org.jboss.mx.loading.HeirarchicalLoaderRepository3; import org.jboss.mx.loading.RepositoryClassLoader; import org.jboss.mx.server.ServerConstants; import org.jboss.mx.util.MBeanServerLocator; import org.jboss.mx.util.ObjectNameFactory; /** * JBoss4Integration.

* * This class and its associated classes are * for the old JBoss4 integration with the LoaderRepository

* *

* * @author Adrian Brock * @author Bill Burke * @author Kabir Khan * @version $Revision: 1.1 $ */ public class JBoss4Integration implements JBossIntegration, ScopedClassPoolFactory { static { //pre-load necessary classes so that we avoid NoClassDefFoundErrors on JRockit when using the RepositoryClassloader hook //When AspectManager.translate() is called the first time, these classes have not been loaded yet, and this is what causes //JRockit to get confused @SuppressWarnings("unused") Class clazz = HeirarchicalLoaderRepository3.class; } static final ObjectName DEFAULT_LOADER_REPOSITORY = ObjectNameFactory.create(ServerConstants.DEFAULT_LOADER_NAME); /** The delegate classpool factory */ private ScopedClassPoolFactory delegateClassPoolFactory; public boolean isValidClassLoader(ClassLoader loader) { if (!(loader instanceof RepositoryClassLoader)) return false; return ((RepositoryClassLoader) loader).getLoaderRepository() != null; } public AOPClassLoaderScopingPolicy createAOPClassLoaderScopingPolicy() { return new RepositoryClassLoaderScopingPolicy(); } public ScopedClassPoolFactory createScopedClassPoolFactory(File tmpDir) throws Exception { delegateClassPoolFactory = new JBossClassPoolFactory(tmpDir); return this; } public ScopedClassPool create(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { return delegateClassPoolFactory.create(cl, src, repository); } public ScopedClassPool create(ClassPool src, ScopedClassPoolRepository repository) { return delegateClassPoolFactory.create(src, repository); } public void attachDeprecatedTranslator() { AspectManager mgr = AspectManager.instance(); MBeanServer server = MBeanServerLocator.locateJBoss(); try { server.setAttribute(DEFAULT_LOADER_REPOSITORY, new Attribute("Translator", mgr)); } catch (InstanceNotFoundException e) { throw new RuntimeException(e); } catch (AttributeNotFoundException e) { throw new RuntimeException(e); } catch (InvalidAttributeValueException e) { throw new RuntimeException(e); } catch (MBeanException e) { throw new RuntimeException(e); } catch (ReflectionException e) { throw new RuntimeException(e); } } public void detachDeprecatedTranslator() { MBeanServer server = MBeanServerLocator.locateJBoss(); try { server.setAttribute(DEFAULT_LOADER_REPOSITORY, new Attribute("Translator", null)); } catch (InstanceNotFoundException e) { throw new RuntimeException(e); } catch (AttributeNotFoundException e) { throw new RuntimeException(e); } catch (InvalidAttributeValueException e) { throw new RuntimeException(e); } catch (MBeanException e) { throw new RuntimeException(e); } catch (ReflectionException e) { throw new RuntimeException(e); } } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/LoaderRepositoryUrlUtil.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/Loader0000644000175000017500000001246211145122070033246 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import java.net.URL; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import org.jboss.mx.loading.HeirarchicalLoaderRepository3; import org.jboss.mx.loading.LoaderRepository; import org.jboss.mx.util.MBeanServerLocator; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class LoaderRepositoryUrlUtil implements NotificationListener { final static MBeanServer SERVER; final static ObjectName MAIN_LOADER_REPOSITORY_OBJECT_NAME; final static LoaderRepository MAIN_LOADER_REPOSITORY; static { SERVER = MBeanServerLocator.locateJBoss(); try { MAIN_LOADER_REPOSITORY_OBJECT_NAME = new ObjectName("JMImplementation:name=Default,service=LoaderRepository"); MAIN_LOADER_REPOSITORY = (LoaderRepository)SERVER.invoke(MAIN_LOADER_REPOSITORY_OBJECT_NAME, "getInstance", new Object[0], new String[0]); } catch (Exception e) { throw new RuntimeException(e); } } long currentSequenceNumber; long lastSequenceNumber = -1; URL[] urls; public LoaderRepositoryUrlUtil() { try { SERVER.addNotificationListener(MAIN_LOADER_REPOSITORY_OBJECT_NAME, this, null, null); } catch (InstanceNotFoundException e) { throw new RuntimeException(e); } } public synchronized void handleNotification(Notification notification, Object handback) { if (notification.getType().equals(LoaderRepository.CLASSLOADER_ADDED)) { currentSequenceNumber = notification.getSequenceNumber(); } else if (notification.getType().equals(LoaderRepository.CLASSLOADER_REMOVED)) { currentSequenceNumber = notification.getSequenceNumber(); } } public synchronized UrlInfo getURLInfo(HeirarchicalLoaderRepository3 scopedLoader, UrlInfo urlInfo) { boolean changed = false; if (lastSequenceNumber != currentSequenceNumber) { urls = MAIN_LOADER_REPOSITORY.getURLs(); lastSequenceNumber = currentSequenceNumber; changed = true; } if (!changed) { changed = urlInfo != null && (urlInfo.getSequenceNumber() != lastSequenceNumber); } if (urlInfo == null || changed) { URL[] localUrls = getLocalUrls(scopedLoader, urls); urlInfo = new UrlInfo(urls, localUrls, lastSequenceNumber); } return urlInfo; } public long getCurrentSequenceNumber() { return currentSequenceNumber; } private URL[] getLocalUrls(HeirarchicalLoaderRepository3 scopedRepository, URL[] globalUrls) { URL[] scopedRepositoryUrls = scopedRepository.getURLs(); //This is a bit of a hack, since this relies on the order of the urls returned by HeirarchicalLoaderRepository3 //My urls, followed by parent urls. int scopedLength = 0; for (int i = 0 ; i < scopedRepositoryUrls.length ; i++) { for (int j = 0 ; j < globalUrls.length ; j ++) { if (scopedRepositoryUrls[i].equals(globalUrls[j])) { scopedLength = i; break; } } if (scopedLength > 0) { break; } } URL[] localUrls = new URL[scopedLength]; System.arraycopy(scopedRepositoryUrls, 0, localUrls, 0, scopedLength); return localUrls; } public class UrlInfo { URL[] globalUrls; URL[] localUrls; long sequenceNumber; public UrlInfo(URL[] globalUrls, URL[] localUrls, long sequenceNumber) { super(); this.globalUrls = globalUrls; this.localUrls = localUrls; this.sequenceNumber = sequenceNumber; } public URL[] getGlobalUrls() { return globalUrls; } public URL[] getLocalUrls() { return localUrls; } public long getSequenceNumber() { return sequenceNumber; } } } ././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/ScopedJBossClassPool.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/Scoped0000644000175000017500000002141611145122070033254 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import java.io.File; import java.net.URL; import java.util.ArrayList; import org.jboss.aop.AspectManager; import org.jboss.aop.classpool.AOPClassPool; import org.jboss.aop.classpool.AOPClassPoolRepository; import org.jboss.aop.asintegration.jboss4.LoaderRepositoryUrlUtil.UrlInfo; import org.jboss.mx.loading.HeirarchicalLoaderRepository3; import org.jboss.mx.loading.LoaderRepository; import org.jboss.mx.loading.RepositoryClassLoader; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import javassist.scopedpool.ScopedClassPoolRepository; /** * A classpool in JBoss backed by a scoped (HierarchicalLoaderRepository) loader repository * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ScopedJBossClassPool extends JBossClassPool { final static LoaderRepositoryUrlUtil LOADER_REPOSITORY_UTIL = new LoaderRepositoryUrlUtil(); private UrlInfo urlInfo; private ThreadLocal lastPool = new ThreadLocal(); public ScopedJBossClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository, File tmp, URL tmpURL) { super(cl, src, repository, tmp, tmpURL); boolean parentFirst = false; LoaderRepository loaderRepository = null; ClassLoader prnt = cl; while (prnt != null) { if (prnt instanceof RepositoryClassLoader) { loaderRepository = ((RepositoryClassLoader)prnt).getLoaderRepository(); if (loaderRepository instanceof HeirarchicalLoaderRepository3) { parentFirst = ((HeirarchicalLoaderRepository3)loaderRepository).getUseParentFirst(); } break; } prnt = SecurityActions.getParent(cl); } super.childFirstLookup = !parentFirst; } private HeirarchicalLoaderRepository3 getRepository() { ClassLoader cl = getClassLoader0(); if (cl != null) { return (HeirarchicalLoaderRepository3)((RepositoryClassLoader)cl).getLoaderRepository(); } return null; } private URL getResourceUrlForClass(String resourcename) { HeirarchicalLoaderRepository3 repo = getRepository(); return repo.getResource(resourcename, super.getClassLoader()); } private boolean isMine(URL url) { HeirarchicalLoaderRepository3 repo = getRepository(); if (repo != null) { //The URL of the class loaded with my scoped classloader if (url != null) { urlInfo = LOADER_REPOSITORY_UTIL.getURLInfo(getRepository(), urlInfo); URL[] myUrls = urlInfo.getLocalUrls(); String resource = url.toString(); for (int i = 0 ; i < myUrls.length ; i++) { if (resource.indexOf(myUrls[i].toString()) >= 0) { return true; } } return false; } } return true; } public CtClass getCached(String classname) { if (classname == null) { return null; } if (isUnloadedClassLoader()) { return null; } if (generatedClasses.get(classname) != null) { //It is a new class, and this callback is probably coming from the frozen check when creating a new nested class return super.getCached(classname); } //Is this from the scoped classloader itself of from the parent? String resourcename = getResourceName(classname); URL url = getResourceUrlForClass(resourcename); boolean isMine = isMine(url); if (isMine) { if (super.childFirstLookup) { //Parent delegation is false, attempt to get this class out of ourselves CtClass clazz = super.getCachedLocally(classname); if (clazz == null) { clazz = createCtClass(classname, false); if (clazz != null) { lockInCache(clazz); } } if (clazz != null) { return clazz; } } return super.getCached(classname); } try { ClassPool pool = getCorrectPoolForResource(classname, url); if (pool != lastPool.get()) { lastPool.set(pool); return pool.get(classname); } } catch (NotFoundException e) { } catch(StackOverflowError e) { throw e; } finally { lastPool.set(null); } return null; } @Override protected boolean includeInGlobalSearch() { return false; } private ClassPool getCorrectPoolForResource(String classname, URL url) { synchronized(AspectManager.getRegisteredCLs()) { //JBoss 5 has an extra NoAnnotationURLCLassLoader that is not on the default path, make sure that that is checked at the end //FIXME This needs revisiting/removing once the ArrayList noAnnotationURLClassLoaderPools = null; String resource = url.toString(); for(ClassPool pool : AspectManager.getRegisteredCLs().values()) { AOPClassPool candidate = (AOPClassPool)pool; if (candidate.isUnloadedClassLoader()) { AspectManager.instance().unregisterClassLoader(candidate.getClassLoader()); continue; } if (candidate.getClassLoader() instanceof RepositoryClassLoader) { //Sometimes the ClassLoader is a proxy for MBeanProxyExt?! RepositoryClassLoader rcl = (RepositoryClassLoader)candidate.getClassLoader(); URL[] urls = rcl.getClasspath(); for (int i = 0 ; i < urls.length ; i++) { if (resource.indexOf(urls[i].getFile()) >= 0) { return candidate; } } } //FIXME Remove once we have the JBoss 5 version of pool else if (isInstanceOfNoAnnotationURLClassLoader(candidate.getClassLoader())) { if (noAnnotationURLClassLoaderPools == null) { noAnnotationURLClassLoaderPools = new ArrayList(); } noAnnotationURLClassLoaderPools.add(candidate); } } //FIXME Remove once we have the JBoss 5 version of pool if (noAnnotationURLClassLoaderPools != null) { for (AOPClassPool pool : noAnnotationURLClassLoaderPools) { try { pool.get(classname); return pool; } catch(NotFoundException ignoreTryNext) { } } } } return AOPClassPool.createAOPClassPool(ClassPool.getDefault(), AOPClassPoolRepository.getInstance()); } /** * NoAnnotationURLCLassLoader lives in different packages in JBoss 4 and 5 */ private boolean isInstanceOfNoAnnotationURLClassLoader(ClassLoader loader) { Class parent = loader.getClass(); while (parent != null) { if ("NoAnnotationURLClassLoader".equals(parent.getSimpleName())) { return true; } parent = parent.getSuperclass(); } return false; } } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/RepositoryClassLoaderScopingPolicy.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/Reposi0000644000175000017500000001274411145122070033304 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import java.util.Map; import java.util.WeakHashMap; import org.jboss.aop.AspectManager; import org.jboss.aop.Domain; import org.jboss.aop.classpool.AOPClassLoaderScopingPolicy; import org.jboss.aop.classpool.AOPClassPoolRepository; import org.jboss.aop.domain.ScopedRepositoryClassLoaderDomain; import org.jboss.logging.Logger; import org.jboss.mx.loading.HeirarchicalLoaderRepository3; import org.jboss.mx.loading.RepositoryClassLoader; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class RepositoryClassLoaderScopingPolicy implements AOPClassLoaderScopingPolicy { Logger log = Logger.getLogger(RepositoryClassLoaderScopingPolicy.class); /** A map of domains by loader repository, maintaned by the top level AspectManager */ private Map scopedClassLoaderDomains = new WeakHashMap(); public synchronized Domain getDomain(ClassLoader classLoader, AspectManager parent) { ClassLoader scopedClassLoader = ifScopedDeploymentGetScopedParentUclForCL(classLoader); if (scopedClassLoader != null) { Domain scopedManager = null; synchronized (AOPClassPoolRepository.getInstance().getRegisteredCLs()) { Object loaderRepository = getLoaderRepository(classLoader); scopedManager = scopedClassLoaderDomains.get(loaderRepository); // FIXME: JBAOP-107 REMOVE THIS HACK if (scopedManager != null && scopedManager.isValid() == false) { scopedClassLoaderDomains.remove(loaderRepository); scopedManager = null; } if (scopedManager == null) { scopedManager = getScopedClassLoaderDomain(scopedClassLoader, parent); log.debug("Created domain " + scopedManager + " for scoped deployment on: " + classLoader + "; identifying scoped ucl: " + scopedClassLoader); scopedManager.setInheritsBindings(true); scopedManager.setInheritsDeclarations(true); scopedClassLoaderDomains.put(loaderRepository, scopedManager); } return scopedManager; } } return null; } public Domain getTopLevelDomain(AspectManager parent) { ClassLoader classLoader = getTopLevelJBossClassLoader(); return getDomain(classLoader, parent); } ////////// private ClassLoader ifScopedDeploymentGetScopedParentUclForCL(ClassLoader loader) { ClassLoader parent = loader; //The web classloader will be a child of the unified classloader - find out if that is scoped while (parent != null) { if (ScopedRepositoryClassLoaderHelper.isScopedClassLoader(parent)) { return parent; } if (parent instanceof RepositoryClassLoader) { //We were a repository classloader, but not scoped - ignore the parents like a sulky teenager return null; } parent = parent.getParent(); } return null; } private ClassLoader getTopLevelJBossClassLoader() { ClassLoader loader = Thread.currentThread().getContextClassLoader(); RepositoryClassLoader topRcl = null; while (loader != null) { if (loader instanceof RepositoryClassLoader) { topRcl = (RepositoryClassLoader)loader; } loader = loader.getParent(); } return topRcl; } private Domain getScopedClassLoaderDomain(ClassLoader cl, AspectManager parent) { boolean parentDelegation = true; if (cl instanceof RepositoryClassLoader) { HeirarchicalLoaderRepository3 repository = (HeirarchicalLoaderRepository3)((RepositoryClassLoader)cl).getLoaderRepository(); parentDelegation = repository.getUseParentFirst(); } String name = String.valueOf(System.identityHashCode(cl)); return new ScopedRepositoryClassLoaderDomain(cl, name, parentDelegation, parent, false); } private Object getLoaderRepository(ClassLoader loader) { ClassLoader cl = ifScopedDeploymentGetScopedParentUclForCL(loader); if (cl != null) { return ((RepositoryClassLoader)cl).getLoaderRepository(); } return null; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/JBossClassPoolFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/JBossC0000644000175000017500000000744411145122070033167 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import java.io.File; import java.io.IOException; import java.net.URL; import org.jboss.aop.classpool.AOPClassPool; import org.jboss.aop.classpool.AbstractJBossClassPoolFactory; import org.jboss.mx.loading.RepositoryClassLoader; import javassist.ClassPool; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolFactory; import javassist.scopedpool.ScopedClassPoolRepository; /** * Comment * * @author Bill Burke * @author adrian@jboss.org * @version $Revision: 70841 $ **/ public class JBossClassPoolFactory extends AbstractJBossClassPoolFactory implements ScopedClassPoolFactory { protected File tmpClassesDir; public JBossClassPoolFactory(File tmpClassesDir) throws IOException { this.tmpClassesDir = tmpClassesDir; } public ScopedClassPool create(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { ClassPool parent = getCreateParentClassPools(cl, src, repository); if (cl instanceof RepositoryClassLoader) { File tempdir = getTempDirectory(cl); URL tmpCP; try { tmpCP = createURLAndAddToLoader(cl, tempdir); } catch (IOException e) { throw new RuntimeException(e); } if (ScopedRepositoryClassLoaderHelper.isScopedClassLoader(cl)) { //It is scoped return new ScopedJBossClassPool(cl, parent, repository, tempdir, tmpCP); } return new JBossClassPool(cl, parent, repository, tempdir, tmpCP); } return new AOPClassPool(cl, parent, repository); } protected File getTempDirectory(ClassLoader cl) { File tempdir = null; int attempts = 0; IOException ex = null; while (tempdir == null && attempts < 5) { //Workaround for JBAOP-254, retry a few times try { tempdir = createTempDir(cl); } catch (IOException e) { ex = e; } } if (tempdir == null) { throw new RuntimeException("", ex); } return tempdir; } public File createTempDir(ClassLoader cl) throws IOException { File tempdir = File.createTempFile("ucl", "", tmpClassesDir); tempdir.delete(); tempdir.mkdir(); tempdir.deleteOnExit(); return tempdir; } private URL createURLAndAddToLoader(ClassLoader cl, File tempdir) throws IOException { URL tmpURL = tempdir.toURL(); URL tmpCP = new URL(tmpURL, "?dynamic=true"); RepositoryClassLoader ucl = (RepositoryClassLoader) cl; // We may be undeploying. if (ucl.getLoaderRepository() != null) { ucl.addURL(tmpCP); } return tmpCP; } } ././@LongLink0000000000000000000000000000020500000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/ScopedRepositoryClassLoaderHelper.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/asintegration/jboss4/Scoped0000644000175000017500000000366611145122070033263 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.jboss4; import org.jboss.mx.loading.HeirarchicalLoaderRepository3; import org.jboss.mx.loading.LoaderRepository; import org.jboss.mx.loading.RepositoryClassLoader; /** * * @author Kabir Khan * @autor adrian@jboss.org * @version $Revision$ */ public class ScopedRepositoryClassLoaderHelper { public static boolean isScopedClassLoader(ClassLoader loader) { boolean scoped = false; if (loader instanceof RepositoryClassLoader) { LoaderRepository repository = ((RepositoryClassLoader)loader).getLoaderRepository(); if (repository instanceof HeirarchicalLoaderRepository3) { scoped = true; //HeirarchicalLoaderRepository3 hlr = (HeirarchicalLoaderRepository3)repository; //boolean parentFirst = hlr.getUseParentFirst(); } } return scoped; } } libjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/0000755000175000017500000000000011145122070030215 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectDeployer40.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectDeployer400000644000175000017500000000226511145122070033234 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; /** * comment * * @author Bill Burke */ public class AspectDeployer40 extends AspectDeployer { public AspectDeployer40() { } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectManagerServiceJDK5.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectManagerSer0000644000175000017500000000310111145122070033317 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; import org.jboss.aop.asintegration.core.AspectManagerServiceDelegate; import org.jboss.aop.asintegration.core.AspectManagerServiceDelegateJDK5; /** * @author Bill Burke * @version $Revision: 57692 $ */ public class AspectManagerServiceJDK5 extends AbstractAspectManagerService { public AspectManagerServiceJDK5() { } protected AspectManagerServiceDelegate createDelegate() { return new AspectManagerServiceDelegateJDK5(); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectDeployerMBean.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectDeployerMB0000644000175000017500000000575011145122070033311 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; /** * MBean interface. */ public interface AspectDeployerMBean extends org.jboss.deployment.SubDeployerMBean { //default object name public static final javax.management.ObjectName OBJECT_NAME = org.jboss.mx.util.ObjectNameFactory.create("jboss.aspect:AspectDeployer"); /** * Returns true if this deployer can deploy the given DeploymentInfo. * @return True if this deployer can deploy the given DeploymentInfo. */ boolean accepts(org.jboss.deployment.DeploymentInfo di) ; /** * Describe init method here. * @param di a DeploymentInfo value * @throws DeploymentException if an error occurs */ void init(org.jboss.deployment.DeploymentInfo di) throws org.jboss.deployment.DeploymentException; /** * Describe create method here. * @param di a DeploymentInfo value * @throws DeploymentException if an error occurs */ void create(org.jboss.deployment.DeploymentInfo di) throws org.jboss.deployment.DeploymentException; /** * The start method starts all the mbeans in this DeploymentInfo.. * @param di a DeploymentInfo value * @throws DeploymentException if an error occurs */ void start(org.jboss.deployment.DeploymentInfo di) throws org.jboss.deployment.DeploymentException; /** * Undeploys the package at the url string specified. This will: Undeploy packages depending on this one. Stop, destroy, and unregister all the specified mbeans Unload this package and packages this package deployed via the classpath tag. Keep track of packages depending on this one that we undeployed so that they can be redeployed should this one be redeployed. * @param di the DeploymentInfo value to stop. */ void stop(org.jboss.deployment.DeploymentInfo di) ; /** * Describe destroy method here. * @param di a DeploymentInfo value */ void destroy(org.jboss.deployment.DeploymentInfo di) ; } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/JBoss4IntegrationWrapper.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/JBoss4Integratio0000644000175000017500000000272211145122070033275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; import org.jboss.aop.asintegration.JBossIntegration; import org.jboss.aop.asintegration.jboss4.JBoss4Integration; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class JBoss4IntegrationWrapper implements JBoss4IntegrationWrapperMBean { JBoss4Integration integration = new JBoss4Integration(); public JBossIntegration getIntegration() { return integration; } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AbstractAspectManagerServiceMBean.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AbstractAspectMa0000644000175000017500000000743711145122070033334 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; /** * MBean interface. */ public interface AbstractAspectManagerServiceMBean extends org.jboss.system.ServiceMBean { /** * The temporary directory to which dyn class files are written */ java.io.File getTmpClassesDir() ; /** * The temporary directory to which dyn class files are written */ void setTmpClassesDir(java.io.File tmpClassesDir) ; /** * Set the verbosity of aop logging. It doesn't use log4j */ boolean getVerbose() ; /** * Set the verbosity of aop logging. It doesn't use log4j */ void setVerbose(boolean verbose) ; /** * Use aop optimizations. Optional just in case there is a bug */ boolean getOptimized() ; /** * Use aop optimizations. Optional just in case there is a bug */ void setOptimized(boolean verbose) ; boolean getSuppressTransformationErrors() ; void setSuppressTransformationErrors(boolean suppressTransformationErrors) ; /** * The temporary directory to which dyn class files are written */ boolean getEnableTransformer() ; /** * The temporary directory to which dyn class files are written */ boolean getEnableLoadtimeWeaving() ; /** * The temporary directory to which dyn class files are written */ java.lang.String interceptorFactories() ; /** * The temporary directory to which dyn class files are written */ java.lang.String aspectDefinitions() ; java.lang.String introductions() ; /** * The temporary directory to which dyn class files are written */ java.lang.String stacks() ; /** * The temporary directory to which dyn class files are written */ java.lang.String bindings() ; java.lang.String pointcuts(); /** * The temporary directory to which dyn class files are written */ java.lang.String registeredClassLoaders() ; /** * The temporary directory to which dyn class files are written */ void setEnableTransformer(boolean enableTransformer) ; void setEnableLoadtimeWeaving(boolean enableTransformer) ; String getExclude(); void setExclude(String exclude); String getInclude(); void setInclude(String include); String getIncludedInvisibleAnnotations(); void setIncludedInvisibleAnnotations(String ia); boolean getPrune(); void setPrune(boolean prune); String getIgnore(); void setIgnore(String ignore); String getInstrumentor(); void setInstrumentor(String instrumentor); /** * Whether or not tu use base-aop.xml */ boolean getUseBaseXml(); /** * Whether or not tu use base-aop.xml */ void setUseBaseXml(boolean useBaseXml); /** * Sets the MBean containing the JBossIntegration implementation */ void setJBossIntegrationWrapper(JBossIntegrationWrapperMBean integration); } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/JBoss4IntegrationWrapperMBean.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/JBoss4Integratio0000644000175000017500000000232711145122070033276 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public interface JBoss4IntegrationWrapperMBean extends JBossIntegrationWrapperMBean { } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/JBossIntegrationWrapperMBean.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/JBossIntegration0000644000175000017500000000241111145122070033362 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; import org.jboss.aop.asintegration.JBossIntegration; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public interface JBossIntegrationWrapperMBean { JBossIntegration getIntegration(); } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectManagerService.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectManagerSer0000644000175000017500000000303111145122070033321 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; import org.jboss.aop.asintegration.core.AspectManagerServiceDelegate; import org.jboss.aop.asintegration.core.AspectManagerServiceDelegateJRockit; /** * AspectManager service meant for use with JRockit or JDK 1.4 * * @author Kabir Khan * @version $Revision: 78670 $ */ public class AspectManagerService extends AbstractAspectManagerService { protected AspectManagerServiceDelegate createDelegate() { return new AspectManagerServiceDelegateJRockit(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectDeployer.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AspectDeployer.j0000644000175000017500000003176111145122070033323 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; import java.io.File; import java.net.URL; import java.util.Iterator; import javax.management.InstanceNotFoundException; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.Notification; import javax.management.ObjectName; import org.jboss.aop.AspectAnnotationLoader; import org.jboss.aop.AspectManager; import org.jboss.aop.AspectXmlLoader; import org.jboss.aop.asintegration.jboss4.ScopedRepositoryClassLoaderHelper; import org.jboss.deployment.DeploymentException; import org.jboss.deployment.DeploymentInfo; import org.jboss.deployment.DeploymentState; import org.jboss.deployment.SubDeployer; import org.jboss.deployment.SubDeployerSupport; import org.jboss.mx.loading.HeirarchicalLoaderRepository3; import org.jboss.mx.loading.LoaderRepository; import org.jboss.util.file.ArchiveBrowser; import org.jboss.util.file.ClassFileFilter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Deployer for Aspects * * @author Bill Burke * @author Dimitris Andreadis * @version $Revision: 70841 $ * @jmx:mbean name="jboss.aspect:AspectDeployer" * extends="org.jboss.deployment.SubDeployerMBean" */ public class AspectDeployer extends SubDeployerSupport implements SubDeployer, AspectDeployerMBean { /** * Default CTOR used to set default values to the Suffixes and RelativeOrder * attributes. Those are read at subdeployer registration time by the MainDeployer * to alter its SuffixOrder. */ public AspectDeployer() { initializeMainDeployer(); } /** * Set the suffixes and relative order attributes. * * Those are read at subdeployer registration time by the MainDeployer * to update its SuffixOrder list. */ protected void initializeMainDeployer() { setSuffixes(new String[]{".aop", "-aop.xml"}); setRelativeOrder(100); } /** * Returns true if this deployer can deploy the given DeploymentInfo. * * @return True if this deployer can deploy the given DeploymentInfo. * @jmx:managed-operation */ public boolean accepts(DeploymentInfo di) { String urlStr = di.url.toString(); return urlStr.endsWith(".aop") || urlStr.endsWith(".aop/") || urlStr.endsWith("-aop.xml"); } /** * Describe init method here. * * @param di a DeploymentInfo value * @throws DeploymentException if an error occurs * @jmx:managed-operation */ public void init(DeploymentInfo di) throws DeploymentException { try { if (di.watch == null) { // resolve the watch if (di.url.getProtocol().equals("file")) { File file = new File(di.url.getFile()); // If not directory we watch the package if (!file.isDirectory()) { di.watch = di.url; } // If directory we watch the xml files else { di.watch = new URL(di.url, "META-INF/jboss-aop.xml"); } } else { // We watch the top only, no directory support di.watch = di.url; } } } catch (Exception e) { log.error("failed to parse AOP document: ", e); throw new DeploymentException(e); } super.init(di); } /** * Describe create method here. * * @param di a DeploymentInfo value * @throws DeploymentException if an error occurs * @jmx:managed-operation */ public void create(DeploymentInfo di) throws DeploymentException { ClassLoader old = Thread.currentThread().getContextClassLoader(); try { URL docURL = getDocUrl(di); ClassLoader scl = getScopedClassLoader(di, docURL); if (scl != null) { log.info("AOP deployment is scoped using classloader " + scl); } Thread.currentThread().setContextClassLoader(di.ucl); AspectManager manager = (scl != null) ? AspectManager.instance(scl) : AspectManager.instance(); if (!di.isXML) { @SuppressWarnings("unchecked") Iterator it = ArchiveBrowser.getBrowser(di.localUrl, new ClassFileFilter()); AspectAnnotationLoader loader = new AspectAnnotationLoader(manager); loader.setClassLoader(scl); loader.deployInputStreamIterator(it); } AspectXmlLoader.deployXML(docURL, scl, manager); Notification msg = new Notification("AOP Deploy", this, getNextNotificationSequenceNumber()); sendNotification(msg); log.debug("Deployed AOP: " + di.url); } catch (Exception ex) { ex.printStackTrace(); throw new DeploymentException(ex); } finally { Thread.currentThread().setContextClassLoader(old); } } /** * The start method starts all the mbeans in this DeploymentInfo.. * * @param di a DeploymentInfo value * @throws DeploymentException if an error occurs * @jmx:managed-operation */ public void start(DeploymentInfo di) throws DeploymentException { } /** * Undeploys the package at the url string specified. This will: Undeploy * packages depending on this one. Stop, destroy, and unregister all the * specified mbeans Unload this package and packages this package deployed * via the classpath tag. Keep track of packages depending on this one that * we undeployed so that they can be redeployed should this one be * redeployed. * * @param di the DeploymentInfo value to stop. * @jmx:managed-operation */ public void stop(DeploymentInfo di) //throws DeploymentException { // Can happen on shutdown with a nested .aop module // which is first stopped then undeployed. if (di.state != DeploymentState.STARTED) { log.debug("Ignoring request to stop '" + di.url + "', current state: " + di.state); return; } log.debug("undeploying document " + di.url); ClassLoader old = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(di.ucl); if (!di.isXML) { @SuppressWarnings("unchecked") Iterator it = ArchiveBrowser.getBrowser(di.localUrl, new ClassFileFilter()); AspectAnnotationLoader loader = new AspectAnnotationLoader(AspectManager.instance()); loader.undeployInputStreamIterator(it); } URL docURL = getDocUrl(di); //long start = System.currentTimeMillis(); AspectXmlLoader.undeployXML(docURL); AspectManager.instance().unregisterClassLoader(di.ucl); /* // System.out.println("************************"); // System.out.println("undeploy took: " + (System.currentTimeMillis() - start)); // System.out.println("************************"); */ Notification msg = new Notification("AOP Undeploy", this, getNextNotificationSequenceNumber()); sendNotification(msg); } catch (Exception ex) { log.error("failed to stop", ex); } finally { Thread.currentThread().setContextClassLoader(old); } } /** * Describe destroy method here. * * @param di a DeploymentInfo value * @jmx:managed-operation */ public void destroy(DeploymentInfo di) //throws DeploymentException { } /** * The startService method gets the mbeanProxies for MainDeployer * and ServiceController, used elsewhere. * * @throws Exception if an error occurs */ protected void startService() throws Exception { super.startService(); } protected ObjectName getObjectName(MBeanServer server, ObjectName name) throws MalformedObjectNameException { return name == null ? OBJECT_NAME : name; } private URL getDocUrl(DeploymentInfo di) throws DeploymentException { URL docURL = di.localUrl; if (di.isXML == false) docURL = di.localCl.findResource("META-INF/jboss-aop.xml"); // Validate that the descriptor was found if (docURL == null) throw new DeploymentException("Failed to find META-INF/jboss-aop.xml"); return docURL; } private ClassLoader getScopedClassLoader(DeploymentInfo di, URL docUrl) throws Exception { //Scoped AOP deployments are only available when deployed as part of a scoped sar, ear etc. //It can contain an aop.xml file, or it can be part of a .aop file //Linking a standalone -aop.xml file onto a scoped deployment is not possible at the moment if (ScopedRepositoryClassLoaderHelper.isScopedClassLoader(di.ucl)) { return di.ucl; } LoaderRepository attachToRepository = getLoaderRepositoryIfAttaching(di, docUrl); if (attachToRepository != null) { di.ucl.setRepository(attachToRepository); attachToRepository.addClassLoader(di.ucl); return di.ucl; } return null; } private LoaderRepository getLoaderRepositoryIfAttaching(DeploymentInfo di, URL docUrl) throws Exception { if (di.parent == null) { //We are a top-level deployment, check if we are meant to be attaching to a scoped repository Document doc = AspectXmlLoader.loadURL(docUrl); Element top = doc.getDocumentElement(); NodeList children = top.getChildNodes(); int childlength = children.getLength(); for (int i = 0; i < childlength ; i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)child; if (element.getTagName().equals("loader-repository")) { String repositoryName = null; NodeList nestedChildren = child.getChildNodes(); int nestedChildLength = nestedChildren.getLength(); for (int j = 0 ; j < nestedChildLength ; j++) { Node nestedChild = nestedChildren.item(j); if (nestedChild.getNodeType() == Node.TEXT_NODE || nestedChild.getNodeType() == Node.CDATA_SECTION_NODE) { repositoryName = nestedChild.getNodeValue().trim(); break; } } log.info("Should attach deployment to loader repository " + repositoryName); ObjectName on; try { on = new ObjectName(repositoryName); } catch (MalformedObjectNameException e) { throw new RuntimeException("loader-repository='" + repositoryName + "' is not a valid object name", e); } try { @SuppressWarnings("unused") MBeanInfo info = server.getMBeanInfo(on); } catch (InstanceNotFoundException e) { log.warn("No scoped loader repository exists with the name " + on); } LoaderRepository repository = (LoaderRepository)server.getAttribute(on, "Instance"); if (repository instanceof HeirarchicalLoaderRepository3) { return repository; } else { log.warn("Loader repository " + on + " is not a isolated loader repository. Deploying aspects in default domain."); } } } } } return null; } }././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AbstractAspectManagerService.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/main/org/jboss/aop/deployment/AbstractAspectMa0000644000175000017500000002010711145122070033321 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.deployment; import java.io.File; import javassist.scopedpool.ScopedClassPoolFactory; import javax.management.Notification; import org.jboss.aop.AspectManager; import org.jboss.aop.AspectNotificationHandler; import org.jboss.aop.ClassLoaderValidation; import org.jboss.aop.asintegration.JBossIntegration; import org.jboss.aop.asintegration.core.AspectManagerServiceDelegate; import org.jboss.logging.Logger; import org.jboss.system.ServiceMBeanSupport; /** * @author Bill Burke * @author adrian@jboss.org * @version $Revision: 70855 $ */ public class AbstractAspectManagerService extends ServiceMBeanSupport implements AbstractAspectManagerServiceMBean, AspectNotificationHandler { Logger log = Logger.getLogger(AbstractAspectManagerService.class); private static final String BASE_XML = "base-aop.xml"; //private boolean registerHappensAfterStart; private AspectManagerServiceDelegate delegate; // Static ------------------------------------------------------- // Constructors ------------------------------------------------- /** * This constructor shouuld only get called when used in JBoss 4.x.x, not in JBoss 5. */ public AbstractAspectManagerService() { //Initialise the manager and delegate delegate = createDelegate(); delegate.setBaseXml(BASE_XML); delegate.setAspectManager(AspectManager.getTopLevelAspectManager()); //This constructor shouuld only get called when used in JBoss 4.x.x, not in JBoss 5. //In JBoss 4 we need to maintain this field delegate.setAspectManagerMaintainAdvisorInterceptors(true); //Default delegate.setUseBaseXml(true); } /** * This constructor should only get called when used in JBoss 5 by JBossAspectLibrary. */ public AbstractAspectManagerService(AspectManagerServiceDelegate delegate) { this.delegate = delegate; } protected AspectManagerServiceDelegate createDelegate() { throw new RuntimeException("Should not use this class directly"); } // Public ------------------------------------------------------- public void setJBossIntegrationWrapper(JBossIntegrationWrapperMBean integration) { JBossIntegration intgr = integration != null ? integration.getIntegration() : null; delegate.setJBossIntegration(intgr); } protected ScopedClassPoolFactory createFactory() throws Exception { return delegate.createFactory(); } protected ClassLoaderValidation createClassLoaderValidation() { return delegate.createClassLoaderValidation(); } @Override protected void createService() throws Exception { delegate.create(); AspectManager.notificationHandler = this; } @Override protected void destroyService() throws Exception { delegate.destroy(); } @Override protected void startService() throws Exception { delegate.start(); } @Override protected void stopService() throws Exception { delegate.stop(); } public void attachClass(String classname) { Notification msg = new Notification("AOP class attached", this, getNextNotificationSequenceNumber()); msg.setUserData(classname); sendNotification(msg); } public boolean getPrune() { return delegate.getPrune(); } public void setPrune(boolean prune) { delegate.setPrune(prune); } public String getExclude() { return delegate.getExclude(); } public void setExclude(String exclude) { delegate.setExclude(exclude); } public String getInclude() { return delegate.getInclude(); } public void setInclude(String include) { delegate.setInclude(include); } public String getIgnore() { return delegate.getIgnore(); } public void setIgnore(String ignore) { delegate.setIgnore(ignore); } public String getIncludedInvisibleAnnotations() { return delegate.getIncludedInvisibleAnnotations(); } public void setIncludedInvisibleAnnotations(String ia) { delegate.setIncludedInvisibleAnnotations(ia); } /** * The temporary directory to which dyn class files are written */ public File getTmpClassesDir() { return delegate.getTmpClassesDir(); } /** * The temporary directory to which dyn class files are written */ public void setTmpClassesDir(File tmpClassesDir) { delegate.setTmpClassesDir(tmpClassesDir); } /** * Set the verbosity of aop logging. It doesn't use log4j */ public boolean getVerbose() { return delegate.getVerbose(); } /** * Set the verbosity of aop logging. */ public void setVerbose(boolean verbose) { delegate.setVerbose(verbose); } /** * Use aop optimizations. Optional just in case there is a bug */ public boolean getOptimized() { return delegate.getOptimized(); } /** * Use aop optimizations. Optional just in case there is a bug */ public void setOptimized(boolean verbose) { delegate.setOptimized(verbose); } public boolean getSuppressTransformationErrors() { return delegate.getSuppressReferenceErrors(); } public void setSuppressTransformationErrors(boolean suppressTransformationErrors) { delegate.setSuppressTransformationErrors(suppressTransformationErrors); } public boolean getSuppressReferenceErrors() { return delegate.getSuppressReferenceErrors(); } public void setSuppressReferenceErrors(boolean suppressReferenceErrors) { delegate.setSuppressReferenceErrors(suppressReferenceErrors); } public boolean getEnableTransformer() { return delegate.getEnableTransformer(); } public String interceptorFactories() { return delegate.interceptorFactories(); } public String aspectDefinitions() { return delegate.aspectDefinitions(); } public String introductions() { return delegate.introductions(); } public String stacks() { return delegate.stacks(); } public String bindings() { return delegate.bindings(); } public String pointcuts() { return delegate.pointcuts(); } public String registeredClassLoaders() { return delegate.registeredClassLoaders(); } public void setEnableTransformer(boolean enableTransformer) { delegate.setEnableTransformer(enableTransformer); } public boolean getEnableLoadtimeWeaving() { return delegate.getEnableLoadtimeWeaving(); } public void setEnableLoadtimeWeaving(boolean enableTransformer) { delegate.setEnableLoadtimeWeaving(enableTransformer); } public String getInstrumentor() { return delegate.getInstrumentor(); } public void setInstrumentor(String instrumentor) { delegate.setInstrumentor(instrumentor); } public boolean getUseBaseXml() { return delegate.getUseBaseXml(); } public synchronized void setUseBaseXml(boolean useBaseXml) { delegate.setUseBaseXml(useBaseXml); } } libjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/resources/0000755000175000017500000000000011145122070024435 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/resources/META-INF/0000755000175000017500000000000011145122070025575 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/resources/META-INF/jboss-service.xml0000644000175000017500000000563411145122070031105 0ustar twernertwerner false true true org.jboss.test, org.jboss.injbossaop org.jboss. true false jboss.aop:service=JBoss4IntegrationWrapper jboss.system:service=MainDeployer libjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/etc/0000755000175000017500000000000011145122070023176 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/etc/jbossorg-eula.txt0000644000175000017500000001764611145122070026531 0ustar twernertwernerLICENSE AGREEMENT JBOSS(r) This License Agreement governs the use of the Software Packages and any updates to the Software Packages, regardless of the delivery mechanism. Each Software Package is a collective work under U.S. Copyright Law. Subject to the following terms, Red Hat, Inc. ("Red Hat") grants to the user ("Client") a license to the applicable collective work(s) pursuant to the GNU Lesser General Public License v. 2.1 except for the following Software Packages: (a) JBoss Portal Forums and JBoss Transactions JTS, each of which is licensed pursuant to the GNU General Public License v.2; (b) JBoss Rules, which is licensed pursuant to the Apache License v.2.0; (c) an optional download for JBoss Cache for the Berkeley DB for Java database, which is licensed under the (open source) Sleepycat License (if Client does not wish to use the open source version of this database, it may purchase a license from Sleepycat Software); and (d) the BPEL extension for JBoss jBPM, which is licensed under the Common Public License v.1, and, pursuant to the OASIS BPEL4WS standard, requires parties wishing to redistribute to enter various royalty-free patent licenses. Each of the foregoing licenses is available at http://www.opensource.org/licenses/index.php. 1. The Software. "Software Packages" refer to the various software modules that are created and made available for distribution by the JBoss.org open source community at http://www.jboss.org. Each of the Software Packages may be comprised of hundreds of software components. The end user license agreement for each component is located in the component's source code. With the exception of certain image files identified in Section 2 below, the license terms for the components permit Client to copy, modify, and redistribute the component, in both source code and binary code forms. This agreement does not limit Client's rights under, or grant Client rights that supersede, the license terms of any particular component. 2. Intellectual Property Rights. The Software Packages are owned by Red Hat and others and are protected under copyright and other laws. Title to the Software Packages and any component, or to any copy, modification, or merged portion shall remain with the aforementioned, subject to the applicable license. The "JBoss" trademark, "Red Hat" trademark, the individual Software Package trademarks, and the "Shadowman" logo are registered trademarks of Red Hat and its affiliates in the U.S. and other countries. This agreement permits Client to distribute unmodified copies of the Software Packages using the Red Hat trademarks that Red Hat has inserted in the Software Packages on the condition that Client follows Red Hat's trademark guidelines for those trademarks located at http://www.redhat.com/about/corporate/trademark/. Client must abide by these trademark guidelines when distributing the Software Packages, regardless of whether the Software Packages have been modified. If Client modifies the Software Packages, then Client must replace all Red Hat trademarks and logos identified at http://www.jboss.com/company/logos, unless a separate agreement with Red Hat is executed or other permission granted. Merely deleting the files containing the Red Hat trademarks may corrupt the Software Packages. 3. Limited Warranty. Except as specifically stated in this Paragraph 3 or a license for a particular component, to the maximum extent permitted under applicable law, the Software Packages and the components are provided and licensed "as is" without warranty of any kind, expressed or implied, including the implied warranties of merchantability, non-infringement or fitness for a particular purpose. Red Hat warrants that the media on which Software Packages may be furnished will be free from defects in materials and manufacture under normal use for a period of 30 days from the date of delivery to Client. Red Hat does not warrant that the functions contained in the Software Packages will meet Client's requirements or that the operation of the Software Packages will be entirely error free or appear precisely as described in the accompanying documentation. This warranty extends only to the party that purchases the Services pertaining to the Software Packages from Red Hat or a Red Hat authorized distributor. 4. Limitation of Remedies and Liability. To the maximum extent permitted by applicable law, the remedies described below are accepted by Client as its only remedies. Red Hat's entire liability, and Client's exclusive remedies, shall be: If the Software media is defective, Client may return it within 30 days of delivery along with a copy of Client's payment receipt and Red Hat, at its option, will replace it or refund the money paid by Client for the Software. To the maximum extent permitted by applicable law, Red Hat or any Red Hat authorized dealer will not be liable to Client for any incidental or consequential damages, including lost profits or lost savings arising out of the use or inability to use the Software, even if Red Hat or such dealer has been advised of the possibility of such damages. In no event shall Red Hat's liability under this agreement exceed the amount that Client paid to Red Hat under this Agreement during the twelve months preceding the action. 5. Export Control. As required by U.S. law, Client represents and warrants that it: (a) understands that the Software Packages are subject to export controls under the U.S. Commerce Department's Export Administration Regulations ("EAR"); (b) is not located in a prohibited destination country under the EAR or U.S. sanctions regulations (currently Cuba, Iran, Iraq, Libya, North Korea, Sudan and Syria); (c) will not export, re-export, or transfer the Software Packages to any prohibited destination, entity, or individual without the necessary export license(s) or authorizations(s) from the U.S. Government; (d) will not use or transfer the Software Packages for use in any sensitive nuclear, chemical or biological weapons, or missile technology end-uses unless authorized by the U.S. Government by regulation or specific license; (e) understands and agrees that if it is in the United States and exports or transfers the Software Packages to eligible end users, it will, as required by EAR Section 740.17(e), submit semi-annual reports to the Commerce Department's Bureau of Industry & Security (BIS), which include the name and address (including country) of each transferee; and (f) understands that countries other than the United States may restrict the import, use, or export of encryption products and that it shall be solely responsible for compliance with any such import, use, or export restrictions. 6. Third Party Programs. Red Hat may distribute third party software programs with the Software Packages that are not part of the Software Packages and which Client must install separately. These third party programs are subject to their own license terms. The license terms either accompany the programs or can be viewed at http://www.redhat.com/licenses/. If Client does not agree to abide by the applicable license terms for such programs, then Client may not install them. If Client wishes to install the programs on more than one system or transfer the programs to another party, then Client must contact the licensor of the programs. 7. General. If any provision of this agreement is held to be unenforceable, that shall not affect the enforceability of the remaining provisions. This License Agreement shall be governed by the laws of the State of North Carolina and of the United States, without regard to any conflict of laws provisions, except that the United Nations Convention on the International Sale of Goods shall not apply. Copyright 2006 Red Hat, Inc. All rights reserved. "JBoss" and the JBoss logo are registered trademarks of Red Hat, Inc. All other trademarks are the property of their respective owners. Page 1 of 1 18 October 2006 libjboss-aop-java-2.0.1.GA.orig/src/asintegration-jmx/etc/default.mf0000644000175000017500000000061711145122070025152 0ustar twernertwernerManifest-Version: 1.0 Created-By: @java.vm.version@ (@java.vm.vendor@) Specification-Title: @aop.title@ Specification-Version: @aop.version@ Specification-Vendor: @specification.vendor@ Implementation-Title: @aop.title@ Implementation-URL: @implementation.url@ Implementation-Version: @aop.version@ Implementation-Vendor: @implementation.vendor@ Implementation-Vendor-Id: @implementation.vendor.id@ libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/0000755000175000017500000000000011145122070022555 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/0000755000175000017500000000000011145122070023501 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/0000755000175000017500000000000011145122070024270 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/0000755000175000017500000000000011145122070025410 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/0000755000175000017500000000000011145122070026167 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/domain/0000755000175000017500000000000011145122070027436 5ustar twernertwerner././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/domain/ScopedClassLoaderDomain.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/domain/ScopedClassLoaderDo0000644000175000017500000001004511145122070033176 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.domain; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import org.jboss.aop.AspectManager; import org.jboss.aop.Domain; import org.jboss.aop.InterceptionMarkers; import org.jboss.aop.advice.AspectDefinition; /** * A domain that is used for scoped classloaders * * @author Kabir Khan * @author adrian@jboss.org * @version $Revision: 1.1 $ */ public abstract class ScopedClassLoaderDomain extends Domain { private WeakReference loader; protected boolean parentDelegation; protected ConcurrentHashMap myPerVMAspects = new ConcurrentHashMap(); protected ConcurrentHashMap notMyPerVMAspects = new ConcurrentHashMap(); protected InterceptionMarkers interceptionMarkers = new InterceptionMarkers(); protected String classLoaderString; public ScopedClassLoaderDomain(ClassLoader loader, String name, boolean parentDelegation, AspectManager manager, boolean parentFirst) { super(manager, name, parentFirst); if (loader == null) throw new IllegalArgumentException("Null classloader"); this.loader = new WeakReference(loader); this.parentDelegation = parentDelegation; classLoaderString = loader.toString(); super.inheritsBindings = true; super.inheritsDeclarations = true; } protected ClassLoader getClassLoader() { ClassLoader cl = loader.get(); if (cl != null) { return cl; } return null; } // FIXME: JBAOP-107 REMOVE THIS HACK @Override public abstract boolean isValid(); @Override public void removeAspectDefinition(String name) { AspectDefinition def = super.internalRemoveAspectDefintion(name); if (def != null) { myPerVMAspects.remove(name); } } @Override public Object getPerVMAspect(AspectDefinition def) { return getPerVMAspect(def.getName()); } // These are indexed by classloader now, so no need to manage them explicitly here // @Override // public InterceptionMarkers getInterceptionMarkers(ClassLoader loader) // { // return interceptionMarkers; // } @Override public Object getPerVMAspect(String def) { if (parentDelegation == true) { //We will alway be loading up the correct class Object aspect = super.getPerVMAspect(def); return aspect; } else { return getPerVmAspectWithNoParentDelegation(def); } } @Override protected Object createPerVmAspect(String def, AspectDefinition adef, ClassLoader scopedClassLoader) { return super.createPerVmAspect(def, adef, getClassLoader()); } protected Object getSuperPerVmAspect(String def) { return super.getPerVMAspect(def); } protected abstract Object getPerVmAspectWithNoParentDelegation(String def); } libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/0000755000175000017500000000000011145122070030166 5ustar twernertwerner././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/AbstractJBossClassPoolFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/AbstractJBossCla0000644000175000017500000000411311145122070033234 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import org.jboss.logging.Logger; import javassist.ClassPool; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolRepository; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public abstract class AbstractJBossClassPoolFactory { protected final Logger log = Logger.getLogger(this.getClass().getName()); protected ClassPool getCreateParentClassPools(final ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { //Make sure that we get classpools for all the parent classloaders if (cl == null) { return ClassPool.getDefault(); } ClassLoader parent = SecurityActions.getParent(cl); if (parent != null) { return repository.registerClassLoader(parent); } return src; } public ScopedClassPool create(ClassPool src, ScopedClassPoolRepository repository) { return new TempJBossClassPool(src, repository); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/URLClassLoaderIsLocalResourcePlugin.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/URLClassLoaderIs0000644000175000017500000000443511145122070033172 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.net.URL; import java.net.URLClassLoader; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class URLClassLoaderIsLocalResourcePlugin extends AbstractIsLocalResourcePlugin { String[] urls; public URLClassLoaderIsLocalResourcePlugin(DelegatingClassPool pool) { // FIXME URLClassLoaderParentResourcePlugin constructor super(pool); } public boolean isMyResource(String resourceName) { URL url = getPool().getClassLoader().getResource(resourceName); if (url != null) { String urlString = url.toString(); for (String s : urls) { if (urlString.contains(s)) { return true; } } } return false; } @Override protected void initialise() { ClassLoader loader = getPool().getClassLoader(); if (loader instanceof URLClassLoader == false) { throw new IllegalStateException("Not a URLClassLoader " + loader); } URL[] loaderUrls = ((URLClassLoader)loader).getURLs(); urls = new String[loaderUrls.length]; for (int i = 0 ; i < loaderUrls.length ; i++) { urls[i] = loaderUrls[i].toString(); } } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/AbstractIsLocalResourcePlugin.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/AbstractIsLocalR0000644000175000017500000000276011145122070033252 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public abstract class AbstractIsLocalResourcePlugin implements IsLocalResourcePlugin { private final DelegatingClassPool pool; public AbstractIsLocalResourcePlugin(DelegatingClassPool pool) { this.pool = pool; initialise(); } protected abstract void initialise(); protected DelegatingClassPool getPool() { return pool; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/SecurityActions.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/SecurityActions.0000644000175000017500000000504511145122070033323 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ class SecurityActions { interface GetParentAction { ClassLoader getParent(ClassLoader loader); GetParentAction NON_PRIVILEGED = new GetParentAction() { public ClassLoader getParent(ClassLoader loader) { return loader.getParent(); } }; GetParentAction PRIVILEGED = new GetParentAction() { public ClassLoader getParent(final ClassLoader loader) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public ClassLoader run() throws Exception { return loader.getParent(); } }); } catch (PrivilegedActionException e) { throw new RuntimeException(e.getException()); } } }; } public static ClassLoader getParent(ClassLoader loader) { if (System.getSecurityManager() == null) { return GetParentAction.NON_PRIVILEGED.getParent(loader); } else { return GetParentAction.PRIVILEGED.getParent(loader); } } } ././@LongLink0000000000000000000000000000020400000000000011561 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/URLClassLoaderIsLocalResourcePluginFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/URLClassLoaderIs0000644000175000017500000000254711145122070033174 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class URLClassLoaderIsLocalResourcePluginFactory implements IsLocalResourcePluginFactory { public IsLocalResourcePlugin create(DelegatingClassPool pool) { return new URLClassLoaderIsLocalResourcePlugin(pool); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/TempJBossClassPool.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/TempJBossClassPo0000644000175000017500000000437411145122070033254 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import org.jboss.aop.classpool.AOPClassPool; import javassist.ClassPool; import javassist.CtClass; import javassist.scopedpool.ScopedClassPoolRepository; /** * The temporary classpool used by the instrumentor. It's main job is to delegate to the parent classpool * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class TempJBossClassPool extends AOPClassPool { boolean isParentPoolAOP; public TempJBossClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { super(cl, src, repository); if (src instanceof AOPClassPool) { isParentPoolAOP = true; } } public TempJBossClassPool(ClassPool src, ScopedClassPoolRepository repository) { super(src, repository); if (src instanceof AOPClassPool) { isParentPoolAOP = true; } } public CtClass getCached(String classname) { CtClass clazz = null; if (isParentPoolAOP) { clazz = ((AOPClassPool)parent).getCached(classname); } if (clazz == null) { clazz = super.getCached(classname); } return clazz; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DelegatingClassPool.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DelegatingClassP0000644000175000017500000001504211145122070033264 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.net.URL; import javassist.CtClass; import javassist.NotFoundException; import javassist.scopedpool.ScopedClassPoolRepository; import org.jboss.logging.Logger; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class DelegatingClassPool extends AOPClassPool //TODO It would be great not to have this redundant code { private final static Logger logger = Logger.getLogger(DelegatingClassPool.class); private final ClassPoolDomain domain; private boolean isTemp; private boolean closed; private IsLocalResourcePlugin isLocalResourcePlugin; public DelegatingClassPool(ClassPoolDomain domain, ClassLoader cl, ScopedClassPoolRepository repository, boolean isTemp) { super(cl, null, repository); this.domain = domain; domain.addClassPool(this); isLocalResourcePlugin = IsLocalResourcePluginFactoryRegistry.getPluginFactory(cl).create(this); } protected DelegatingClassPool(ClassPoolDomain domain, ClassLoader cl, ScopedClassPoolRepository repository) { super(cl, null, repository); this.domain = domain; domain.addClassPool(this); isLocalResourcePlugin = IsLocalResourcePluginFactoryRegistry.getPluginFactory(cl).create(this); } public CtClass get(String classname) throws NotFoundException { System.out.println("==> Initiating lookup of " + classname + " in " + this); if (logger.isTraceEnabled()) { logger.trace("Initiating lookup of " + classname + " in " + this); } return super.get(classname); } /** * Overrides ClassPool.get0() so that we can look up classes without caching them in the initiating pool. * The DelgatingClassPool + DomainClassPool handle the caching in the correct pool + handles the * parentFirst functionality */ @Override protected synchronized CtClass get0(String classname, boolean useCache) throws NotFoundException { CtClass clazz = null; if (useCache) { clazz = getCached(classname); if (clazz != null) { return clazz; } } return createCtClass(classname, useCache); } @Override public boolean isUnloadedClassLoader() { return closed; } @Override public void close() { closed = true; super.close(); domain.removeClassPool(this); } @Override public CtClass getCached(String classname) { return getCached(true, classname); } CtClass getCached(boolean isInitiatingPool, String classname) { if (isInitiatingPool && domain.isParentFirst()) { CtClass clazz = domain.getCached(this, classname); if (clazz != null) { return clazz; } } CtClass clazz = getCachedLocally(classname); if (clazz != null) { System.out.println("==> Found cached class " + classname + " in " + this); if (logger.isTraceEnabled()) { logger.trace("Found cached class " + classname + " in " + this); } return clazz; } if (clazz == null) { boolean isLocal = false; ClassLoader cl = getClassLoader0(); if (cl != null) { isLocal = isLocalResource(classname); } if (!isLocal) { Object o = generatedClasses.get(classname); if (o == null && isInitiatingPool) { return domain.getCached(this, classname); } } } // *NOTE* NEED TO TEST WHEN SUPERCLASS IS IN ANOTHER UCL!!!!!! return null; } @Override protected CtClass createCtClass(String classname, boolean useCache) { return createCtClass(true, classname, useCache); } CtClass createCtClass(boolean isInitiatingPool, String classname, boolean useCache) { CtClass clazz = null; if (isLocalResource(classname)) { URL classUrl = find(classname); boolean create = true; if (domain.isParentFirst()) { if (domain.findParentResource(classname) != null) { create = false; } } if (create) { clazz = super.createCtClass(classname, useCache); if (clazz != null && useCache) { if (useCache) { System.out.println("==> Caching class " + classname + " in " + this); if (logger.isTraceEnabled()) { logger.trace("Caching class " + classname + " in " + this); } cacheCtClass(clazz.getName(), clazz, false); } } } } if (clazz == null && isInitiatingPool) { return domain.createCtClass(this, classname, useCache); } return clazz; } //Lifted from AOPClassPool, also exists in JBossClassPool @Override protected boolean isLocalResource(String resourceName) { return super.isLocalResource(resourceName); } @Override public boolean isLocalClassLoaderResource(String classResourceName) { return isLocalResourcePlugin.isMyResource(classResourceName); } public boolean isLocalClassLoaderClass(String classname) { return isLocalResourcePlugin.isMyResource(getResourceName(classname)); } @Override public String toString() { return super.toString() + " domain: " + domain; } } ././@LongLink0000000000000000000000000000020100000000000011556 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DefaultClassLoaderIsLocalResourcePlugin.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DefaultClassLoad0000644000175000017500000000304511145122070033265 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class DefaultClassLoaderIsLocalResourcePlugin extends AbstractIsLocalResourcePlugin implements IsLocalResourcePlugin { public DefaultClassLoaderIsLocalResourcePlugin(DelegatingClassPool pool) { super(pool); } @Override protected void initialise() { } public boolean isMyResource(String resourceName) { return getPool().getClassLoader().getResource(resourceName) != null; } } ././@LongLink0000000000000000000000000000021000000000000011556 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DefaultClassLoaderIsLocalResourcePluginFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DefaultClassLoad0000644000175000017500000000255711145122070033274 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class DefaultClassLoaderIsLocalResourcePluginFactory implements IsLocalResourcePluginFactory { public IsLocalResourcePlugin create(DelegatingClassPool pool) { return new DefaultClassLoaderIsLocalResourcePlugin(pool); } } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/TranslatableClassLoaderIsLocalResourcePlugin.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/TranslatableClas0000644000175000017500000000356611145122070033342 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import org.jboss.util.loading.Translatable; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class TranslatableClassLoaderIsLocalResourcePlugin extends AbstractIsLocalResourcePlugin { public TranslatableClassLoaderIsLocalResourcePlugin(DelegatingClassPool pool) { // FIXME TranslatableClassLoaderParentResourcePlugin constructor super(pool); } @Override protected void initialise() { } public boolean isMyResource(String resourceName) { ClassLoader loader = getPool().getClassLoader(); if (loader instanceof Translatable == false) { throw new IllegalStateException("ClassLoader is not instance of Translatable " + loader); } return ((Translatable)getPool().getClassLoader()).getResourceLocally(resourceName) != null; } } ././@LongLink0000000000000000000000000000021500000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/TranslatableClassLoaderIsLocalResourcePluginFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/TranslatableClas0000644000175000017500000000257011145122070033334 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class TranslatableClassLoaderIsLocalResourcePluginFactory implements IsLocalResourcePluginFactory { public IsLocalResourcePlugin create(DelegatingClassPool pool) { return new TranslatableClassLoaderIsLocalResourcePlugin(pool); } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/ExtraClassPoolFactoryParameters.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/ExtraClassPoolFa0000644000175000017500000000360411145122070033266 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.util.Map; /** * This class is used by the AS5 integration. Do not delete!!!! * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ExtraClassPoolFactoryParameters { /** A map of properties that can be used to configure the classpool factories further */ private static ThreadLocal> properties = new ThreadLocal>(); public static void pushThreadProperties(Map props) { properties.set(props); } public static Map peekThreadProperties() { return properties.get(); } public static Map popThreadProperties() { Map props = properties.get(); properties.remove(); return props; } } ././@LongLink0000000000000000000000000000017600000000000011571 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/IsLocalResourcePluginFactoryRegistry.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/IsLocalResourceP0000644000175000017500000000620011145122070033265 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.net.URLClassLoader; import java.util.Map; import java.util.WeakHashMap; import org.jboss.util.loading.Translatable; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class IsLocalResourcePluginFactoryRegistry { private static Map, IsLocalResourcePluginFactory> plugins = new WeakHashMap, IsLocalResourcePluginFactory>(); static { addPluginFactory(ClassLoader.class, new DefaultClassLoaderIsLocalResourcePluginFactory()); addPluginFactory(URLClassLoader.class, new URLClassLoaderIsLocalResourcePluginFactory()); addPluginFactory(Translatable.class, new TranslatableClassLoaderIsLocalResourcePluginFactory()); } public static synchronized void addPluginFactory(Class classLoaderClass, IsLocalResourcePluginFactory plugin) { plugins.put(classLoaderClass, plugin); } public static synchronized void removePluginFactory(Class classLoaderClass, IsLocalResourcePluginFactory plugin) { plugins.remove(classLoaderClass); } public static synchronized IsLocalResourcePluginFactory getPluginFactory(ClassLoader classLoader) { if (classLoader != null) { return getPluginFactory(classLoader.getClass()); } return getPluginFactory(ClassLoader.class); } public static synchronized IsLocalResourcePluginFactory getPluginFactory(Class classLoaderClass) { IsLocalResourcePluginFactory plugin = plugins.get(classLoaderClass); if (plugin == null) { Class[] interfaces = classLoaderClass.getInterfaces(); if (interfaces.length > 0) { for (Class iface : interfaces) { plugin = getPluginFactory(iface); if (plugin != null) { return plugin; } } } Class superClass = classLoaderClass.getSuperclass(); if (superClass != null && superClass != Object.class) { return getPluginFactory(superClass); } } return plugin; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/ClassPoolDomain.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/ClassPoolDomain.0000644000175000017500000001555511145122070033231 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.net.URL; import java.util.ArrayList; import java.util.List; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import org.jboss.aop.AspectManager; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ClassPoolDomain { private String domainName; private ClassPoolDomain parent; private List delegatingPools = new ArrayList(); private ClassPoolDomainStrategy classPoolDomainStrategy; private boolean parentFirst; public ClassPoolDomain(String domainName, ClassPoolDomain parent) { this.parent = parent; this.domainName = domainName; if (parent == null) { classPoolDomainStrategy = new RootClassPoolDomainImpl(); } else { classPoolDomainStrategy = new ChildClassPoolDomainImpl(); } } public String getDomainName() { return domainName; } public boolean isParentFirst() { return parentFirst; } public void setParentFirst(boolean parentFirst) { this.parentFirst = parentFirst; } synchronized void addClassPool(DelegatingClassPool pool) { if (!delegatingPools.contains(pool)) { delegatingPools.add(pool); } } synchronized void removeClassPool(DelegatingClassPool pool) { delegatingPools.remove(pool); } synchronized CtClass getCached(DelegatingClassPool initiating, String classname) { if (parentFirst) { CtClass clazz = classPoolDomainStrategy.getParentCached(classname); if (clazz != null) { return clazz; } } for(DelegatingClassPool pool : delegatingPools) { if (pool == initiating) { continue; } if (pool.isUnloadedClassLoader()) { AspectManager.instance().unregisterClassLoader(pool.getClassLoader()); continue; } CtClass clazz = pool.getCached(false, classname); if (clazz != null) { return clazz; } } if (!parentFirst) { return classPoolDomainStrategy.getParentCached(classname); } return null; } synchronized CtClass createCtClass(DelegatingClassPool initiating, String classname, boolean useCache) { if (parentFirst) { CtClass clazz = createParentCtClass(classname, useCache); if (clazz != null) { return clazz; } } for(DelegatingClassPool pool : delegatingPools) { if (pool == initiating) { continue; } if (pool.isUnloadedClassLoader()) { AspectManager.instance().unregisterClassLoader(pool.getClassLoader()); continue; } CtClass clazz = pool.createCtClass(false, classname, useCache); if (clazz != null) { return clazz; } } if (!parentFirst) { return createParentCtClass(classname, useCache); } return null; } synchronized CtClass createParentCtClass(String classname, boolean useCache) { return classPoolDomainStrategy.createParentCtClass(classname, useCache); } synchronized URL findParentResource(String classname) { return classPoolDomainStrategy.findParentResource(classname); } synchronized URL findResource(String classname) { if (parentFirst) { URL url = classPoolDomainStrategy.findParentResource(classname); if (url != null) { return url; } } for (DelegatingClassPool pool : delegatingPools) { if (pool.isUnloadedClassLoader()) { AspectManager.instance().unregisterClassLoader(pool.getClassLoader()); continue; } if (pool.isLocalClassLoaderClass(classname)) { URL url = pool.find(classname); if (url != null) { return url; } } } if (!parentFirst) { return classPoolDomainStrategy.findParentResource(classname); } return null; } public String toString() { return super.toString() + "[" + domainName + "]"; } private interface ClassPoolDomainStrategy { URL findParentResource(String classname); CtClass createParentCtClass(String classname, boolean useCache); CtClass getParentCached(String classname); } private class RootClassPoolDomainImpl implements ClassPoolDomainStrategy { ClassPool defaultPool = ClassPool.getDefault(); public URL findParentResource(String classname) { return defaultPool.find(classname); } public CtClass createParentCtClass(String classname, boolean useCache) { try { return defaultPool.get(classname); } catch(NotFoundException ignore) { } return null; } public CtClass getParentCached(String classname) { try { return defaultPool.get(classname); } catch (NotFoundException ignore) { } return null; } } private class ChildClassPoolDomainImpl implements ClassPoolDomainStrategy { public URL findParentResource(String classname) { return parent.findResource(classname); } public CtClass createParentCtClass(String classname, boolean useCache) { return parent.createCtClass(null, classname, useCache); } public CtClass getParentCached(String classname) { return parent.getCached(null, classname); } } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DomainClassPoolRules.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/DomainClassPoolR0000644000175000017500000000255311145122070033267 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class DomainClassPoolRules { private boolean parentFirst; public boolean isParentFirst() { return parentFirst; } public void setParentFirst(boolean parentFirst) { this.parentFirst = parentFirst; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/IsLocalResourcePluginFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/IsLocalResourceP0000644000175000017500000000234711145122070033275 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public interface IsLocalResourcePluginFactory { IsLocalResourcePlugin create(DelegatingClassPool pool); } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/IsLocalResourcePlugin.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/classpool/IsLocalResourceP0000644000175000017500000000232311145122070033267 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public interface IsLocalResourcePlugin { boolean isMyResource(String resourceName); } libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/0000755000175000017500000000000011145122070031036 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/core/0000755000175000017500000000000011145122070031766 5ustar twernertwerner././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/core/AspectManagerServiceDelegate.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/core/AspectM0000644000175000017500000005237711145122070033263 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.core; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javassist.ClassPool; import javassist.scopedpool.ScopedClassPoolFactory; import javax.xml.parsers.ParserConfigurationException; import org.jboss.aop.AspectManager; import org.jboss.aop.AspectXmlLoader; import org.jboss.aop.ClassLoaderValidation; import org.jboss.aop.ClassicWeavingStrategy; import org.jboss.aop.Deployment; import org.jboss.aop.SuperClassesFirstWeavingStrategy; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.AdviceStack; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.InterceptorFactory; import org.jboss.aop.annotation.PortableAnnotationElement; import org.jboss.aop.asintegration.JBossIntegration; import org.jboss.aop.hook.JDK14Transformer; import org.jboss.aop.hook.JDK14TransformerManager; import org.jboss.aop.instrument.InstrumentorFactory; import org.jboss.aop.instrument.TransformerCommon; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.pointcut.Pointcut; import org.jboss.logging.Logger; import org.jboss.system.server.ServerConfig; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public abstract class AspectManagerServiceDelegate { Logger log = Logger.getLogger(AspectManagerServiceDelegate.class); static { //pre-load necessary classes so that we avoid NoClassDefFoundErrors on JRockit when using the RepositoryClassloader hook //When AspectManager.translate() is called the first time, these classes have not been loaded yet, and this is what causes //JRockit to get confused @SuppressWarnings("unused") Class clazz = TransformerCommon.class; clazz = SuperClassesFirstWeavingStrategy.class; clazz = ClassicWeavingStrategy.class; } // Attributes --------------------------------------------------- // boolean created = false; protected File tmpClassesDir; /** True if the deprecated translator is enabled */ protected boolean enableTransformer = false; /** True if the noveau translator is enabled */ protected boolean enableLoadtimeWeaving = false; protected boolean suppressTransformationErrors = true; protected boolean suppressReferenceErrors = true; protected String exclude; protected String include; protected String ignore; protected String includedInvisibleAnnotations; /** * A string containing xml to be deployed first thing when this service is created */ private String bootstrapXml; /** * The name of the file used to deploy the core aspects */ private String baseXml; /** Whether we found and deployed baseXml */ private boolean deployedBaseXml; /** Whether we should deploy baseXml or not */ private boolean useBaseXml; /** When running with JBoss 5 registration with MBeanServer happens after the service has been started */ boolean registerHappensAfterStart; /** The encapsulation of the integration */ private JBossIntegration integration; /** Whether this service was started */ private boolean started; /** The AspectManager managed by this service */ private AspectManager manager; // Static ------------------------------------------------------- // Constructors ------------------------------------------------- public AspectManagerServiceDelegate() { } public void setBootstrapXml(String bootstrapXml) { this.bootstrapXml = bootstrapXml; } public void setBaseXml(String baseXml) { this.baseXml = baseXml; } public void setRegisterHappensAfterStart(boolean registerHappensAfterStart) { this.registerHappensAfterStart = registerHappensAfterStart; } /** * This needs setting to true in AS 4 */ public void setAspectManagerMaintainAdvisorInterceptors(boolean maintain) { AspectManager.maintainAdvisorMethodInterceptors = maintain; } public void setAspectManager(AspectManager manager) { this.manager = manager; } public AspectManager getAspectManager() { return manager; } // Public ------------------------------------------------------- /** * Get the integration * * @return the integration */ public JBossIntegration getJBossIntegration() { return integration; } /** * Set the integration * * @param integration the integration */ public void setJBossIntegration(JBossIntegration integration) { this.integration = integration; } public ScopedClassPoolFactory createFactory() throws Exception { return initIntegration().createScopedClassPoolFactory(tmpClassesDir); } public ClassLoaderValidation createClassLoaderValidation() { return initIntegration(); } /** * Initialize the integration if not alreday done so * * @return the integration */ protected JBossIntegration initIntegration() { if (integration == null) { throw new IllegalStateException("Integration was not set"); } return integration; } public void create() throws Exception { initIntegration(); if (started) { return; } PortableAnnotationElement.setClosingDownManager(false); // Set a default tmp classes dir to the jboss tmp dir/aopclasses if (tmpClassesDir == null) { String jbossTmpDir = System.getProperty(ServerConfig.SERVER_TEMP_DIR); if (jbossTmpDir == null) jbossTmpDir = System.getProperty("java.io.tmpdir"); tmpClassesDir = new File(jbossTmpDir, "aopdynclasses"); } // Validate the the tmp dir exists if (tmpClassesDir.exists() == false && tmpClassesDir.mkdirs() == false) throw new FileNotFoundException("Failed to create tmpClassesDir: " + tmpClassesDir.getAbsolutePath()); AspectManager.setClassPoolFactory(createFactory()); AspectManager.classLoaderValidator = createClassLoaderValidation(); // Add the tmp classes dir to our UCL classpath Deployment.searchClasspath = false; // turn off dynamic finding of DDs AspectManager.suppressTransformationErrors = suppressTransformationErrors; if (enableTransformer && enableLoadtimeWeaving) throw new RuntimeException("Cannot set both EnableTransformer and EnableLoadtimeWeaving"); if (enableTransformer) { attachDeprecatedTranslator(); } if (enableLoadtimeWeaving) { attachTranslator(); } AspectManager.setClassLoaderScopingPolicy(integration.createAOPClassLoaderScopingPolicy()); deployBootstrapXml(); deployBaseXml(); } public void start() throws Exception { started = true; } public void stop() { started = false; } public void destroy() { try { PortableAnnotationElement.setClosingDownManager(true); undeployBaseXml(); } catch(Exception e) { log.error("Problem destroying AspectManager", e); } try { undeployBootstrapXml(); } catch (Exception e) { log.error("Problem destroying AspectManager", e); } } public void deployBaseXml() { if (!deployedBaseXml && useBaseXml) { URL base = baseXmlUrl(); try { if (base != null) { log.debug("Deploying base aspects " + base); AspectXmlLoader.deployXML(base, null, manager); deployedBaseXml = true; } } catch (Exception e) { throw new RuntimeException("Error loading " + baseXml + " file" + e); } } } public void undeployBaseXml() { if (deployedBaseXml) { URL base = baseXmlUrl(); try { if (base != null) { log.debug("Undeploying base aspects " + base); AspectXmlLoader.undeployXML(base, manager); } } catch (Exception e) { log.warn("Error loading " + baseXml + " file" + e); } deployedBaseXml = false; } } private URL baseXmlUrl() { if (baseXml == null || baseXml.trim().length() == 0) { return null; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL base = cl.getResource(baseXml); if (base == null) { log.debug("Could not find " + baseXml + " file in the resources of " + cl); } return base; } private void deployBootstrapXml() { try { Document doc = bootstrapXmlDocument(); if (doc != null) { AspectXmlLoader loader = new AspectXmlLoader(); loader.setManager(manager); loader.deployXML(doc, null); } } catch(Exception e) { throw new RuntimeException("Error deploying bootstrap xml", e); } } private void undeployBootstrapXml() { try { Document doc = bootstrapXmlDocument(); if (doc != null) { AspectXmlLoader loader = new AspectXmlLoader(); loader.setManager(manager); loader.undeployXML(doc, null); } } catch(Exception e) { log.warn("Error undeploying bootstrap xml", e); } } private Document bootstrapXmlDocument() throws IOException, SAXException, ParserConfigurationException { if (bootstrapXml != null && bootstrapXml.trim().length() > 0) { InputStream in = new BufferedInputStream(new ByteArrayInputStream(bootstrapXml.getBytes())); try { Document doc = AspectXmlLoader.loadDocument(new BufferedInputStream(in)); return doc; } finally { if (in != null) { in.close(); } } } return null; } protected void attachDeprecatedTranslator() { log.warn("EnableTransformer has been deprecated, please use EnableLoadtimeWeaving. See docs for more details"); initIntegration().attachDeprecatedTranslator(); } protected void detachDeprecatedTranslator() { initIntegration().detachDeprecatedTranslator(); } /* * Despite its name, this is also used for the JRockit transformer */ protected void attachTranslator() { //Despite its name, this is also used for the JRockit transformer JDK14TransformerManager.transformer = new JDK14Transformer() { public byte[] transform(ClassLoader loader, String classname, byte[] classBytes) { try { //Make sure that we use the correct classloader, in order to get the correct domain if it is a scoped loader return AspectManager.instance(loader).translate(classname, loader, classBytes); } catch (Exception e) { throw new RuntimeException("Error converting " + classname + " on " + loader, e); } } }; } protected void detachTranslator() { JDK14TransformerManager.transformer = null; } public boolean getPrune() { return AspectManager.getPrune(); } public void setPrune(boolean prune) { AspectManager.setPrune(prune); } public String getExclude() { return exclude; } public void setExclude(String exclude) { this.exclude = exclude; ArrayList list = new ArrayList(); if (exclude != null) { StringTokenizer tokenizer = new StringTokenizer(exclude, ","); while (tokenizer.hasMoreTokens()) { list.add(tokenizer.nextToken().trim()); } } manager.setExclude(list); } public String getInclude() { return include; } public void setInclude(String include) { this.include = include; ArrayList list = new ArrayList(); if (include != null) { StringTokenizer tokenizer = new StringTokenizer(include, ","); while (tokenizer.hasMoreTokens()) { list.add(tokenizer.nextToken().trim()); } } manager.setInclude(list); } public String getIgnore() { return ignore; } public void setIgnore(String ignore) { this.ignore = ignore; ArrayList list = new ArrayList(); if (ignore != null) { StringTokenizer tokenizer = new StringTokenizer(ignore, ","); while (tokenizer.hasMoreTokens()) { list.add(tokenizer.nextToken().trim()); } } manager.setIgnore(list); } public String getIncludedInvisibleAnnotations() { return includedInvisibleAnnotations; } public void setIncludedInvisibleAnnotations(String ia) { List iiaList = new ArrayList(); if(ia != null) { for(String inc : ia.split(",")) iiaList.add(inc.trim()); } manager.setIncludedInvisibleAnnotations(iiaList); } /** * The temporary directory to which dyn class files are written */ public File getTmpClassesDir() { return tmpClassesDir; } /** * The temporary directory to which dyn class files are written */ public void setTmpClassesDir(File tmpClassesDir) { this.tmpClassesDir = tmpClassesDir; } /** * Set the verbosity of aop logging. It doesn't use log4j */ public boolean getVerbose() { return AspectManager.verbose; } /** * Set the verbosity of aop logging. It doesn't use log4j */ public void setVerbose(boolean verbose) { AspectManager.verbose = verbose; } /** * Use aop optimizations. Optional just in case there is a bug */ public boolean getOptimized() { return AspectManager.optimize; } /** * Use aop optimizations. Optional just in case there is a bug */ public void setOptimized(boolean verbose) { AspectManager.optimize = verbose; } /** * Gets whether the base aspects are being deployed */ public boolean getUseBaseXml() { return useBaseXml; } /** * Set whether the base aspects should be deployed. If called against * a running server, will deploy/undeploy the base aspects depending on the * value of the parameter */ public synchronized void setUseBaseXml(boolean useBaseXml) { if (useBaseXml != this.useBaseXml) { this.useBaseXml = useBaseXml; if (started) { if (useBaseXml) { deployBaseXml(); } else { undeployBaseXml(); } } } } public boolean getSuppressTransformationErrors() { return suppressTransformationErrors; } public void setSuppressTransformationErrors(boolean suppressTransformationErrors) { this.suppressTransformationErrors = suppressTransformationErrors; AspectManager.suppressTransformationErrors = suppressTransformationErrors; } public boolean getSuppressReferenceErrors() { return suppressReferenceErrors; } public void setSuppressReferenceErrors(boolean suppressReferenceErrors) { this.suppressReferenceErrors = suppressReferenceErrors; AspectManager.suppressReferenceErrors = suppressReferenceErrors; } /** * The temporary directory to which dyn class files are written */ public boolean getEnableTransformer() { return enableTransformer; } /** * The temporary directory to which dyn class files are written */ public String interceptorFactories() { Map factories = manager.getInterceptorFactories(); StringBuffer buffer = new StringBuffer(""); for (String name : factories.keySet()) { buffer.append(name + "
"); } return buffer.toString(); } /** * The temporary directory to which dyn class files are written */ public String aspectDefinitions() { Map factories = manager.getAspectDefinitions(); StringBuffer buffer = new StringBuffer(""); for (String name : factories.keySet()) { buffer.append(name + "
"); } return buffer.toString(); } public String introductions() { Map factories = manager.getInterfaceIntroductions(); StringBuffer buffer = new StringBuffer(""); for (String name : factories.keySet()) { buffer.append(name + "
"); } return buffer.toString(); } public String stacks() { Map factories = manager.getInterceptorStacks(); StringBuffer buffer = new StringBuffer(""); for (String name : factories.keySet()) { buffer.append(name + "
"); } return buffer.toString(); } public String bindings() { Map factories = manager.getBindings(); StringBuffer buffer = new StringBuffer(""); for (String name : factories.keySet()) { AdviceBinding binding = factories.get(name); StringBuilder detail = new StringBuilder(); if (binding != null) { detail.append(binding.getPointcut()); detail.append("{"); InterceptorFactory[] ifactories = binding.getInterceptorFactories(); for (InterceptorFactory ifactory : ifactories) { detail.append(ifactory.getName()); } detail.append("}"); } buffer.append("" + name + " - " + detail.toString() + "
"); } return buffer.toString(); } public String pointcuts() { Map pointcuts = manager.getPointcuts(); StringBuffer buffer = new StringBuffer(""); for (String name : pointcuts.keySet()) { Pointcut pointcut = pointcuts.get(name); buffer.append("" + name + " - " + pointcut + "
"); } return buffer.toString(); } public String registeredClassLoaders() { Map loaders = AspectManager.getRegisteredCLs(); StringBuffer buffer = new StringBuffer(""); for (ClassLoader loader : loaders.keySet()) { buffer.append(loader + "
"); } return buffer.toString(); } public void setEnableTransformer(boolean enableTransformer) { // Testsuite uses enableTransformer, we may be testing new loadtime features though. if (this.enableTransformer == enableTransformer) return; if (enableLoadtimeWeaving && enableTransformer) { log.warn("enabledLoadtimeWeaving alread set"); return; } if (started) { if (enableTransformer) { attachDeprecatedTranslator(); } else { detachDeprecatedTranslator(); } } this.enableTransformer = enableTransformer; } public boolean getEnableLoadtimeWeaving() { return enableLoadtimeWeaving; } public void setEnableLoadtimeWeaving(boolean enableTransformer) { if (this.enableLoadtimeWeaving == enableTransformer) return; if (enableLoadtimeWeaving && enableTransformer) { log.warn("enableTransformer already set"); } if (started) { if (enableTransformer) { attachTranslator(); } else { detachTranslator(); } } this.enableLoadtimeWeaving = enableTransformer; } public String getInstrumentor() { return InstrumentorFactory.getInstrumentorName(); } public void setInstrumentor(String instrumentor) { InstrumentorFactory.initialise(instrumentor); } public Logger getLog() { return log; } } ././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/core/AspectManagerServiceDelegateJDK5.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/core/AspectM0000644000175000017500000000326311145122070033251 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.core; import org.jboss.aop.standalone.AOPTransformer; import org.jboss.aop.standalone.PluggableInstrumentor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class AspectManagerServiceDelegateJDK5 extends AspectManagerServiceDelegate { protected AOPTransformer transformer = new AOPTransformer(); public AspectManagerServiceDelegateJDK5() { } protected void attachTranslator() { PluggableInstrumentor.getInstrumentor().addTransformer(transformer); } protected void detachTranslator() { PluggableInstrumentor.getInstrumentor().removeTransformer(transformer); } } ././@LongLink0000000000000000000000000000020600000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/core/AspectManagerServiceDelegateJRockit.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/core/AspectM0000644000175000017500000000233611145122070033251 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration.core; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class AspectManagerServiceDelegateJRockit extends AspectManagerServiceDelegate { } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/JBossIntegration.javalibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/main/org/jboss/aop/asintegration/JBossIntegra0000644000175000017500000000440011145122070033311 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.asintegration; import java.io.File; import javassist.scopedpool.ScopedClassPoolFactory; import org.jboss.aop.ClassLoaderValidation; import org.jboss.aop.classpool.AOPClassLoaderScopingPolicy; /** * AOPIntegration.

* * This class is intended to identify all the integration * points AOP is making with the JBoss appserver. * * @author Adrian Brock * @version $Revision: 1.1 $ */ public interface JBossIntegration extends ClassLoaderValidation { /** * Create the AOPClassLoaderScopingPolicy * * @return the policy */ AOPClassLoaderScopingPolicy createAOPClassLoaderScopingPolicy(); /** * Create a scoped classpool factory * * TODO JBAOP-107 need to review whether ScopedClassPool should also be replaced with * some other policy, e.g. javassist ClassPath notion is closer to new classloader? * @param tmpDir the temporary directory for classes * @return the factory * @throws Exception for any error */ ScopedClassPoolFactory createScopedClassPoolFactory(File tmpDir) throws Exception; /** * Attach the depreacted translator */ void attachDeprecatedTranslator(); /** * Detach the deprecated translator */ void detachDeprecatedTranslator(); } libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/0000755000175000017500000000000011145122070023330 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/jbossorg-eula.txt0000644000175000017500000001764611145122070026663 0ustar twernertwernerLICENSE AGREEMENT JBOSS(r) This License Agreement governs the use of the Software Packages and any updates to the Software Packages, regardless of the delivery mechanism. Each Software Package is a collective work under U.S. Copyright Law. Subject to the following terms, Red Hat, Inc. ("Red Hat") grants to the user ("Client") a license to the applicable collective work(s) pursuant to the GNU Lesser General Public License v. 2.1 except for the following Software Packages: (a) JBoss Portal Forums and JBoss Transactions JTS, each of which is licensed pursuant to the GNU General Public License v.2; (b) JBoss Rules, which is licensed pursuant to the Apache License v.2.0; (c) an optional download for JBoss Cache for the Berkeley DB for Java database, which is licensed under the (open source) Sleepycat License (if Client does not wish to use the open source version of this database, it may purchase a license from Sleepycat Software); and (d) the BPEL extension for JBoss jBPM, which is licensed under the Common Public License v.1, and, pursuant to the OASIS BPEL4WS standard, requires parties wishing to redistribute to enter various royalty-free patent licenses. Each of the foregoing licenses is available at http://www.opensource.org/licenses/index.php. 1. The Software. "Software Packages" refer to the various software modules that are created and made available for distribution by the JBoss.org open source community at http://www.jboss.org. Each of the Software Packages may be comprised of hundreds of software components. The end user license agreement for each component is located in the component's source code. With the exception of certain image files identified in Section 2 below, the license terms for the components permit Client to copy, modify, and redistribute the component, in both source code and binary code forms. This agreement does not limit Client's rights under, or grant Client rights that supersede, the license terms of any particular component. 2. Intellectual Property Rights. The Software Packages are owned by Red Hat and others and are protected under copyright and other laws. Title to the Software Packages and any component, or to any copy, modification, or merged portion shall remain with the aforementioned, subject to the applicable license. The "JBoss" trademark, "Red Hat" trademark, the individual Software Package trademarks, and the "Shadowman" logo are registered trademarks of Red Hat and its affiliates in the U.S. and other countries. This agreement permits Client to distribute unmodified copies of the Software Packages using the Red Hat trademarks that Red Hat has inserted in the Software Packages on the condition that Client follows Red Hat's trademark guidelines for those trademarks located at http://www.redhat.com/about/corporate/trademark/. Client must abide by these trademark guidelines when distributing the Software Packages, regardless of whether the Software Packages have been modified. If Client modifies the Software Packages, then Client must replace all Red Hat trademarks and logos identified at http://www.jboss.com/company/logos, unless a separate agreement with Red Hat is executed or other permission granted. Merely deleting the files containing the Red Hat trademarks may corrupt the Software Packages. 3. Limited Warranty. Except as specifically stated in this Paragraph 3 or a license for a particular component, to the maximum extent permitted under applicable law, the Software Packages and the components are provided and licensed "as is" without warranty of any kind, expressed or implied, including the implied warranties of merchantability, non-infringement or fitness for a particular purpose. Red Hat warrants that the media on which Software Packages may be furnished will be free from defects in materials and manufacture under normal use for a period of 30 days from the date of delivery to Client. Red Hat does not warrant that the functions contained in the Software Packages will meet Client's requirements or that the operation of the Software Packages will be entirely error free or appear precisely as described in the accompanying documentation. This warranty extends only to the party that purchases the Services pertaining to the Software Packages from Red Hat or a Red Hat authorized distributor. 4. Limitation of Remedies and Liability. To the maximum extent permitted by applicable law, the remedies described below are accepted by Client as its only remedies. Red Hat's entire liability, and Client's exclusive remedies, shall be: If the Software media is defective, Client may return it within 30 days of delivery along with a copy of Client's payment receipt and Red Hat, at its option, will replace it or refund the money paid by Client for the Software. To the maximum extent permitted by applicable law, Red Hat or any Red Hat authorized dealer will not be liable to Client for any incidental or consequential damages, including lost profits or lost savings arising out of the use or inability to use the Software, even if Red Hat or such dealer has been advised of the possibility of such damages. In no event shall Red Hat's liability under this agreement exceed the amount that Client paid to Red Hat under this Agreement during the twelve months preceding the action. 5. Export Control. As required by U.S. law, Client represents and warrants that it: (a) understands that the Software Packages are subject to export controls under the U.S. Commerce Department's Export Administration Regulations ("EAR"); (b) is not located in a prohibited destination country under the EAR or U.S. sanctions regulations (currently Cuba, Iran, Iraq, Libya, North Korea, Sudan and Syria); (c) will not export, re-export, or transfer the Software Packages to any prohibited destination, entity, or individual without the necessary export license(s) or authorizations(s) from the U.S. Government; (d) will not use or transfer the Software Packages for use in any sensitive nuclear, chemical or biological weapons, or missile technology end-uses unless authorized by the U.S. Government by regulation or specific license; (e) understands and agrees that if it is in the United States and exports or transfers the Software Packages to eligible end users, it will, as required by EAR Section 740.17(e), submit semi-annual reports to the Commerce Department's Bureau of Industry & Security (BIS), which include the name and address (including country) of each transferee; and (f) understands that countries other than the United States may restrict the import, use, or export of encryption products and that it shall be solely responsible for compliance with any such import, use, or export restrictions. 6. Third Party Programs. Red Hat may distribute third party software programs with the Software Packages that are not part of the Software Packages and which Client must install separately. These third party programs are subject to their own license terms. The license terms either accompany the programs or can be viewed at http://www.redhat.com/licenses/. If Client does not agree to abide by the applicable license terms for such programs, then Client may not install them. If Client wishes to install the programs on more than one system or transfer the programs to another party, then Client must contact the licensor of the programs. 7. General. If any provision of this agreement is held to be unenforceable, that shall not affect the enforceability of the remaining provisions. This License Agreement shall be governed by the laws of the State of North Carolina and of the United States, without regard to any conflict of laws provisions, except that the United Nations Convention on the International Sale of Goods shall not apply. Copyright 2006 Red Hat, Inc. All rights reserved. "JBoss" and the JBoss logo are registered trademarks of Red Hat, Inc. All other trademarks are the property of their respective owners. Page 1 of 1 18 October 2006 ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/jboss-50-install-jboss-aop-jdk50-build.xmllibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/jboss-50-install-jboss-aop-jdk50-build.xm0000644000175000017500000001323311145122070032611 0ustar twernertwerner Backing up existing lib directory to ${old.lib} Backing up existing aop deployer to ${old.deployer} Backing up existing ${lib.jbossaop-client.injboss} to ${bak.jbossaop-client} libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/ReadMe-AS5.txt0000644000175000017500000000112611145122070025614 0ustar twernertwernerTo upgrade your jboss instance: 1) Copy the contents of the lib folder into the JBoss-5.x/lib/ folder 2) Copy the jboss-aop-jdk50.deployer over the JBoss-5.x/server/xxx/deployers/jboss-aop-jboss5.deployer/ folder 3) Copy the jboss-aop-client.jar (located at ../lib) into the JBoss-5.x/client/ folder. Note that this will not replace the jboss-aspect-library.jar, which is tied to application server version Alternatively, you can use the ant script: 1) Edit jboss.properties file, setting the root of the jboss installation and the server configuration you wish to patch. 2) Run the command: $ ant ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/jboss-40-install-jboss-aop-jdk50-build.xmllibjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/jboss-40-install-jboss-aop-jdk50-build.xm0000644000175000017500000004427611145122070032623 0ustar twernertwerner JBoss AS Version is '${AS-Specification-Version}' The server ${jboss.home} lacks a jboss-aspect-library.jdk50.jar library. Downloading jar... Backing up existing jbossall-client.jar to ${bak.jbossall-client} Backing up existing ${lib.jbossaop-client.injboss} to ${bak.jbossaop-client} Backing up existing aop deployer to ${old.deployer} libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/jboss.properties0000644000175000017500000000041511145122070026566 0ustar twernertwerner# Properties file for the ant install scripts # Set the root of your jboss installation here jboss.home=/Users/kabir/sourcecontrol/jboss-head/build/output/jboss-5.0.0.GA/ #Set the server configuration you want to patch here (e.g, all or default) jboss.config=all libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/default.mf0000644000175000017500000000061711145122070025304 0ustar twernertwernerManifest-Version: 1.0 Created-By: @java.vm.version@ (@java.vm.vendor@) Specification-Title: @aop.title@ Specification-Version: @aop.version@ Specification-Vendor: @specification.vendor@ Implementation-Title: @aop.title@ Implementation-URL: @implementation.url@ Implementation-Version: @aop.version@ Implementation-Vendor: @implementation.vendor@ Implementation-Vendor-Id: @implementation.vendor.id@ libjboss-aop-java-2.0.1.GA.orig/src/asintegration-core/etc/ReadMe-AS4.txt0000644000175000017500000000320411145122070025612 0ustar twernertwernerNOTE: from the 2.0 release of JBoss AOP only JDK1.5 is supported. This means that that both JBoss AS and AOP need to be compiled with JDK1.5 before you upgrade JBoss AOP. To upgrade your jboss instance: * If installing in a version before JBoss 4.0.4, you should leave javassist.jar in place in this folder. *If installing in jboss 4.0.4 or later, the classes contained in javassist.jar will already be available, and you should do the following to avoid versioning conflicts: -move javassist.jar to ../../lib/javassist.jar *On JBoss 4.0.4 or later, and if using JDK 1.4, you should upgrade the version of jbossretro-rt.jar by moving it from the jboss-aop-jdk14.deployer to ../../lib/jbossretro-rt.jar * Note that this will not replace the jboss-aspect-library(-jdk50).jar, which is tied to application server version. If you are upgrading from JBoss AOP 1.5.x, you should remove the following packages and classes contained therein from your jboss-aspect-library(-jdk50).jar: -org.jboss.aop -org.jboss.aop.deployment *Also, in the existing jboss-aspect-library(-jdk50).jar you should delete the classes that exist in jboss-standalone-aspect-library-jdkxx.jar * If you are deploying the jdk 1.4 deployer and upgrading from JDK 1.5, we need to modify the interfaces specifying the simulated annotations in jboss-aspect-library.jar. The build.xml file does this as part of the install step. Alternatively, you can use the ant script, which will automate all these tasks for you: 1) Edit jboss.properties file, setting the root of the jboss installation and the server configuration you wish to patch. 2) Run the command: $ ant libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/0000755000175000017500000000000011145122054022234 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/0000755000175000017500000000000011145122054023160 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/0000755000175000017500000000000011145122054023747 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/0000755000175000017500000000000011145122056025071 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aspects/0000755000175000017500000000000011145122056026533 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aspects/ThreadbasedAspect.java0000644000175000017500000000351211145122056032745 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aspects; import org.jboss.aop.joinpoint.FieldReadInvocation; import org.jboss.aop.joinpoint.FieldWriteInvocation; /** * This aspect should be scoped PER_JOINPOINT * It allows a field to be like a ThreadLocal * * @author Bill Burke * @version $Revision: 71279 $ */ public class ThreadbasedAspect { private ThreadLocal threadbased = new ThreadLocal(); public Object access(FieldReadInvocation invocation) throws Throwable { // just in case we have a primitive, we can't return null if (threadbased.get() == null) return invocation.invokeNext(); return threadbased.get(); } public Object access(FieldWriteInvocation invocation) throws Throwable { threadbased.set(invocation.getValue()); return null; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aspects/Threadbased.java0000644000175000017500000000273411145122056031612 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aspects; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for declaring a field that behaves like a ThreadLocal * * @author Bill Burke * @version $Revision: 57688 $ */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Threadbased { } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/0000755000175000017500000000000011145122070025644 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/AspectAnnotationLoader.java0000644000175000017500000012210711145122062033114 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.io.DataInputStream; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import javassist.CtClass; import javassist.CtPrimitiveType; import javassist.Modifier; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.Descriptor; import javassist.bytecode.FieldInfo; import javassist.bytecode.MethodInfo; import javassist.bytecode.annotation.ArrayMemberValue; import javassist.bytecode.annotation.BooleanMemberValue; import javassist.bytecode.annotation.ClassMemberValue; import javassist.bytecode.annotation.MemberValue; import javassist.bytecode.annotation.StringMemberValue; import org.jboss.aop.AspectAnnotationLoaderStrategy.InterfaceIntroductionInfo; import org.jboss.aop.AspectAnnotationLoaderStrategy.InterfaceIntroductionMixinInfo; import org.jboss.aop.advice.AspectFactory; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.advice.PrecedenceDefEntry; import org.jboss.aop.advice.Scope; import org.jboss.annotation.factory.javassist.AnnotationProxy; import org.jboss.aop.pointcut.DynamicCFlow; import org.jboss.aop.pointcut.ast.ASTCFlowExpression; import org.jboss.aop.pointcut.ast.PointcutExpressionParser; import org.jboss.aop.util.MethodHashing; import org.jboss.aop.util.logging.AOPLogger; /** * Comment * * @author Bill Burke * @version $Revision: 77480 $ */ public class AspectAnnotationLoader { private static final AOPLogger logger = AOPLogger.getLogger(AspectAnnotationLoader.class); protected AspectManager manager; private ClassLoader cl; private final AspectAnnotationLoaderStrategy loaderStrategy; public AspectAnnotationLoader(AspectManager manager) { this.manager = manager; loaderStrategy = new AspectManagerAnnotationLoaderStrategy(); } public AspectAnnotationLoader(AspectManager manager, AspectAnnotationLoaderStrategy loaderStrategy) { this.manager = manager; this.loaderStrategy = loaderStrategy; } public void setClassLoader(ClassLoader cl) { this.cl = cl; } public AspectManager getAspectManager() { return manager; } public ClassLoader getClassLoader() { return cl; } public void deployInputStreamIterator(Iterator it) throws Exception { while (it.hasNext()) { InputStream stream = it.next(); DataInputStream dstream = new DataInputStream(stream); ClassFile cf = null; try { cf = new ClassFile(dstream); } finally { dstream.close(); stream.close(); } deployClassFile(cf); } } public void deployClassFile(ClassFile cf) throws Exception { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Looking for aspects in: " + cf.getName()); AnnotationsAttribute visible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag); if (visible != null) { boolean deployed = deployAspect(visible, cf); if (!deployed) { deployed = deployInterceptor(visible, cf); } if (!deployed) { deployDynamicCFlow(visible, cf); if (!deployPreparedClass(visible, cf)) { deployPrecedence(visible, cf); } } } } public void undeployInputStreamIterator(Iterator it) throws Exception { while (it.hasNext()) { InputStream stream = it.next(); DataInputStream dstream = new DataInputStream(stream); ClassFile cf = null; try { cf = new ClassFile(dstream); } finally { dstream.close(); stream.close(); } undeployClassFile(cf); } } public void undeployClassFile(ClassFile cf) throws Exception { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Looking for aspects in: " + cf.getName()); AnnotationsAttribute visible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag); if (visible != null) { undeployAspect(visible, cf); undeployInterceptor(visible, cf); undeployDynamicCFlow(visible, cf); undeployPreparedClass(visible, cf); undeployPrecedence(visible, cf); undeployPointcuts(cf); undeployMixins(cf); undeployIntroductions(cf); undeployTypedefs(cf); undeployCFlowStackDefs(cf); undeployPrepares(cf); undeployAnnotationIntroductions(cf); undeployDeclares(cf); } } private boolean deployAspect(AnnotationsAttribute visible, ClassFile cf) throws Exception { //Check for Aspect javassist.bytecode.annotation.Annotation info = visible.getAnnotation(Aspect.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("[debug] Found @Aspect in: " + cf.getName()); Aspect aspect = (Aspect) AnnotationProxy.createProxy(info, Aspect.class); Scope scope = aspect.scope(); String[] interfaces = cf.getInterfaces(); boolean isFactory = false; for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(AspectFactory.class.getName())) { isFactory = true; break; } } loaderStrategy.deployAspect(this, isFactory, cf.getName(), scope); deployAspectOrInterceptorFields(cf); if (!isFactory) { deployAspectMethodBindings(cf, cf.getName()); } return true; } return false; } private void undeployAspect(AnnotationsAttribute visible, ClassFile cf) throws Exception { //Check for Aspect javassist.bytecode.annotation.Annotation info = visible.getAnnotation(Aspect.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Undeploying @Aspect in: " + cf.getName()); loaderStrategy.undeployAspect(this, cf.getName()); undeployAspectMethodBindings(cf); } } private boolean deployInterceptor(AnnotationsAttribute visible, ClassFile cf) throws Exception { //Check for InterceptorDef javassist.bytecode.annotation.Annotation info = visible.getAnnotation(InterceptorDef.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Found @InterceptorDef in: " + cf.getName()); Aspect aspect = (Aspect) AnnotationProxy.createProxy(info, Aspect.class); Scope scope = aspect.scope(); String[] interfaces = cf.getInterfaces(); boolean isFactory = false; for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(AspectFactory.class.getName())) { isFactory = true; break; } else if (interfaces[i].equals(Interceptor.class.getName())) { break; } } loaderStrategy.deployInterceptor(this, isFactory, cf.getName(), scope); deployAspectOrInterceptorFields(cf); deployInterceptorBindings(visible, cf, cf.getName()); return true; } return false; } private void undeployInterceptor(AnnotationsAttribute visible, ClassFile cf) throws Exception { //Check for InterceptorDef javassist.bytecode.annotation.Annotation info = visible.getAnnotation(InterceptorDef.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Undeploying @InterceptorDef in: " + cf.getName()); AnnotationProxy.createProxy(info, Aspect.class); loaderStrategy.undeployInterceptor(this, cf.getName()); undeployInterceptorBindings(visible, cf); } } private void deployDynamicCFlow(AnnotationsAttribute visible, ClassFile cf) throws Exception { javassist.bytecode.annotation.Annotation info = visible.getAnnotation(DynamicCFlowDef.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Found @DynamicCFlowDef in: " + cf.getName()); AnnotationProxy.createProxy(info, DynamicCFlowDef.class); String name = cf.getName(); String clazz = cf.getName(); String[] interfaces = cf.getInterfaces(); boolean foundDCFlow = false; for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(DynamicCFlow.class.getName())) { foundDCFlow = true; break; } } if (!foundDCFlow) throw new RuntimeException("@DynamicCFlow annotated class: " + clazz + " must implement " + DynamicCFlow.class.getName()); loaderStrategy.deployDynamicCFlow(this, clazz, name); } } private void undeployDynamicCFlow(AnnotationsAttribute visible, ClassFile cf) throws Exception { javassist.bytecode.annotation.Annotation info = visible.getAnnotation(DynamicCFlowDef.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Undeploying @DynamicCFlowDef in: " + cf.getName()); String name = cf.getName(); loaderStrategy.undeployDynamicCFlow(this, name); } } private boolean deployPreparedClass(AnnotationsAttribute visible, ClassFile cf) throws Exception { //Check for Aspect javassist.bytecode.annotation.Annotation info = visible.getAnnotation(Prepare.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Found top-level @Prepare in: " + cf.getName()); Prepare prepare = (Prepare) AnnotationProxy.createProxy(info, Prepare.class); String name = cf.getName() + "." + visible.getName(); String expr = replaceThisInExpr(prepare.value(), cf.getName()); loaderStrategy.deployPointcut(this, name, expr); return true; } return false; } private void undeployPreparedClass(AnnotationsAttribute visible, ClassFile cf) throws Exception { //Check for Aspect javassist.bytecode.annotation.Annotation info = visible.getAnnotation(Prepare.class.getName()); if (info != null) { String name = cf.getName() + "." + visible.getName(); loaderStrategy.undeployPointcut(this, name); } } private void deployPrecedence(AnnotationsAttribute visible, ClassFile cf)throws Exception { javassist.bytecode.annotation.Annotation info = visible.getAnnotation(Precedence.class.getName()); if (info != null) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Found top-level @Precedence in: " + cf.getName()); ArrayList entries = new ArrayList(); Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(PrecedenceInterceptor.class.getName()); if (binfo != null) { //TODO Make sure it is an interceptor entries.add(new PrecedenceDefEntry(getFieldType(finfo), null)); } else { binfo = mgroup.getAnnotation(PrecedenceAdvice.class.getName()); if (binfo != null) { PrecedenceAdvice advice = (PrecedenceAdvice) AnnotationProxy.createProxy(binfo, PrecedenceAdvice.class); String method = advice.value(); entries.add(new PrecedenceDefEntry(getFieldType(finfo), method)); } } } PrecedenceDefEntry[] pentries = entries.toArray(new PrecedenceDefEntry[entries.size()]); loaderStrategy.deployPrecedence(this, cf.getName(), pentries); } } private void undeployPrecedence(AnnotationsAttribute visible, ClassFile cf)throws Exception { javassist.bytecode.annotation.Annotation info = visible.getAnnotation(Precedence.class.getName()); if (info != null) { loaderStrategy.undeployPrecedence(this, cf.getName()); } } private void deployAspectMethodBindings(ClassFile cf, String aspectDefName/*, AspectDefinition def*/) throws Exception { Iterator methods = cf.getMethods().iterator(); while (methods.hasNext()) { MethodInfo minfo = methods.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Bind.class.getName()); if (binfo == null) continue; Bind binding = (Bind) AnnotationProxy.createProxy(binfo, Bind.class); String pointcutString = replaceThisInExpr(binding.pointcut(), cf.getName()); String cflow = replaceThisInExpr(binding.cflow(), cf.getName()); if (cflow == null || cflow.trim().equals("")) cflow = null; ASTCFlowExpression cflowExpression = null; if (cflow != null) { cflowExpression = new PointcutExpressionParser(new StringReader(cflow)).CFlowExpression(); } org.jboss.aop.advice.AdviceType internalAdviceType = getInternalAdviceType(binding.type()); String bindingName = getAspectMethodBindingName(cf, minfo); loaderStrategy.deployAspectMethodBinding(this, internalAdviceType, aspectDefName, minfo.getName(), bindingName, pointcutString, cflow, cflowExpression); } } private org.jboss.aop.advice.AdviceType getInternalAdviceType(AdviceType adviceType) { if (adviceType == AdviceType.AROUND) { return org.jboss.aop.advice.AdviceType.AROUND; } else if (adviceType == AdviceType.BEFORE) { return org.jboss.aop.advice.AdviceType.BEFORE; } else if (adviceType == AdviceType.AFTER) { return org.jboss.aop.advice.AdviceType.AFTER; } else if (adviceType == AdviceType.THROWING) { return org.jboss.aop.advice.AdviceType.THROWING; } else if (adviceType == AdviceType.FINALLY) { return org.jboss.aop.advice.AdviceType.FINALLY; } throw new RuntimeException("Bad type " + adviceType); } private void undeployAspectMethodBindings(ClassFile cf) throws Exception { Iterator methods = cf.getMethods().iterator(); while (methods.hasNext()) { MethodInfo minfo = methods.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Bind.class.getName()); if (binfo == null) continue; String bindingName = getAspectMethodBindingName(cf, minfo); loaderStrategy.undeployAspectMethodBinding(this, bindingName, cf.getName(), minfo.getName()); } } private String getAspectMethodBindingName(ClassFile cf, MethodInfo minfo)throws Exception { String method = cf.getName() + "." + minfo.getName(); String fullMethod = method + minfo.getDescriptor(); return method + " " + MethodHashing.createHash(fullMethod); } private void deployInterceptorBindings(AnnotationsAttribute visible, ClassFile cf, String name) throws Exception { javassist.bytecode.annotation.Annotation binfo = visible.getAnnotation(Bind.class.getName()); if (binfo == null) return; Bind bind = (Bind) AnnotationProxy.createProxy(binfo, Bind.class); String pointcutString = replaceThisInExpr(bind.pointcut(), cf.getName()); String cflow = replaceThisInExpr(bind.cflow(), cf.getName()); if (cflow == null || cflow.trim().equals("")) cflow = null; ASTCFlowExpression cflowExpression = null; if (cflow != null) { cflowExpression = new PointcutExpressionParser(new StringReader(cflow)).CFlowExpression(); } loaderStrategy.deployInterceptorBinding(this, name, pointcutString, cflow, cflowExpression); } private void undeployInterceptorBindings(AnnotationsAttribute visible, ClassFile cf) throws Exception { javassist.bytecode.annotation.Annotation binfo = visible.getAnnotation(Bind.class.getName()); if (binfo == null) return; loaderStrategy.undeployInterceptorBinding(this, cf.getName()); } private void deployPointcuts(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(PointcutDef.class.getName()); if (binfo == null) continue; PointcutDef pdef = (PointcutDef) AnnotationProxy.createProxy(binfo, PointcutDef.class); loaderStrategy.deployPointcut(this, getPointcutName(cf, finfo), pdef.value()); } } private void undeployPointcuts(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(PointcutDef.class.getName()); if (binfo == null) continue; loaderStrategy.undeployPointcut(this, getPointcutName(cf, finfo)); } } private String getPointcutName(ClassFile cf, FieldInfo finfo) { return cf.getName() + "." + finfo.getName(); } private void deployMixins(ClassFile cf) throws Exception { Iterator methods = cf.getMethods().iterator(); while (methods.hasNext()) { MethodInfo minfo = methods.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Mixin.class.getName()); if (binfo == null) continue; //Since some of the values are of type Class, and method gets called by the system classloader (via Agent) // for loadtime aop in jdk 1.5 the classes we try to look at might not yet have been loaded. We're //only after the names anyway, so we bypass the AnnotationProxy/ProxyMapCreator which tries to validate //class names by loading the (so far) non-existent class. //Mixin mixin = (Mixin) AnnotationProxy.createProxy(binfo, Mixin.class); //String target = mixin.target(); //String typeExpression = mixin.typeExpression(); //String[] interfaces = mixin.interfaces(); //boolean isTransient = mixin.isTransient(); MemberValue mv = binfo.getMemberValue("target"); String target = (mv != null) ? ((ClassMemberValue) mv).getValue() : "java.lang.Class";//Note! this should be the same as the default in @Mixin mv = binfo.getMemberValue("typeExpression"); String typeExpression = (mv != null) ? ((StringMemberValue) mv).getValue() : "";//Note! this should be the same as the default in @Mixin mv = binfo.getMemberValue("interfaces"); MemberValue[] values = ((ArrayMemberValue) mv).getValue(); String[] interfaces = new String[values.length]; for (int i = 0; i < values.length; i++) interfaces[i] = ((ClassMemberValue) values[i]).getValue(); mv = binfo.getMemberValue("isTransient"); boolean isTransient = (mv != null) ? ((BooleanMemberValue) mv).getValue() : true;//Note! this should be the same as the default in @Mixin String name = cf.getName() + "." + minfo.getName(); //Name of the method defined on InterfaceIntroductionInfo intro = null; String construction = name; switch(Descriptor.numOfParameters(minfo.getDescriptor())) { case 0: construction += "()"; intro = createIntroduction(name, target, typeExpression, null, null, null);//cf.getName(), minfo.getName()); break; case 1: construction += "(this)"; intro = createIntroduction(name, target, typeExpression, null, cf.getName(), minfo.getName()); String parameter = Descriptor.getParamDescriptor(minfo.getDescriptor()); if (parameter.charAt(1) != 'L') { String errorMessage = "Mixin creator method '" + name + "' parameter is primitive type "; char desc = parameter.charAt(1); if (desc == ((CtPrimitiveType) CtClass.booleanType).getDescriptor()) { errorMessage += "boolean"; } else if (desc == ((CtPrimitiveType) CtClass.byteType).getDescriptor()) { errorMessage += "byte"; } else if (desc == ((CtPrimitiveType) CtClass.charType).getDescriptor()) { errorMessage += "char"; } else if (desc == ((CtPrimitiveType) CtClass.doubleType).getDescriptor()) { errorMessage += "double"; } else if (desc == ((CtPrimitiveType) CtClass.floatType).getDescriptor()) { errorMessage += "float"; } else if (desc == ((CtPrimitiveType) CtClass.intType).getDescriptor()) { errorMessage += "int"; } else if (desc == ((CtPrimitiveType) CtClass.longType).getDescriptor()) { errorMessage += "long"; } else if (desc == ((CtPrimitiveType) CtClass.shortType).getDescriptor()) { errorMessage += "short"; } else { break; } errorMessage += ".\n It should have the introduction target type as parameter, or have no parameter at all."; throw new RuntimeException(errorMessage); } break; default: throw new RuntimeException("Mixin creator method '" + name + "' should not have more than one parameter."); } if (!Modifier.isStatic(minfo.getAccessFlags()) || !Modifier.isPublic(minfo.getAccessFlags())) { throw new RuntimeException("Mixin creator method '" + name + "' must be public and static."); } //Parse the descriptor to get the returntype of the method. String classname = getReturnType(minfo); intro.addMixin(new InterfaceIntroductionMixinInfo(classname, interfaces, construction, isTransient)); loaderStrategy.deployInterfaceIntroduction(this, intro); } } private void undeployMixins(ClassFile cf) throws Exception { Iterator methods = cf.getMethods().iterator(); while (methods.hasNext()) { MethodInfo minfo = methods.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Mixin.class.getName()); if (binfo == null) continue; String name = cf.getName() + "." + minfo.getName(); //Name of the method defined on loaderStrategy.undeployInterfaceIntroduction(this, name); } } private void deployIntroductions(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Introduction.class.getName()); if (binfo == null) continue; //Since some of the values are of type Class, and method gets called by the system classloader (via Agent) // for loadtime aop in jdk 1.5 the classes we try to look at might not yet have been loaded. We're //only after the names anyway, so we bypass the AnnotationProxy/ProxyMapCreator which tries to validate //class names by loading the (so far) non-existent class. //Introduction introduction = (Introduction) AnnotationProxy.createProxy(binfo, Introduction.class); //String target = introduction.target(); //String typeExpression = introduction.typeExpression(); //String[] interfaces = introduction.interfaces(); MemberValue mv = binfo.getMemberValue("target"); String target = (mv != null) ? ((ClassMemberValue) mv).getValue() : "java.lang.Class";//Note! this should be the same as the default in @Interceptor mv = binfo.getMemberValue("typeExpression"); String typeExpression = (mv != null) ? ((StringMemberValue) mv).getValue() : "";//Note! this should be the same as the default in @Interceptor mv = binfo.getMemberValue("interfaces"); MemberValue[] values = ((ArrayMemberValue) mv).getValue(); String[] interfaces = new String[values.length]; for (int i = 0; i < values.length; i++) interfaces[i] = ((ClassMemberValue) values[i]).getValue(); String name = cf.getName() + "." + finfo.getName(); //Name of the field defined on InterfaceIntroductionInfo interfaceIntro = createIntroduction(name, target, typeExpression, interfaces, null, null); loaderStrategy.deployInterfaceIntroduction(this, interfaceIntro); } } private void undeployIntroductions(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Introduction.class.getName()); if (binfo == null) continue; String name = cf.getName() + "." + finfo.getName(); //Name of the field defined on loaderStrategy.undeployInterfaceIntroduction(this, name); } } private void deployTypedefs(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(TypeDef.class.getName()); if (binfo == null) continue; TypeDef typeDefinition = (TypeDef) AnnotationProxy.createProxy(binfo, TypeDef.class); String name = getTypedefName(cf, finfo); String expr = typeDefinition.value(); loaderStrategy.deployTypedef(this, name, expr); } } private void undeployTypedefs(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(TypeDef.class.getName()); if (binfo == null) continue; AnnotationProxy.createProxy(binfo, TypeDef.class); loaderStrategy.undeployTypedef(this, getTypedefName(cf, finfo)); } } private String getTypedefName(ClassFile cf, FieldInfo finfo) { return cf.getName() + "." + finfo.getName(); } private void deployCFlowStackDefs(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(CFlowStackDef.class.getName()); if (binfo == null) continue; CFlowStackDef stackDef = (CFlowStackDef) AnnotationProxy.createProxy(binfo, CFlowStackDef.class); String name = getStackDefName(cf, finfo); CFlowDef[] cflows = stackDef.cflows(); AspectAnnotationLoaderStrategy.CFlowStackInfo stack = new AspectAnnotationLoaderStrategy.CFlowStackInfo(name); for (int i = 0; i < cflows.length; i++) { CFlowDef cflow = cflows[i]; boolean not = !cflow.called(); stack.addCFlow(new AspectAnnotationLoaderStrategy.CFlowInfo(cflow.expr(), not)); } loaderStrategy.deployCFlow(this, stack); } } private void undeployCFlowStackDefs(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(CFlowStackDef.class.getName()); if (binfo == null) continue; AnnotationProxy.createProxy(binfo, CFlowStackDef.class); loaderStrategy.undeployCFlow(this, getStackDefName(cf, finfo)); } } private String getStackDefName(ClassFile cf, FieldInfo finfo) { return cf.getName() + "." + finfo.getName(); } private void deployPrepares(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Prepare.class.getName()); if (binfo == null) continue; Prepare prepare = (Prepare) AnnotationProxy.createProxy(binfo, Prepare.class); String name = getPrepareName(cf, finfo); String expr = prepare.value(); loaderStrategy.deployPointcut(this, name, expr); } } private void undeployPrepares(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Prepare.class.getName()); if (binfo == null) continue; AnnotationProxy.createProxy(binfo, Prepare.class); loaderStrategy.undeployPointcut(this, getPrepareName(cf, finfo)); } } private String getPrepareName(ClassFile cf, FieldInfo finfo) { return cf.getName() + "." + finfo.getName(); } private void deployAnnotationIntroductions(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(AnnotationIntroductionDef.class.getName()); if (binfo == null) continue; AnnotationIntroductionDef intro = (AnnotationIntroductionDef) AnnotationProxy.createProxy(binfo, AnnotationIntroductionDef.class); String expr = intro.expr(); boolean invisible = intro.invisible(); String annotation = intro.annotation(); annotation = annotation.replace('\'', '"'); loaderStrategy.deployAnnotationIntroduction(this, expr, annotation, invisible); } } private void undeployAnnotationIntroductions(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(AnnotationIntroductionDef.class.getName()); if (binfo == null) continue; AnnotationIntroductionDef intro = (AnnotationIntroductionDef) AnnotationProxy.createProxy(binfo, AnnotationIntroductionDef.class); String expr = intro.expr(); boolean invisible = intro.invisible(); String annotation = intro.annotation(); annotation = annotation.replace('\'', '"'); loaderStrategy.undeployAnnotationIntroduction(this, expr, annotation, invisible); } } private void deployDeclares(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation dwinfo = mgroup.getAnnotation(DeclareWarning.class.getName()); javassist.bytecode.annotation.Annotation deinfo = mgroup.getAnnotation(DeclareError.class.getName()); if (dwinfo == null && deinfo == null) continue; String name = getDeclareName(cf, finfo); if (dwinfo != null && deinfo != null) throw new RuntimeException("Cannot annotate " + name + " field with both DeclareError and DeclareWarning"); String expr = null; String msg = null; boolean warning = false; if (deinfo != null) { DeclareError derror = (DeclareError) AnnotationProxy.createProxy(deinfo, DeclareError.class); expr = derror.expr(); msg = derror.msg(); } else { DeclareWarning dwarning = (DeclareWarning) AnnotationProxy.createProxy(dwinfo, DeclareWarning.class); expr = dwarning.expr(); msg = dwarning.msg(); warning = true; } loaderStrategy.deployDeclare(this, name, expr, warning, msg); } } private void undeployDeclares(ClassFile cf) throws Exception { Iterator fields = cf.getFields().iterator(); while (fields.hasNext()) { FieldInfo finfo = fields.next(); AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag); if (mgroup == null) continue; javassist.bytecode.annotation.Annotation dwinfo = mgroup.getAnnotation(DeclareWarning.class.getName()); javassist.bytecode.annotation.Annotation deinfo = mgroup.getAnnotation(DeclareError.class.getName()); if (dwinfo == null && deinfo == null) continue; String name = getDeclareName(cf, finfo); loaderStrategy.undeployDeclare(this, name); } } private String getDeclareName(ClassFile cf, FieldInfo finfo) { return cf.getName() + "." + finfo.getName(); } private InterfaceIntroductionInfo createIntroduction(String name, String target, String typeExpression, String[] interfaces, String constructorClass, String constructorMethod) throws Exception { if (typeExpression != null && typeExpression.trim().equals("")) { typeExpression = null; } if (typeExpression != null && target != null && target.equals("java.lang.Class")) { target = null; } if (target == null && typeExpression == null) { throw new RuntimeException("No target nor a typeExpression attribute is defined for this @Mixin"); } if (target == null && typeExpression == null) { throw new RuntimeException("You cannot define both a target and typeExpression attribute in the same @Mixin"); } InterfaceIntroductionInfo intro = new InterfaceIntroductionInfo(name, interfaces, target, typeExpression, constructorClass, constructorMethod); return intro; } private String getReturnType(MethodInfo minfo) { String descriptor = minfo.getDescriptor(); int paramsEnd = descriptor.indexOf(")"); String classname = descriptor.substring(paramsEnd + 2, descriptor.length() - 1); classname = classname.replace('/', '.'); return classname; } private String getFieldType(FieldInfo finfo) { //This will be of the form: Lorg/jboss/test/aop/annotated/AspectPerClass; String descriptor = finfo.getDescriptor(); String classname = descriptor.substring(1, descriptor.length() - 1); classname = classname.replace('/', '.'); return classname; } /** * Replace all occurrences of 'this' unless it happens to be part of * another word. For example (if class name is org.acme.Foo: * "all(this)" -> "all(org.acme.Foo)" * "all(org.Forthis)" -> "all(org.Forthis)" * "all(org.thisthing.Foo)" -> "all(org.thisthing.Foo)" * * @param s * @param classname * @return */ private static String replaceThisInExpr(String expr, String classname) { final String THIS = "this"; StringBuffer buf = new StringBuffer(); int index = expr.indexOf(THIS); if (index == -1) { return expr; } int lastindex = 0; while (index != -1) { boolean isPartOfWord = false; if (index > 0) { char before = expr.charAt(index - 1); isPartOfWord = Character.isJavaIdentifierPart(before); } if (!isPartOfWord && index + THIS.length() < expr.length() - 1) { char after = expr.charAt(index + THIS.length()); isPartOfWord = Character.isJavaIdentifierPart(after); } buf.append(expr.substring(lastindex, index)); if (isPartOfWord) { buf.append(THIS); } else { buf.append(classname); } lastindex = index + THIS.length(); index = expr.indexOf(THIS, lastindex); } buf.append(expr.substring(lastindex)); return buf.toString(); } private void deployAspectOrInterceptorFields(ClassFile cf) throws Exception { deployPointcuts(cf); deployMixins(cf); deployIntroductions(cf); deployTypedefs(cf); deployCFlowStackDefs(cf); deployPrepares(cf); deployAnnotationIntroductions(cf); deployDeclares(cf); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/ConByMethodInfo.java0000644000175000017500000000565711145122060031512 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.joinpoint.ConstructorCalledByMethodJoinpoint; import org.jboss.aop.joinpoint.ConstructorCallByMethod; import org.jboss.aop.joinpoint.Joinpoint; /** * * @author Kabir Khan * @version $Revision: 70817 $ */ public class ConByMethodInfo extends CallerConstructorInfo implements ConstructorCallByMethod { private final long callingMethodHash; private final Method callingMethod; /** * Create a new ConByMethodJoinPont. * * @param c * @param in */ public ConByMethodInfo(Advisor advisor, Class calledClass, Method callingMethod, long callingMethodHash, Constructor c, long calledConHash, Method wrappingMethod, Interceptor[] in) { super(advisor, calledClass, c, calledConHash, wrappingMethod, in, callingMethod.getDeclaringClass()); this.callingMethodHash = callingMethodHash; this.callingMethod = callingMethod; } /* * For copying */ protected ConByMethodInfo(ConByMethodInfo other) { super(other); this.callingMethodHash = other.callingMethodHash; this.callingMethod = other.callingMethod; } protected Joinpoint internalGetJoinpoint() { return new ConstructorCalledByMethodJoinpoint(callingMethod, getConstructor()); } public JoinPointInfo copy() { return new ConByMethodInfo(this); } public String toString() { StringBuffer sb = new StringBuffer("Constructor called by Method"); sb.append("["); sb.append("calling=" + callingMethod); sb.append(",called=" + getConstructor()); sb.append("]"); return sb.toString(); } public long getCallingMethodHash() { return callingMethodHash; } public Method getCallingMethod() { return callingMethod; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/WeavingStrategy.java0000644000175000017500000000247211145122060031636 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; /** * * @author Stale W. Pedersen * @author Kabir Khan * @version $Revision: */ public interface WeavingStrategy { byte[] translate(AspectManager manager, String className, ClassLoader loader, byte[] classfileBuffer) throws Exception; } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/AspectManagerAnnotationLoaderStrategy.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/AspectManagerAnnotationLoade0000644000175000017500000002447711145122064033322 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.io.StringReader; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.AdviceFactory; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.AspectFactory; import org.jboss.aop.advice.AspectFactoryDelegator; import org.jboss.aop.advice.AspectFactoryWithClassLoader; import org.jboss.aop.advice.DynamicCFlowDefinition; import org.jboss.aop.advice.GenericAspectFactory; import org.jboss.aop.advice.InterceptorFactory; import org.jboss.aop.advice.PrecedenceDef; import org.jboss.aop.advice.PrecedenceDefEntry; import org.jboss.aop.advice.Scope; import org.jboss.aop.advice.ScopedInterceptorFactory; import org.jboss.aop.introduction.AnnotationIntroduction; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.pointcut.CFlow; import org.jboss.aop.pointcut.CFlowStack; import org.jboss.aop.pointcut.DeclareDef; import org.jboss.aop.pointcut.Pointcut; import org.jboss.aop.pointcut.PointcutExpression; import org.jboss.aop.pointcut.Typedef; import org.jboss.aop.pointcut.TypedefExpression; import org.jboss.aop.pointcut.ast.ASTCFlowExpression; import org.jboss.aop.pointcut.ast.ASTStart; import org.jboss.aop.pointcut.ast.TypeExpressionParser; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class AspectManagerAnnotationLoaderStrategy implements AspectAnnotationLoaderStrategy { public void deployAspect(AspectAnnotationLoader loader, boolean isFactory, String name, Scope scope) { AspectFactory factory = null; if (isFactory) { factory = new AspectFactoryDelegator(name, null); ((AspectFactoryWithClassLoader)factory).setClassLoader(loader.getClassLoader()); } else { factory = new GenericAspectFactory(name, null); ((AspectFactoryWithClassLoader)factory).setClassLoader(loader.getClassLoader()); } AspectDefinition def = new AspectDefinition(name, scope, factory); loader.getAspectManager().addAspectDefinition(def); } public void deployAspectMethodBinding( AspectAnnotationLoader loader, org.jboss.aop.advice.AdviceType internalAdviceType, String aspectDefName, String methodName, String bindingName, String pointcutString, String cflow, ASTCFlowExpression cflowExpression)throws Exception { AspectDefinition def = loader.getAspectManager().getAspectDefinition(aspectDefName); AdviceFactory factory = null; if (internalAdviceType == org.jboss.aop.advice.AdviceType.AROUND) { factory = new AdviceFactory(def, methodName); } else { factory = new AdviceFactory(def, methodName, internalAdviceType); } loader.getAspectManager().addInterceptorFactory(factory.getName(), factory); InterceptorFactory[] fact = {factory}; PointcutExpression pointcut = new PointcutExpression(bindingName, pointcutString); AdviceBinding abinding = new AdviceBinding(bindingName, pointcut, cflowExpression, cflow, fact); loader.getAspectManager().addBinding(abinding); } public void undeployAspect(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removeAspectDefinition(name); } public void undeployAspectMethodBinding(AspectAnnotationLoader loader, String bindingName, String className, String methodName) { String adviceName = className + "." + methodName; loader.getAspectManager().removeInterceptorFactory(adviceName); loader.getAspectManager().removePointcut(bindingName); loader.getAspectManager().removeBinding(bindingName); } public void deployInterceptor(AspectAnnotationLoader loader, boolean isFactory, String name, Scope scope) { deployAspect(loader, isFactory, name, scope); AspectDefinition def = loader.getAspectManager().getAspectDefinition(name); ScopedInterceptorFactory factory = new ScopedInterceptorFactory(def); loader.getAspectManager().addInterceptorFactory(factory.getName(), factory); } public void deployInterceptorBinding(AspectAnnotationLoader loader, String name, String pointcutString, String cflow, ASTCFlowExpression cflowExpression) throws Exception { InterceptorFactory factory = loader.getAspectManager().getInterceptorFactory(name); InterceptorFactory[] inters = {factory}; Pointcut p = null; p = new PointcutExpression(name, pointcutString); AdviceBinding binding = new AdviceBinding(name, p, cflowExpression, cflow, inters); loader.getAspectManager().addBinding(binding); } public void undeployInterceptor(AspectAnnotationLoader loader, String name) { undeployAspect(loader, name); loader.getAspectManager().removeInterceptorFactory(name); } public void undeployInterceptorBinding(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removePointcut(name); loader.getAspectManager().removeBinding(name); } public void deployDynamicCFlow(AspectAnnotationLoader loader, String name, String clazz) { loader.getAspectManager().addDynamicCFlow(name, new DynamicCFlowDefinition(null, clazz, name)); } public void undeployDynamicCFlow(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removeDynamicCFlow(name); } public void deployPointcut(AspectAnnotationLoader loader, String name, String expr) throws Exception { Pointcut p = new PointcutExpression(name, expr); loader.getAspectManager().addPointcut(p); } public void undeployPointcut(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removePointcut(name); } public void deployPrecedence(AspectAnnotationLoader loader, String name, PrecedenceDefEntry[] pentries) { PrecedenceDef precedenceDef = new PrecedenceDef(name, pentries); loader.getAspectManager().addPrecedence(precedenceDef); } public void undeployPrecedence(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removePrecedence(name); } public void deployTypedef(AspectAnnotationLoader loader, String name, String expr) throws Exception { Typedef typedef = new TypedefExpression(name, expr); loader.getAspectManager().addTypedef(typedef); } public void undeployTypedef(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removeTypedef(name); } public void deployDeclare(AspectAnnotationLoader loader, String name, String expr, boolean warning, String msg) throws Exception { DeclareDef def = new DeclareDef(name, expr, warning, msg); loader.getAspectManager().addDeclare(def); } public void undeployDeclare(AspectAnnotationLoader loader, String name) throws Exception { loader.getAspectManager().removeDeclare(name); } public void deployAnnotationIntroduction(AspectAnnotationLoader loader, String expr, String annotation, boolean invisible) { AnnotationIntroduction annIntro = AnnotationIntroduction.createComplexAnnotationIntroduction(expr, annotation, invisible); loader.getAspectManager().addAnnotationIntroduction(annIntro); } public void undeployAnnotationIntroduction(AspectAnnotationLoader loader, String expr, String annotation, boolean invisible) { AnnotationIntroduction annIntro = AnnotationIntroduction.createComplexAnnotationIntroduction(expr, annotation, invisible); loader.getAspectManager().removeAnnotationIntroduction(annIntro); } public void deployCFlow(AspectAnnotationLoader loader, CFlowStackInfo info) { CFlowStack stack = new CFlowStack(info.getName()); for (CFlowInfo cinfo : info.getCFlows()) { stack.addCFlow(new CFlow(cinfo.getExpr(), cinfo.isNot())); } loader.getAspectManager().addCFlowStack(stack); } public void undeployCFlow(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removeCFlowStack(name); } public void deployInterfaceIntroduction(AspectAnnotationLoader loader, AspectAnnotationLoaderStrategy.InterfaceIntroductionInfo introduction) throws Exception { InterfaceIntroduction intro = null; if (introduction.getTarget() != null) { intro = new InterfaceIntroduction(introduction.getName(), introduction.getTarget(), introduction.getInterfaces(), introduction.getConstructorClass(), introduction.getConstructorMethod()); } else { ASTStart start = new TypeExpressionParser(new StringReader(introduction.getExpr())).Start(); intro = new InterfaceIntroduction(introduction.getName(), start, introduction.getInterfaces(), introduction.getConstructorClass(), introduction.getConstructorMethod()); } if (introduction.getMixins() != null) { for (AspectAnnotationLoaderStrategy.InterfaceIntroductionMixinInfo mixin : introduction.getMixins()) { intro.getMixins().add(new InterfaceIntroduction.Mixin(mixin.getClassname(), mixin.getInterfaces(), mixin.getConstruction(), mixin.isTrans())); } } loader.getAspectManager().addInterfaceIntroduction(intro); } public void undeployInterfaceIntroduction(AspectAnnotationLoader loader, String name) { loader.getAspectManager().removeInterfaceIntroduction(name); } }././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/GeneratedInstanceAdvisorMixin.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/GeneratedInstanceAdvisorMixi0000644000175000017500000003542511145122060033341 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import org.jboss.aop.advice.AdviceStack; import org.jboss.aop.advice.AdviceType; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.advice.InterceptorFactory; import org.jboss.aop.advice.GeneratedAdvisorInterceptor; import org.jboss.aop.joinpoint.Joinpoint; import org.jboss.aop.metadata.SimpleMetaData; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Adapts the old instance advisor api to the new generated advisor stuff. * Old API calls on generated instance advisors will delegate to this class * * @author Kabir Khan * @version $Revision$ */ public class GeneratedInstanceAdvisorMixin implements InstanceAdvisor, java.io.Serializable { static final long serialVersionUID = -3057976129116723527L; protected ArrayList insertedInterceptors = null; protected ArrayList appendedInterceptors = null; protected WeakReference instanceRef; public boolean hasInstanceAspects = false; private InterceptorChainObserver interceptorChainObserver; InstanceAdvisorDelegate delegate; protected Map stacks = null; public GeneratedInstanceAdvisorMixin() { } public GeneratedInstanceAdvisorMixin(Object instance, GeneratedClassAdvisor genadvisor) { this.instanceRef = new WeakReference(instance); delegate = new InstanceAdvisorDelegate(genadvisor, this); delegate.initialize(); this.interceptorChainObserver = ((ClassAdvisor) genadvisor).getInterceptorChainObserver(); } public boolean hasInterceptors() { return appendedInterceptors != null || insertedInterceptors != null; } public Object getPerInstanceAspect(String def) { return delegate.getPerInstanceAspect(def); } public Object getPerInstanceAspect(AspectDefinition def) { return delegate.getPerInstanceAspect(def); } public Object getPerInstanceJoinpointAspect(Joinpoint joinpoint, AspectDefinition def) { return delegate.getPerInstanceJoinpointAspect(joinpoint, def); } public SimpleMetaData getMetaData() { return delegate.getMetaData(); } public Interceptor[] getInterceptors() { ArrayList newlist = new ArrayList(); if (insertedInterceptors != null && insertedInterceptors.size() > 0) { for (Interceptor icptr : insertedInterceptors) { Interceptor interceptor = ((GeneratedAdvisorInterceptor)icptr). create(null, null); if (interceptor != null) { newlist.add(interceptor); } } } if (appendedInterceptors != null && appendedInterceptors.size() > 0) { for (Interceptor icptr : appendedInterceptors) { newlist.add(((GeneratedAdvisorInterceptor)icptr).create(null, null)); } } return newlist.toArray(new Interceptor[newlist.size()]); } /** * Called by the advisor */ public Interceptor[] getInterceptors(Interceptor[] advisorChain) { if (insertedInterceptors == null && appendedInterceptors == null) return advisorChain; ArrayList newlist = new ArrayList(); if (insertedInterceptors != null && insertedInterceptors.size() > 0) { for (Interceptor icptr : insertedInterceptors) { Interceptor interceptor = ((GeneratedAdvisorInterceptor)icptr). create(null, null); if (interceptor != null) { newlist.add(interceptor); } } } if (advisorChain != null) { newlist.addAll(Arrays.asList(advisorChain)); } if (appendedInterceptors != null && appendedInterceptors.size() > 0) { for (Interceptor icptr : appendedInterceptors) { newlist.add(((GeneratedAdvisorInterceptor)icptr).create(null, null)); } } return newlist.toArray(new Interceptor[newlist.size()]); } public GeneratedAdvisorInterceptor[] getWrappers() { ArrayList newlist = new ArrayList(); if (insertedInterceptors != null) newlist.addAll(insertedInterceptors); if (appendedInterceptors != null) newlist.addAll(appendedInterceptors); return newlist.toArray(new GeneratedAdvisorInterceptor[newlist.size()]); } /** * Called by the advisor * @param An array of GeneratedAdvisorInterceptor from the advisor's intereceptor chain for the joinpoint * @return The advisor's original array along with extra GeneratedAdvisorInterceptors appended/prepended to this instance */ public Interceptor[] getWrappers(Interceptor[] advisorChain) { if (insertedInterceptors == null && appendedInterceptors == null) return advisorChain; ArrayList newlist = new ArrayList(); if (insertedInterceptors != null) newlist.addAll(insertedInterceptors); if (advisorChain != null) { newlist.addAll(Arrays.asList(advisorChain)); } if (appendedInterceptors != null) newlist.addAll(appendedInterceptors); return newlist.toArray(new GeneratedAdvisorInterceptor[newlist.size()]); } public void insertInterceptor(int index, Interceptor interceptor) { ArrayList newList = new ArrayList(); if (insertedInterceptors != null && insertedInterceptors.size() > 0) { newList.addAll(insertedInterceptors); } newList.add(index, createWrapper(interceptor)); insertedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } public void insertInterceptor(Interceptor interceptor) { ArrayList newList = new ArrayList(); if (insertedInterceptors != null && insertedInterceptors.size() > 0) { newList.addAll(insertedInterceptors); } newList.add(createWrapper(interceptor)); insertedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } public void appendInterceptor(Interceptor interceptor) { ArrayList newList = new ArrayList(); if (appendedInterceptors != null && appendedInterceptors.size() > 0) { newList.addAll(appendedInterceptors); } newList.add(createWrapper(interceptor)); appendedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } public void appendInterceptor(int index, Interceptor interceptor) { ArrayList newList = new ArrayList(); if (appendedInterceptors != null && appendedInterceptors.size() > 0) { newList.addAll(appendedInterceptors); } newList.add(index, createWrapper(interceptor)); appendedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } /** * This will not remove interceptor pointcuts! You will have to do this through AspectManager */ public void removeInterceptor(String name) { int interceptorsRemoved = internalRemoveInterceptor(name); if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorsRemoved(this, interceptorsRemoved); } } /** * @param name * @return */ private int internalRemoveInterceptor(String name) { int interceptorsRemoved = 0; if (insertedInterceptors != null) { int size = insertedInterceptors.size(); for (int i = 0; i < size ; i++) { GeneratedAdvisorInterceptor interceptor = (GeneratedAdvisorInterceptor) insertedInterceptors.get(i); if (interceptor.getName().equals(name)) { ArrayList newList = new ArrayList(); newList.addAll(insertedInterceptors); newList.remove(i); insertedInterceptors = newList; interceptorsRemoved ++; } } } if (appendedInterceptors != null) { int size = appendedInterceptors.size(); for (int i = 0; i < size ; i++) { GeneratedAdvisorInterceptor interceptor = (GeneratedAdvisorInterceptor) appendedInterceptors.get(i); if (interceptor.getName().equals(name)) { ArrayList newList = new ArrayList(); newList.addAll(appendedInterceptors); newList.remove(i); appendedInterceptors = newList; interceptorsRemoved ++; } } } hasInstanceAspects = ((insertedInterceptors != null && insertedInterceptors.size() > 0) || (appendedInterceptors != null && appendedInterceptors.size() > 0)); return interceptorsRemoved; } public final boolean hasAspects() { return hasInstanceAspects; } public void insertInterceptorStack(String stackName) { AdviceStack stack = AspectManager.instance().getAdviceStack(stackName); if (stack == null) throw new RuntimeException("Stack " + stackName + " not found."); ClassAdvisor classAdvisor = null; Object inst = getInstance(); if (inst instanceof Advised) { Advised advised = (Advised) inst; classAdvisor = ((ClassAdvisor) advised._getAdvisor()); } Interceptor[] interceptors = stack.createInterceptors(classAdvisor, null); for (Interceptor interceptor: interceptors) { insertInterceptor(interceptor); } if (this.stacks == null) { this.stacks = new HashMap(); } this.stacks.put(stackName, interceptors); if (interceptorChainObserver != null) { this.interceptorChainObserver.instanceInterceptorsAdded(this, interceptors.length); } } public void appendInterceptorStack(String stackName) { AdviceStack stack = AspectManager.instance().getAdviceStack(stackName); if (stack == null) throw new RuntimeException("Stack " + stackName + " not found."); ClassAdvisor classAdvisor = null; Object inst = getInstance(); if (inst instanceof Advised) { Advised advised = (Advised) inst; classAdvisor = ((ClassAdvisor) advised._getAdvisor()); } Interceptor[] interceptors = stack.createInterceptors(classAdvisor, null); for (Interceptor interceptor: interceptors) { appendInterceptor(interceptor); } if (this.stacks == null) { this.stacks = new HashMap(); } this.stacks.put(stackName, interceptors); if (interceptorChainObserver != null) { this.interceptorChainObserver.instanceInterceptorsAdded(this, interceptors.length); } } public void removeInterceptorStack(String stackName) { Interceptor[] interceptors = stacks.remove(stackName); if (interceptors == null) { AdviceStack stack = AspectManager.instance().getAdviceStack(stackName); if (stack == null) throw new RuntimeException("Stack " + stackName + " not found."); return; } int interceptorsRemoved = 0; for (Interceptor interceptor: interceptors) { interceptorsRemoved += internalRemoveInterceptor(interceptor.getName()); } if (interceptorChainObserver != null) { this.interceptorChainObserver.instanceInterceptorsRemoved(this, interceptorsRemoved); } } public Domain getDomain() { throw new RuntimeException("Should be handled by generated advisors"); } /** * Added to notify interceptor chain observer of interceptor chain garbage collection. */ protected void finalize() { ClassLoader classLoader = delegate.getAdvisor().getClassLoader(); if (this.interceptorChainObserver == null || !AspectManager.getRegisteredCLs().containsKey(classLoader)) { return; } this.interceptorChainObserver.allInstanceInterceptorsRemoved(this); } private GeneratedAdvisorInterceptor createWrapper(Interceptor interceptor) { return new GeneratedAdvisorInterceptor(new InstanceInterceptorFactory(interceptor), null, null); } public Object getInstance() { if (instanceRef != null) { Object instance = instanceRef.get(); return instance; } return null; } public class InstanceInterceptorFactory implements InterceptorFactory { private Interceptor interceptor; private InstanceInterceptorFactory(Interceptor interceptor) { this.interceptor = interceptor; } public Interceptor create(Advisor advisor, Joinpoint joinpoint) { return interceptor; } public String getClassName() { return interceptor.getClass().getName(); } public String getAdvice() { return "invoke"; } public AspectDefinition getAspect() { return null; } public String getName() { return interceptor.getName(); } public boolean isDeployed() { return true; } public AdviceType getType() { return AdviceType.AROUND; } } }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/Advised.java0000644000175000017500000000326511145122060030073 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; /** * Interface implemented by all classes or interfaces * that are AOP enabled (those are also known as advised classes/interfaces). *
* In other words, every class that is weaved by JBoss AOP automatically implements * this interface, which allows the class and instance advisor retrieval. * * @author Bill Burke * @version $Revision: 68585 $ */ public interface Advised extends InstanceAdvised { /** * Returns the manager, also known as advisor, of the weaved class. * * @return the advisor of the weaved class. Usually this just returns * a {@link ClassAdvisor}. */ public Advisor _getAdvisor(); }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/WeavingStrategySupport.java0000644000175000017500000000421511145122062033232 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; /** * * @author Stale W. Pedersen * @author Kabir Khan * @version $Revision: */ public abstract class WeavingStrategySupport implements WeavingStrategy { // indicates that the transformation process has begun private static boolean transformationStarted = false; private static ThreadLocal REENTRY = new ThreadLocal() { protected Boolean initialValue() { return Boolean.FALSE; } }; /** * Are we re-entering? * * @return true if re-entry, false otherwise. */ protected static boolean isReEntry() { return REENTRY.get().booleanValue(); } /** * Set the re-entry flag. */ protected static void setReEntry() { REENTRY.set(Boolean.TRUE); } /** * Clear the re-entry flag. */ protected static void clearReEntry() { REENTRY.set(Boolean.FALSE); } protected static boolean transformationStarted() { return transformationStarted; } protected void setTransformationStarted() { transformationStarted = true; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/InterceptionMarkers.java0000644000175000017500000000676111145122056032515 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.util.concurrent.ConcurrentHashMap; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class InterceptionMarkers { protected final ConcurrentHashMap convertableReference = new ConcurrentHashMap(); protected final ConcurrentHashMap hasFieldInterception = new ConcurrentHashMap(); protected final ConcurrentHashMap hasConstructorInterception = new ConcurrentHashMap(); protected final ConcurrentHashMap skipConvertableReference = new ConcurrentHashMap(); protected final ConcurrentHashMap skipFieldInterception = new ConcurrentHashMap(); protected final ConcurrentHashMap skipConstructorInterception = new ConcurrentHashMap(); public void addConstructionInterceptionMarker(String classname) { skipConstructorInterception.remove(classname); skipConvertableReference.remove(classname); hasConstructorInterception.put(classname, classname); convertableReference.put(classname, classname); } public void addFieldInterceptionMarker(String classname) { skipFieldInterception.remove(classname); skipConvertableReference.remove(classname); hasFieldInterception.put(classname, classname); convertableReference.put(classname, classname); } public void skipReference(String classname) { skipConvertableReference.put(classname, classname); } public boolean shouldSkipConstruction(String classname) { return !(hasConstructorInterception.containsKey(classname) || !skipConstructorInterception.containsKey(classname)); //return false; } public boolean shouldSkipFieldAccess(String classname) { return !(hasFieldInterception.containsKey(classname) || !skipFieldInterception.containsKey(classname)); //return false; } public void skipConstruction(String classname) { skipConstructorInterception.put(classname, classname); } public void skipFieldAccess(String classname) { skipFieldInterception.put(classname, classname); } public boolean convertReference(String classname) { return !skipConvertableReference.containsKey(classname) || convertableReference.containsKey(classname); //return true; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/CFlowDef.java0000644000175000017500000000240411145122066030145 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; /** * Created by IntelliJ IDEA. * User: Kab * Date: 04-Oct-2004 * Time: 18:40:22 * To change this template use File | Settings | File Templates. */ public @interface CFlowDef { boolean called(); String expr(); } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/0000755000175000017500000000000011254651544026622 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/SecurityActions.java0000644000175000017500000000344611145122056032612 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.hook; import java.security.AccessController; import java.security.PrivilegedAction; /** * SecurityActions. * * @author Adrian Brock * @version $Revision: 1.1 $ */ public class SecurityActions { public static class GetContextClassLoaderAction implements PrivilegedAction { public static GetContextClassLoaderAction INSTANCE = new GetContextClassLoaderAction(); public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } } static ClassLoader getContextClassLoader() { if (System.getSecurityManager() == null) return Thread.currentThread().getContextClassLoader(); else return AccessController.doPrivileged(GetContextClassLoaderAction.INSTANCE); } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/GeneratePluggableInstrumentedClassLoader.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/GeneratePluggableInstru0000644000175000017500000001257311145122056033325 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.hook; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.Modifier; import javassist.NotFoundException; /** * Generate the instrumented version of the classloader and store it in the filesystem. * * @author kevin */ public class GeneratePluggableInstrumentedClassLoader { private static void declare5(CtClass clazz, CtMethod method) throws NotFoundException, CannotCompileException { method.setName("wrappedDefineClass"); CtMethod wrapper = CtNewMethod.make(Modifier.PROTECTED, method.getReturnType(), "defineClass", method.getParameterTypes(), method.getExceptionTypes(), null, clazz); String code = "{" + " byte[] newBytes = org.jboss.aop.hook.JDK14TransformerManager.transform($0, $1, $2) ;" + " if (newBytes != (byte[])null) {" + " return wrappedDefineClass($1, newBytes, 0, newBytes.length, $5); " + " } else {" + " return wrappedDefineClass($1, $2, $3, $4, $5); " + " }" + "}"; wrapper.setBody(code); clazz.addMethod(wrapper); } /** * Get the instrumented version of the class loader. * * @return The instrumented version of the class loader. * @throws javassist.NotFoundException if the class loader cannot be found. * @throws javassist.CannotCompileException * if the class cannot be compiled. * @throws java.io.IOException If the class bytecodes cannot be obtained. */ public static byte[] getInstrumentedClassLoader() throws NotFoundException, IOException, CannotCompileException { ClassPool classpool = ClassPool.getDefault(); classpool = ClassPool.getDefault(); ClassLoader cl = SecurityActions.getContextClassLoader(); classpool.insertClassPath(new LoaderClassPath(cl)); final CtClass clazz = classpool.get(ClassLoader.class.getName()); CtMethod[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals("defineClass")) { if (methods[i].getParameterTypes().length == 5 && methods[i].getParameterTypes()[1].isArray()) { declare5(clazz, methods[i]); } } } return clazz.toBytecode(); } /** * Store the instrumented classloader in the filesystem. * * @param args The filename as the first argument. */ public static void main(final String[] args) { if (args.length != 1) { System.err.println("Usage: java " + GeneratePluggableInstrumentedClassLoader.class.getName() + " "); System.exit(1); } final String filename = args[0] + File.separatorChar + "java" + File.separatorChar + "lang" + File.separatorChar + "ClassLoader.class"; final File file = new File(filename); if (file.exists()) { if (!file.canWrite()) { System.err.println("Cannot write to existing file: " + file.getAbsolutePath()); System.exit(2); } } else { final File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } if (!dir.canWrite()) { System.err.println("Cannot write to parent directory: " + dir.getAbsolutePath()); } } final byte[] bytes; try { bytes = getInstrumentedClassLoader(); } catch (final Throwable th) { System.err.println("Unexpected exception caught during instrumentation: " + th.getMessage()); th.printStackTrace(System.err); System.exit(5); return; } try { final FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } catch (final IOException ioe) { System.err.println("Unexpected exception caught while writing class file: " + ioe.getMessage()); ioe.printStackTrace(System.err); System.exit(6); } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/JDK14Transformer.java0000644000175000017500000000242111145122056032452 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.hook; /** * Comment * * @author Bill Burke * @version $Revision: 37406 $ */ public interface JDK14Transformer { public byte[] transform(ClassLoader loader, String classname, byte[] classBytes); } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/GenerateInstrumentedClassLoader.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/GenerateInstrumentedCla0000644000175000017500000001472311145122056033316 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.hook; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.Modifier; import javassist.NotFoundException; /** * Generate the instrumented version of the classloader and store it in the filesystem. * * @author kevin */ public class GenerateInstrumentedClassLoader { private static void declare5(CtClass clazz, CtMethod method) throws NotFoundException, CannotCompileException { method.setName("wrappedDefineClass"); CtMethod wrapper = CtNewMethod.make(Modifier.PROTECTED, method.getReturnType(), "defineClass", method.getParameterTypes(), method.getExceptionTypes(), null, clazz); String code = "{" + " if (!$1.startsWith(\"org.jboss.aop.\") &&" // + " !$1.endsWith(\"$aop\") &&" + " !$1.startsWith(\"javassist\") &&" + " !$1.startsWith(\"org.jboss.util.\") &&" + " !$1.startsWith(\"gnu.trove.\") &&" + " !$1.startsWith(\"EDU.oswego.cs.dl.util.concurrent.\") &&" // System classes + " !$1.startsWith(\"org.apache.crimson\") &&" + " !$1.startsWith(\"org.apache.xalan\") &&" + " !$1.startsWith(\"org.apache.xml\") &&" + " !$1.startsWith(\"org.apache.xpath\") &&" + " !$1.startsWith(\"org.ietf.\") &&" + " !$1.startsWith(\"org.omg.\") &&" + " !$1.startsWith(\"org.w3c.\") &&" + " !$1.startsWith(\"org.xml.sax.\") &&" + " !$1.startsWith(\"sunw.\") &&" + " !$1.startsWith(\"sun.\") &&" + " !$1.startsWith(\"java.\") &&" + " !$1.startsWith(\"javax.\") &&" + " !$1.startsWith(\"com.sun.\") &&" + " !$1.startsWith(\"$Proxy\")) {" + " byte[] newBytes = org.jboss.aop.AspectManager.instance().translate($1, $0, $2) ;" + " if (newBytes != (byte[])null) {" + " return wrappedDefineClass($1, newBytes, 0, newBytes.length, $5); " + " }}" + " return wrappedDefineClass($1, $2, $3, $4, $5); " + " " + "}"; wrapper.setBody(code); clazz.addMethod(wrapper); } /** * Get the instrumented version of the class loader. * * @return The instrumented version of the class loader. * @throws javassist.NotFoundException if the class loader cannot be found. * @throws javassist.CannotCompileException * if the class cannot be compiled. * @throws java.io.IOException If the class bytecodes cannot be obtained. */ public static byte[] getInstrumentedClassLoader() throws NotFoundException, IOException, CannotCompileException { ClassPool classpool = ClassPool.getDefault(); classpool = ClassPool.getDefault(); ClassLoader cl = SecurityActions.getContextClassLoader(); classpool.insertClassPath(new LoaderClassPath(cl)); final CtClass clazz = classpool.get(ClassLoader.class.getName()); CtMethod[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals("defineClass")) { if (methods[i].getParameterTypes().length == 5 && methods[i].getParameterTypes()[1].isArray()) { declare5(clazz, methods[i]); } } } return clazz.toBytecode(); } /** * Store the instrumented classloader in the filesystem. * * @param args The filename as the first argument. */ public static void main(final String[] args) { if (args.length != 1) { System.err.println("Usage: java " + GeneratePluggableInstrumentedClassLoader.class.getName() + " "); System.exit(1); } final String filename = args[0] + File.separatorChar + "java" + File.separatorChar + "lang" + File.separatorChar + "ClassLoader.class"; final File file = new File(filename); if (file.exists()) { if (!file.canWrite()) { System.err.println("Cannot write to existing file: " + file.getAbsolutePath()); System.exit(2); } } else { final File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } if (!dir.canWrite()) { System.err.println("Cannot write to parent directory: " + dir.getAbsolutePath()); } } final byte[] bytes; try { bytes = getInstrumentedClassLoader(); } catch (final Throwable th) { System.err.println("Unexpected exception caught during instrumentation: " + th.getMessage()); th.printStackTrace(System.err); System.exit(5); return; } try { final FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } catch (final IOException ioe) { System.err.println("Unexpected exception caught while writing class file: " + ioe.getMessage()); ioe.printStackTrace(System.err); System.exit(6); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/JDK14TransformerManager.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/hook/JDK14TransformerManager0000644000175000017500000000516511145122064033034 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.hook; /** * Comment * * @author Bill Burke * @version $Revision: 70481 $ */ public class JDK14TransformerManager { public static JDK14Transformer transformer; public static byte[] transform(ClassLoader loader, String className, byte[] classBytes) { if (transformer == null) return null; if (isNonAdvisableClassName(className)) return null; return transformer.transform(loader, className, classBytes); } public static boolean isNonAdvisableClassName(String classname) { return (classname.startsWith("org.jboss.aop.") || classname.endsWith("$aop") || classname.startsWith("javassist") || classname.startsWith("org.jboss.util.") || classname.startsWith("gnu.trove.") || classname.startsWith("EDU.oswego.cs.dl.util.concurrent.") || // System classes classname.startsWith("org.apache.crimson") || classname.startsWith("org.apache.xalan") || classname.startsWith("org.apache.xml") || classname.startsWith("org.apache.xpath") || classname.startsWith("org.ietf.") || classname.startsWith("org.omg.") || classname.startsWith("org.w3c.") || classname.startsWith("org.xml.sax.") || classname.startsWith("sunw.") || classname.startsWith("sun.") || classname.startsWith("java.") || classname.startsWith("javax.") || classname.startsWith("com.sun.") || classname.startsWith("junit") || classname.startsWith("jrockit.") || classname.startsWith("com.bea.vm.") || classname.startsWith("$Proxy") ); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/ClassInstanceAdvisor.java0000644000175000017500000003015211145122066032577 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.jboss.aop.advice.AdviceStack; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.joinpoint.Joinpoint; import org.jboss.aop.metadata.SimpleMetaData; /** * Holds an object instance's metadata and attached interceptors * * @author Bill Burke * @version $Revision: 82580 $ */ public class ClassInstanceAdvisor implements InstanceAdvisor, java.io.Serializable { static final long serialVersionUID = -3057976129116723527L; protected ArrayList insertedInterceptors = null; protected ArrayList appendedInterceptors = null; protected WeakReference instanceRef; protected transient WeakReference classAdvisorRef; public boolean hasInstanceAspects = false; protected Map stacks = null; /** * aspects is a weak hash map of AspectDefinitions so that perinstance advices can be undeployed/redeployed */ private InterceptorChainObserver interceptorChainObserver; InstanceAdvisorDelegate delegate; public ClassInstanceAdvisor() { delegate = new InstanceAdvisorDelegate(null, this); delegate.initialize(); } public ClassInstanceAdvisor(Object obj) { this.instanceRef = new WeakReference(obj); if (obj instanceof Advised) { Advised advised = (Advised) obj; Advisor advizor = advised._getAdvisor(); setAdvisorAndInitialise(advizor); } } public ClassInstanceAdvisor(Advisor advizor) { setAdvisorAndInitialise(advizor); } private void setAdvisorAndInitialise(Advisor advizor) { this.classAdvisorRef = new WeakReference(advizor); if (advizor instanceof ClassAdvisor) { delegate = new InstanceAdvisorDelegate(advizor, this); delegate.initialize(); this.interceptorChainObserver = ((ClassAdvisor) advizor).getInterceptorChainObserver(); } } public boolean hasInterceptors() { return appendedInterceptors != null || insertedInterceptors != null; } public Object getPerInstanceAspect(String def) { return delegate.getPerInstanceAspect(def); } public Object getPerInstanceAspect(AspectDefinition def) { return delegate.getPerInstanceAspect(def); } public Object getPerInstanceJoinpointAspect(Joinpoint joinpoint, AspectDefinition def) { return delegate.getPerInstanceJoinpointAspect(joinpoint, def); } public SimpleMetaData getMetaData() { return delegate.getMetaData(); } public Interceptor[] getInterceptors() { ArrayList newlist = new ArrayList(); if (insertedInterceptors != null) newlist.addAll(insertedInterceptors); if (appendedInterceptors != null) newlist.addAll(appendedInterceptors); return newlist.toArray(new Interceptor[newlist.size()]); } /** * Called by the advisor */ public Interceptor[] getInterceptors(Interceptor[] advisorChain) { if (insertedInterceptors == null && appendedInterceptors == null) return advisorChain; ArrayList newlist = new ArrayList(); if (insertedInterceptors != null) newlist.addAll(insertedInterceptors); if (advisorChain != null) { newlist.addAll(Arrays.asList(advisorChain)); } if (appendedInterceptors != null) newlist.addAll(appendedInterceptors); return newlist.toArray(new Interceptor[newlist.size()]); } public void insertInterceptor(int index, Interceptor interceptor) { ArrayList newList = new ArrayList(); if (insertedInterceptors != null) { newList.addAll(insertedInterceptors); } newList.add(index, interceptor); insertedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } public void insertInterceptor(Interceptor interceptor) { ArrayList newList = new ArrayList(); if (insertedInterceptors != null) { newList.addAll(insertedInterceptors); } newList.add(interceptor); insertedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } public void appendInterceptor(Interceptor interceptor) { ArrayList newList = new ArrayList(); if (appendedInterceptors != null) { newList.addAll(appendedInterceptors); } newList.add(interceptor); appendedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } public void appendInterceptor(int index, Interceptor interceptor) { ArrayList newList = new ArrayList(); if (appendedInterceptors != null) { newList.addAll(appendedInterceptors); } newList.add(index, interceptor); appendedInterceptors = newList; hasInstanceAspects = true; if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorAdded(this); } } /** * This will not remove interceptor pointcuts! You will have to do this through AspectManager */ public void removeInterceptor(String name) { int interceptorsRemoved = internalRemoveInterceptor(name); if (interceptorChainObserver != null) { interceptorChainObserver.instanceInterceptorsRemoved(this, interceptorsRemoved); } } /** * @param name * @return */ private int internalRemoveInterceptor(String name) { int interceptorsRemoved = 0; if (insertedInterceptors != null) { for (int i = 0; i < insertedInterceptors.size(); i++) { Interceptor interceptor = insertedInterceptors.get(i); if (interceptor.getName().equals(name)) { ArrayList newList = new ArrayList(); newList.addAll(insertedInterceptors); newList.remove(i); insertedInterceptors = newList; interceptorsRemoved ++; } } } if (appendedInterceptors != null) { for (int i = 0; i < appendedInterceptors.size(); i++) { Interceptor interceptor = appendedInterceptors.get(i); if (interceptor.getName().equals(name)) { ArrayList newList = new ArrayList(); newList.addAll(appendedInterceptors); newList.remove(i); appendedInterceptors = newList; interceptorsRemoved ++; } } } hasInstanceAspects = ((insertedInterceptors != null && insertedInterceptors.size() > 0) || (appendedInterceptors != null && appendedInterceptors.size() > 0)); return interceptorsRemoved; } public final boolean hasAspects() { return hasInstanceAspects; } public void insertInterceptorStack(String stackName) { AdviceStack stack = AspectManager.instance().getAdviceStack(stackName); if (stack == null) throw new RuntimeException("Stack " + stackName + " not found."); ClassAdvisor classAdvisor = null; if (getInstance() instanceof Advised) { Advised advised = (Advised) getInstance(); classAdvisor = ((ClassAdvisor) advised._getAdvisor()); } Interceptor[] interceptors = stack.createInterceptors(classAdvisor, null); for (Interceptor interceptor: interceptors) { insertInterceptor(interceptor); } if (this.stacks == null) { this.stacks = new HashMap(); } this.stacks.put(stackName, interceptors); if (interceptorChainObserver != null) { this.interceptorChainObserver.instanceInterceptorsAdded(this, interceptors.length); } } public void appendInterceptorStack(String stackName) { AdviceStack stack = AspectManager.instance().getAdviceStack(stackName); if (stack == null) throw new RuntimeException("Stack " + stackName + " not found."); ClassAdvisor classAdvisor = null; if (getInstance() instanceof Advised) { Advised advised = (Advised) getInstance(); classAdvisor = ((ClassAdvisor) advised._getAdvisor()); } Interceptor[] interceptors = stack.createInterceptors(classAdvisor, null); for (Interceptor interceptor: interceptors) { appendInterceptor(interceptor); } if (this.stacks == null) { this.stacks = new HashMap(); } this.stacks.put(stackName, interceptors); if (interceptorChainObserver != null) { this.interceptorChainObserver.instanceInterceptorsAdded(this, interceptors.length); } } public void removeInterceptorStack(String stackName) { Interceptor[] interceptors = stacks.remove(stackName); if (interceptors == null) { AdviceStack stack = AspectManager.instance().getAdviceStack(stackName); if (stack == null) throw new RuntimeException("Stack " + stackName + " not found."); return; } int interceptorsRemoved = 0; for (Interceptor interceptor: interceptors) { interceptorsRemoved += internalRemoveInterceptor(interceptor.getName()); } if (interceptorChainObserver != null) { this.interceptorChainObserver.instanceInterceptorsRemoved(this, interceptorsRemoved); } } public Domain getDomain() { throw new RuntimeException("getDomain() is only available when you use weaving with generated advisors"); } /** * Added to notify interceptor chain observer of interceptor chain garbage collection. */ protected void finalize() { Advisor advisor = getClassAdvisor(); // gc'ed if (advisor == null) { return; } Class advisedClass = advisor.getClazz(); // gc'ed if (advisedClass == null) { return; } ClassLoader classLoader = SecurityActions.getClassLoader(advisedClass); if (this.interceptorChainObserver == null || !AspectManager.getRegisteredCLs().containsKey(classLoader)) { return; } this.interceptorChainObserver.allInstanceInterceptorsRemoved(this); } private Advisor getClassAdvisor() { if (classAdvisorRef != null) { return classAdvisorRef.get(); } return null; } public Object getInstance() { if (instanceRef != null) { return instanceRef.get(); } return null; } }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/0000755000175000017500000000000011145122056030664 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/lifecycle/0000755000175000017500000000000011145122064032622 5ustar twernertwerner././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/lifecycle/LifecycleCallbackBinding.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/lifecycle/Lif0000644000175000017500000001020511145122060033251 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.microcontainer.lifecycle; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.jboss.aop.Advisor; import org.jboss.aop.pointcut.TypeMatcher; import org.jboss.aop.pointcut.Util; import org.jboss.aop.pointcut.ast.ASTStart; import org.jboss.aop.pointcut.ast.ClassExpression; import org.jboss.aop.pointcut.ast.TypeExpressionParser; /** * A binding for callbacks for when a MC bean reaches a certain state * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class LifecycleCallbackBinding { /** * The name of this binding */ protected String name; /** * The class to match */ protected ClassExpression classes; /** * A type expression picking out the classes to apply this to */ protected ASTStart ast; /** * A list of beans */ List lifecycleCallbackDefinitions = new ArrayList(); /** * This will be an instance of org.jboss.dependency.spi.ControllerState from the MC project */ Object controllerState; public LifecycleCallbackBinding(String name, String classString, String typeExpression, Object controllerState) throws Exception { this.name = name; if (classString == null && typeExpression == null) { throw new RuntimeException("Need either classString or typeExpression"); } if (classString != null && typeExpression != null) { throw new RuntimeException("Should not use both classString and typeExpression"); } if (classString != null) { this.classes = new ClassExpression(classString); } else if (typeExpression != null) { this.ast = new TypeExpressionParser(new StringReader(typeExpression)).Start(); } this.controllerState = controllerState; } public String getName() { return name; } public void addLifecycleCallback(String bean, String installMethod, String uninstallMethod) { lifecycleCallbackDefinitions.add(new LifecycleCallbackDefinition(bean, installMethod, uninstallMethod)); } public List getLifecycleCallbacks() { return lifecycleCallbackDefinitions; } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof LifecycleCallbackBinding)) return false; return ((LifecycleCallbackBinding) obj).getName().equals(name); } public int hashCode() { return name.hashCode(); } public boolean matches(Advisor advisor, Class clazz) { if (classes != null) { return Util.matchesClassExpr(classes, clazz, advisor); } else { TypeMatcher matcher = new TypeMatcher(advisor, clazz); return ((Boolean) ast.jjtAccept(matcher, null)).booleanValue(); } } public Object getControllerState() { return controllerState; } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/lifecycle/LifecycleManager.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/lifecycle/Lif0000644000175000017500000000457311145122064033270 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.microcontainer.lifecycle; import java.util.LinkedHashMap; import java.util.Map; import org.jboss.aop.AspectManager; import org.jboss.aop.advice.AspectDefinition; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class LifecycleManager { AspectManager manager; Map lifecycles = new LinkedHashMap(); Map lifecycleBindings = new LinkedHashMap(); public LifecycleManager(AspectManager manager) { this.manager = manager; } public void addLifecycleDefinition(AspectDefinition def) { AspectDefinition old = lifecycles.put(def.getName(), def); if (old != null) { old.undeploy(); } } public void removeLifecycleDefinition(String name) { lifecycles.remove(name); } public void addLifecycleBinding(LifecycleCallbackBinding lifecycleBinding) { lifecycleBindings.put(lifecycleBinding.getName(), lifecycleBinding); } public void removeLifecycleBinding(String name) { lifecycleBindings.remove(name); } public Map getLifecycleBindings() { return lifecycleBindings; } } ././@LongLink0000000000000000000000000000020200000000000011557 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/lifecycle/LifecycleCallbackDefinition.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/microcontainer/lifecycle/Lif0000644000175000017500000000377511145122056033274 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.microcontainer.lifecycle; /** * Represents a bean that is used for callbacks * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class LifecycleCallbackDefinition { /** * The name of the bean implementing the callback */ private String bean; /** * The method to call on installation */ private String installMethod; /** * The method to call on uninstallation */ private String uninstallMethod; public LifecycleCallbackDefinition(String bean, String installMethod, String uninstallMethod) { this.bean = bean; this.installMethod = installMethod; this.uninstallMethod = uninstallMethod; } public String getBean() { return bean; } public String getInstallMethod() { return installMethod; } public String getUninstallMethod() { return uninstallMethod; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/reflection/0000755000175000017500000000000011145122064030001 5ustar twernertwerner././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/reflection/ReflectionAspect.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/reflection/ReflectionAspect.0000644000175000017500000016132411145122064033243 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.reflection; import gnu.trove.TLongObjectHashMap; import org.jboss.aop.Advised; import org.jboss.aop.AspectManager; import org.jboss.aop.ClassAdvisor; import org.jboss.aop.ConByConInfo; import org.jboss.aop.ConByMethodInfo; import org.jboss.aop.ConstructorInfo; import org.jboss.aop.FieldInfo; import org.jboss.aop.MethodByConInfo; import org.jboss.aop.MethodByMethodInfo; import org.jboss.aop.instrument.Untransformable; import org.jboss.aop.joinpoint.Invocation; import org.jboss.aop.joinpoint.MethodCalledByConstructorInvocation; import org.jboss.aop.joinpoint.MethodCalledByMethodInvocation; import org.jboss.aop.util.MethodHashing; import org.jboss.aop.util.ReflectUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Kabir Khan *

* Aspect to intercept calls to the reflection API. Calls to * Class.newInstance(), Field.setXXX(), Field.getXXX(), Constructor.newInstance() * don't get intercepted even though the underlying constructor/field * might have an advice associated with it. This class adds advices to help intercept these * calls and attach to the original chains on the caller or target object. Method.invoke() * works for chains on the target object "out of the box", but bypasses caller chains. *

*
*
* Also, Class.getMethods(), Class.getDeclaredMethods(), Class.getInterfaces(), * and Class.getDeclaredFields() return extra methods/interfaces/fields added * by the AOP framework. The aspects contained here cleans this information. */ public class ReflectionAspect { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- private static Pattern fieldGetPattern = Pattern.compile("get(|Boolean|Byte|Char|Double|Float|Int|Long|Short)?"); private static Pattern fieldSetPattern = Pattern.compile("set(|Boolean|Byte|Char|Double|Float|Int|Long|Short)?"); // Constructors -------------------------------------------------- public ReflectionAspect() { } // Public -------------------------------------------------------- /** * Advice for calls to Class.newInstance() and Constructor.newInstance(). Intended use is for * caller pointcuts. If you wish to handle the intercepted calls, override interceptConstructor. * * @param invocation * @return result of invocation * @throws Throwable * @see ReflectionAspect#interceptConstructor(Invocation, Constructor, Object[]) */ public Object interceptNewInstance(MethodCalledByConstructorInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptNewInstance(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Class.newInstance() and Constructor.newInstance(). Intended use is for * caller pointcuts. If you wish to handle the intercepted calls, override interceptConstructor. * * @param invocation * @return result of invocation * @throws Throwable * @see ReflectionAspect#interceptConstructor(Invocation, Constructor, Object[]) */ public Object interceptNewInstance(MethodCalledByMethodInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptNewInstance(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Method.invoke(). Intended use is for * caller pointcuts. If you wish to handle the intercepted calls, override interceptMethod. * * @param invocation * @return result of invocation * @throws Throwable * @see ReflectionAspect#interceptMethod(Invocation, Object, Method, Object[]) */ public Object interceptMethodInvoke(MethodCalledByConstructorInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptMethodInvoke(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Class.newInstance() and Constructor.newInstance(). Intended use is for * caller pointcuts. If you wish to handle the intercepted calls, override interceptMethod. * * @param invocation * @return result of invocation * @throws Throwable * @see ReflectionAspect#interceptMethod(Invocation, Object, Method, Object[]) */ public Object interceptMethodInvoke(MethodCalledByMethodInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptMethodInvoke(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Field.setXXX(). Intended use is for caller pointcuts. If you wish to handle * the intercepted calls, override interceptFieldWrite. * * @param invocation * @return result of invocation * @throws Throwable * @see ReflectionAspect#interceptFieldWrite(Invocation, Field, Object, Object) */ public Object interceptFieldSet(MethodCalledByConstructorInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptFieldSet(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Field.setXXX(). Intended use is for caller pointcuts. If you wish to handle * the intercepted calls, override interceptFieldWrite. * * @param invocation * @return result of invocation * @throws Throwable * @see ReflectionAspect#interceptFieldWrite(Invocation, Field, Object, Object) */ public Object interceptFieldSet(MethodCalledByMethodInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptFieldSet(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Field.getXXX(). Intended use is for caller pointcuts. If you wish to handle * the intercepted calls, override interceptFieldRead. * * @param invocation * @return The value of the field (or whatever you choose) * @throws Throwable * @see ReflectionAspect#interceptFieldRead(Invocation, Field, Object) */ public Object interceptFieldGet(MethodCalledByConstructorInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptFieldGet(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Field.getXXX(). Intended use is for caller pointcuts. If you wish to handle * the intercepted calls, override interceptFieldRead. * * @param invocation * @return The value of the field (or whatever you choose) * @throws Throwable * @see ReflectionAspect#interceptFieldRead(Invocation, Field, Object) */ public Object interceptFieldGet(MethodCalledByMethodInvocation invocation) throws Throwable { Method reflectionMethod = invocation.getCalledMethod(); Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptFieldGet(invocation, reflectionMethod, targetObject, args); } /** * Advice for calls to Class.getDeclaredMethods(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method[] containing the declared methods of the class * @throws Throwable * @see Class#getDeclaredMethods()() */ public final Object interceptGetDeclaredMethods(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetDeclaredMethods((Class) targetObject); } /** * Advice for calls to Class.getDeclaredMethods(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method[] containing the declared methods of the class * @throws Throwable * @see Class#getDeclaredMethods()() */ public final Object interceptGetDeclaredMethods(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetDeclaredMethods((Class) targetObject); } /** * Advice for calls to Class.getDeclaredMethod(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method the declared method * @throws Throwable * @see Class#getDeclaredMethod()() */ public final Object interceptGetDeclaredMethod(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptGetDeclaredMethod((Class) targetObject, args); } /** * Advice for calls to Class.getDeclaredMethod(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method the declared method * @throws Throwable * @see Class#getDeclaredMethod()() */ public final Object interceptGetDeclaredMethod(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptGetDeclaredMethod((Class) targetObject, args); } /** * Advice for calls to Class.getDeclaredMethod(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method[] The methods of the class * @throws Throwable * @see Class#getDeclaredMethod()() */ public final Object interceptGetMethods(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetMethods((Class) targetObject); } /** * Advice for calls to Class.getMethods(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method[] The methods of the class * @throws Throwable * @see Class#getMethods()() */ public final Object interceptGetMethods(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetMethods((Class) targetObject); } /** * Advice for calls to Class.getMethod(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method The method * @throws Throwable * @see Class#getDeclaredMethod()() */ public final Object interceptGetMethod(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptGetMethod((Class) targetObject, args); } /** * Advice for calls to Class.getMethod(). Cleans methods that get added to the * class by the AOP framework (Methods introduced by introductions/mixin classes will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Method The method * @throws Throwable * @see Class#getDeclaredMethod()() */ public final Object interceptGetMethod(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptGetMethod((Class) targetObject, args); } /** * Advice for calls to Class.getInterfaces(). Cleans interfaces that get added to the * class by the AOP framework. (Interfaces introduced by introductions will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.Class[] containing the interfaces of the class * @throws Throwable * @see Class#getInterfaces() */ public final Object interceptGetInterfaces(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetInterfaces((Class) targetObject); } /** * Advice for calls to Class.getInterfaces(). Cleans interfaces that get added to the * class by the AOP framework. (Interfaces introduced by introductions will * still be returned). Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.Class[] containing the interfaces of the class * @throws Throwable * @see Class#getInterfaces() */ public final Object interceptGetInterfaces(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetInterfaces((Class) targetObject); } /** * Advice for calls to Class.getDeclaredClasses(). Cleans inner classes that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.Class[] containing the Class objects representing inner classes of the class * @throws Throwable * @see Class#getDeclaredClasses() */ public final Object interceptGetDeclaredClasses(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetDeclaredClasses((Class) targetObject); } /** * Advice for calls to Class.getDeclaredClasses(). Cleans inner classes that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.Class[] containing the Class objects representing inner classes of the class * @throws Throwable * @see Class#getDeclaredClasses() */ public final Object interceptGetDeclaredClasses(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetDeclaredClasses((Class) targetObject); } /** * Advice for calls to Class.getClasses(). Cleans inner classes that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * Extra stuff only seems to get returned when using JRockit * * @param invocation The invocation * @return java.lang.Class[] containing the Class objects representing inner classes of the class * @throws Throwable * @see Class#getClasses() */ public final Object interceptGetClasses(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetClasses((Class) targetObject); } /** * Advice for calls to Class.getClasses(). Cleans inner classes that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * Extra stuff only seems to get returned when using JRockit * * @param invocation The invocation * @return java.lang.Class[] containing the Class objects representing inner classes of the class * @throws Throwable * @see Class#getDeclaredClasses() */ public final Object interceptGetClasses(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetClasses((Class) targetObject); } /** * Advice for calls to Class.getDeclaredFields(). Cleans fields that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Field[] containing the Fields of the class * @throws Throwable * @see Class#getDeclaredClasses() */ public final Object interceptGetDeclaredFields(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetDeclaredFields((Class) targetObject); } /** * Advice for calls to Class.getDeclaredFields(). Cleans fields that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Field[] containing the Fields of the class * @throws Throwable * @see Class#getDeclaredFields() */ public final Object interceptGetDeclaredFields(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); return interceptGetDeclaredFields((Class) targetObject); } /** * Advice for calls to Class.getDeclaredField(). Cleans fields that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Field The Field * @throws Throwable * @see Class#getDeclaredField() */ public final Object interceptGetDeclaredField(MethodCalledByConstructorInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptGetDeclaredField((Class) targetObject, args); } /** * Advice for calls to Class.getDeclaredField(). Cleans fields that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Field[] The Field * @throws Throwable * @see Class#getDeclaredField() */ public final Object interceptGetDeclaredField(MethodCalledByMethodInvocation invocation) throws Throwable { Object targetObject = invocation.getTargetObject(); Object[] args = invocation.getArguments(); return interceptGetDeclaredField((Class) targetObject, args); } /** * Advice for calls to Class.getFields(). Cleans fields that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Field[] containing the Fields of the class * @throws Throwable * @see Class#getFields() */ public final Object interceptGetFields(MethodCalledByConstructorInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } /** * Advice for calls to Class.getFields(). Cleans fields that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Field[] containing the Fields of the class * @throws Throwable * @see Class#getFields() */ public final Object interceptGetFields(MethodCalledByMethodInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } /** * Advice for calls to Class.getDeclaredConstructors(). Cleans constructors that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Constructor[] containing the Constructors of the class * @throws Throwable * @see Class#getDeclaredConstructors() */ public final Object interceptGetDeclaredConstructors(MethodCalledByConstructorInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } /** * Advice for calls to Class.getDeclaredConstructors(). Cleans constructors that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Constructor[] containing the Constructors of the class * @throws Throwable * @see Class#getDeclaredConstructors() */ public final Object interceptGetDeclaredConstructors(MethodCalledByMethodInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } /** * Advice for calls to Class.getDeclaredConstructor(). Cleans constructors that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Constructor[] The constructor * @throws Throwable * @see Class#getFields() */ public final Object interceptGetDeclaredConstructor(MethodCalledByConstructorInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } /** * Advice for calls to Class.getDeclaredConstructor(). Cleans constructors that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.reflect.Constructor[] The constructor * @throws Throwable * @see Class#getFields() */ public final Object interceptGetDeclaredConstructor(MethodCalledByMethodInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } /** * Advice for calls to Class.getConstructors(). Cleans fields that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.Constructor[] containing the Constructors of the class * @throws Throwable * @see Class#getFields() */ public final Object interceptGetConstructors(MethodCalledByConstructorInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } /** * Advice for calls to Class.getConstructors(). Cleans constructors that get added to the * class by the AOP framework. Intended use is for caller pointcuts. * * @param invocation The invocation * @return java.lang.Constructor[] containing the Constructors of the class * @throws Throwable * @see Class#getFields() */ public final Object interceptGetConstructors(MethodCalledByMethodInvocation invocation) throws Throwable { //Nothing seems to get added return invocation.invokeNext(); } // Z implementation ---------------------------------------------- // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- /** * Overridable advice for a Constructor.newInstance() or Class.newInstance() call. * Default behaviour is to first try to attach to any caller advice chain. If that * does not exist, try to attach to the advice chains on the target object. And * if that does not exist to invoke the reflected constructor. * * @param invocation The invocation * @param constructor The field on which we are calling set * @param args The arguments for the constructor * @return The new instance * @throws Throwable */ protected Object interceptConstructor(Invocation invocation, Constructor constructor, Object[] args) throws Throwable { return invokeOriginalChainIfExists(invocation, constructor, args); } /** * Overridable advice for a Field.setXXX() call. * Default behaviour is to first try to attach to the advice chains on the target object. And * if that does not exist to invoke the reflected field read. * * @param invocation The invocation * @param field The field on which we are calling set * @param instance The instance on which we want to write a field * @return The value of the field (or whatever you choose) * @throws Throwable */ protected Object interceptFieldRead(Invocation invocation, Field field, Object instance) throws Throwable { return invokeOriginalChainIfExists(invocation, field, instance); } /** * Overridable advice for a Field.setXXX() call. * Default behaviour is to first try attach to the advice chains on the target object. And * if that does not exist to invoke the reflected field write. * * @param invocation The invocation * @param field The field on which we are calling set * @param instance The instance on which we want to read a field * @param arg The value we want to set the field to * @return result of invocation * @throws Throwable */ protected Object interceptFieldWrite(Invocation invocation, Field field, Object instance, Object arg) throws Throwable { return invokeOriginalChainIfExists(invocation, field, instance, arg); } /** * Overridable advice for a Method.invoke() call. * Default behaviour is to first try to attach to any caller advice chain. If that * does not exist, try to attach to the advice chains on the target object. And * if that does not exist to invoke the reflected method. * * @param invocation The invocation * @param method The method on which we are calling set * @param instance The instance on which we want to read a field * @param arg The value we want to set the field to * @return result of invocation * @throws Throwable */ protected Object interceptMethod(Invocation invocation, Method method, Object instance, Object[] args) throws Throwable { return invokeOriginalChainIfExists(invocation, method, instance, args); } // Private ------------------------------------------------------- private Object interceptNewInstance(Invocation invocation, Method reflectionMethod, Object targetObject, Object[] args) throws Throwable { Class reflectionClass = targetObject.getClass(); if (reflectionClass.equals(Class.class)) { //For our purposes Class.newInstance() can be made into a call to the empty constructor Constructor constructor = ((Class) targetObject).getConstructor(new Class[0]); return interceptConstructor(invocation, constructor, args); } else if (reflectionClass.equals(Constructor.class)) { if (reflectionMethod.getName().equals("newInstance")) { //Object newObject = args[0]; Object[] constructorArgs; int length = args.length; if (length < 1) { constructorArgs = new Object[0]; } else { constructorArgs = (Object[]) args[0]; } Constructor constructor = (Constructor) targetObject; return interceptConstructor(invocation, constructor, constructorArgs); } } return invocation.invokeNext(); } private Object interceptMethodInvoke(Invocation invocation, Method reflectionMethod, Object targetObject, Object[] args) throws Throwable { Method method = (Method) invocation.getTargetObject(); if (reflectionMethod.getName().equals("invoke")) { Object instance = args[0]; return interceptMethod(invocation, method, instance, (Object[]) args[1]); } return invocation.invokeNext(); } private Class[] interceptGetInterfaces(Class clazz) { Class[] interfaces = clazz.getInterfaces(); ArrayList> cleanedInterfaces = new ArrayList>(interfaces.length); for (int i = 0; i < interfaces.length; i++) { if (!interfaces[i].equals(Advised.class)) { cleanedInterfaces.add(interfaces[i]); } } return cleanedInterfaces.toArray(new Class[cleanedInterfaces.size()]); } private Object interceptFieldSet(Invocation invocation, Method reflectionMethod, Object targetObject, Object[] args) throws Throwable { Field field = (Field) invocation.getTargetObject(); Matcher m = fieldSetPattern.matcher(reflectionMethod.getName()); if (m.matches()) { Object instance = args[0]; return interceptFieldWrite(invocation, field, instance, args[1]); } return invocation.invokeNext(); } private Object interceptFieldGet(Invocation invocation, Method reflectionMethod, Object targetObject, Object[] args) throws Throwable { Field field = (Field) invocation.getTargetObject(); Matcher m = fieldGetPattern.matcher(reflectionMethod.getName()); if (m.matches()) { Object instance = args[0]; return interceptFieldRead(invocation, field, instance); } return invocation.invokeNext(); } private Method[] interceptGetDeclaredMethods(Class clazz) { ClassAdvisor advisor = AspectManager.instance().getAdvisorIfAdvised(clazz); if (advisor == null) { return getDeclaredMethods(clazz); } else { Object[] advisedMethods = advisor.getAdvisedMethods().getValues(); ArrayList methods = new ArrayList(advisedMethods.length); for (int i = 0; i < advisedMethods.length; i++) { Method m = (Method) advisedMethods[i]; if (clazz.equals(m.getDeclaringClass()) && ReflectUtils.isNotAccessMethod(m) && isNotJavassistWrappedMethod(m)) { methods.add(m); } } return methods.toArray(new Method[methods.size()]); } } private Method interceptGetDeclaredMethod(Class clazz, Object[] args) throws NoSuchMethodException { ClassAdvisor advisor = AspectManager.instance().getAdvisorIfAdvised(clazz); Method method = getDeclaredMethod(clazz, (String) args[0], (Class[]) args[1]); if (advisor == null) { return method; } else { Object[] advisedMethods = advisor.getAdvisedMethods().getValues(); for (int i = 0; i < advisedMethods.length; i++) { Method m = (Method) advisedMethods[i]; if (m.equals(method) && ReflectUtils.isNotAccessMethod(m) && isNotJavassistWrappedMethod(m)) { return method; } } } throw new NoSuchMethodException(); } private boolean isNotJavassistWrappedMethod(Method m) { if (Modifier.isPrivate(m.getModifiers()) && !Modifier.isStatic(m.getModifiers())) { if (m.getName().startsWith("_added_m$")) { return false; } } return true; } private Method[] interceptGetMethods(Class clazz) { ArrayList methods = new ArrayList(); //These are the methods that have already been added. Since we are //using Class.getDeclaredMethods(), we don't want to add super //implementations of overrriden methods GetMethodsAlreadyFound methodsFound = new GetMethodsAlreadyFound(); while (clazz != null) { ClassAdvisor advisor = AspectManager.instance().getAdvisorIfAdvised(clazz); Object[] foundMethods; if (advisor == null) { foundMethods = getDeclaredMethods(clazz); } else { foundMethods = advisor.getAdvisedMethods().getValues(); } for (int i = 0; i < foundMethods.length; i++) { Method m = (Method) foundMethods[i]; if (clazz.equals(m.getDeclaringClass()) && Modifier.isPublic(m.getModifiers())) { if (!methodsFound.existsMethod(m)) { methods.add(m); methodsFound.addMethod(m); } } } clazz = clazz.getSuperclass(); } return methods.toArray(new Method[methods.size()]); } private Method interceptGetMethod(Class clazz, Object[] args) throws NoSuchMethodException { Method method = clazz.getMethod((String) args[0], (Class[]) args[1]); Class declaringClass = method.getDeclaringClass(); while (clazz != null) { //Go up the inheritance hierachy looking for the class that declares this method if (clazz.equals(declaringClass)) { ClassAdvisor advisor = AspectManager.instance().getAdvisorIfAdvised(clazz); if (advisor == null) { return method; } else { Object[] methods = advisor.getAdvisedMethods().getValues(); for (int i = 0; i < methods.length; i++) { Method m = (Method) methods[i]; if (m.equals(method)) { return method; } } } } clazz = clazz.getSuperclass(); } throw new NoSuchMethodException(); } private Field[] interceptGetDeclaredFields(Class clazz) { ClassAdvisor advisor = AspectManager.instance().getAdvisorIfAdvised(clazz); if (advisor == null) { return getDeclaredFields(clazz); } else { Field[] advisedFields = advisor.getAdvisedFields(); ArrayList fields = new ArrayList(advisedFields.length); for (int i = 0; i < advisedFields.length; i++) { Field f = advisedFields[i]; if (clazz.equals(f.getDeclaringClass())) { fields.add(f); } } return fields.toArray(new Field[fields.size()]); } } /** Sun JVMs do not return any extra info from Class.getClasses(), * JRockit does, so make it got through the same cleaning procedure * here */ private Class[] interceptGetClasses(Class clazz) throws Throwable { Class[] classes = clazz.getClasses(); return cleanClasses(classes); } private Class[] interceptGetDeclaredClasses(Class clazz) throws Throwable { Class[] classes = getDeclaredClasses(clazz); return cleanClasses(classes); } private Class[] cleanClasses(Class[] classes) { ArrayList> clazzes = new ArrayList>(); for (int i = 0; i < classes.length; i++) { Class innerClass = classes[i]; //Check if implements Untransformable Class[] interfaces = classes[i].getInterfaces(); boolean implUntransformable = false; for (int j = 0; j < interfaces.length; j++) { if (interfaces[j].equals(Untransformable.class)) { implUntransformable = true; break; } } if (!implUntransformable) { //Check if class implements Invocation at any stage boolean isInvocationImpl = false; Class superclass = innerClass.getSuperclass(); while (superclass != null) { interfaces = classes[i].getInterfaces(); for (int j = 0; j < interfaces.length; j++) { if (interfaces[j].equals(Invocation.class)) { isInvocationImpl = true; break; } } superclass = superclass.getSuperclass(); } if (!isInvocationImpl) { clazzes.add(innerClass); } } } return clazzes.toArray(new Class[clazzes.size()]); } private Field interceptGetDeclaredField(Class clazz, Object[] args) throws NoSuchFieldException { ClassAdvisor advisor = AspectManager.instance().getAdvisorIfAdvised(clazz); Field field = getDeclaredField(clazz, (String) args[0]); if (advisor == null) { return field; } else { Field[] advisedFields = advisor.getAdvisedFields(); for (int i = 0; i < advisedFields.length; i++) { Field f = advisedFields[i]; if (f.equals(field)) { return field; } } } throw new NoSuchFieldException(); } /** * First attempt to invoke the original caller interceptor chains in the * calling class, then attempt to invoke the original interceptor chain * attached to the constructor in the target class. * For now we don't bother attempting to use optimized invocations since we * are using reflection anyway */ private Object invokeOriginalChainIfExists(Invocation invocation, Constructor constructor, Object[] args) throws Throwable { //Try to attach to the caller chain if (invocation instanceof MethodCalledByConstructorInvocation) { MethodCalledByConstructorInvocation inv = (MethodCalledByConstructorInvocation) invocation; Constructor callingCon = inv.getCalling(); Class callingClass = callingCon.getDeclaringClass(); if (isAdvised(callingClass)) { ClassAdvisor advisor = AspectManager.instance().getAdvisor(callingClass); if (advisor != null) { int index = advisor.getConstructorIndex(callingCon); if (index >= 0) { HashMap calledClassesMap = advisor.getConCalledByConInterceptors()[index]; if (calledClassesMap != null) { TLongObjectHashMap calledCons = calledClassesMap.get(constructor.getDeclaringClass().getName()); if (calledCons != null) { long calledHash = MethodHashing.constructorHash(constructor); ConByConInfo info = (ConByConInfo) calledCons.get(calledHash); if (info != null && info.hasAdvices()) { return advisor.invokeConCalledByCon(info, inv.getCallingObject(), args); } } } } } } } else if (invocation instanceof MethodCalledByMethodInvocation) { MethodCalledByMethodInvocation inv = (MethodCalledByMethodInvocation) invocation; Method callingMethod = inv.getCallingMethod(); if (isAdvised(callingMethod.getDeclaringClass())) { ClassAdvisor advisor = AspectManager.instance().getAdvisor(callingMethod.getDeclaringClass()); if (advisor != null) { long callingMethodHash = MethodHashing.calculateHash(callingMethod); long calledHash = MethodHashing.constructorHash(constructor); @SuppressWarnings("unchecked") HashMap calledClassesMap = (HashMap) advisor.getConCalledByMethodInterceptors().get(callingMethodHash); if (calledClassesMap != null) { TLongObjectHashMap calledCons = (TLongObjectHashMap) calledClassesMap.get(constructor.getDeclaringClass().getName()); if (calledCons != null) { //CallerConstructorInfo info = (CallerConstructorInfo) calledCons.get(calledHash); ConByMethodInfo info = (ConByMethodInfo) calledCons.get(calledHash); if (info != null && info.hasAdvices()) { //return advisor.invokeConCalledByMethod(callingMethodHash, args, info, inv.getCallingObject()); return advisor.invokeConCalledByMethod(info, inv.getCallingObject(), args); } } } } } } //Try to attach to chain on target object Class calledClass = constructor.getDeclaringClass(); if (isAdvised(calledClass)) { ClassAdvisor advisor = AspectManager.instance().getAdvisor(constructor.getDeclaringClass()); if (advisor != null && advisor.hasAspects()) { int index = advisor.getConstructorIndex(constructor); if (index >= 0) { ConstructorInfo jp = advisor.getConstructorInfos()[index]; return jp.getWrapper().invoke(null, args); } } } return invocation.invokeNext(); } /** * Attempt to invoke the original interceptor chain attached to the * field read in the target class. * For now we don't bother attempting to use optimized invocations since we * are using reflection anyway */ private Object invokeOriginalChainIfExists(Invocation invocation, Field field, Object targetObject) throws Throwable { //Don't attach to caller chain, since we don't have caller interception for fields //Try to attach to chain on target object ClassAdvisor advisor = AspectManager.instance().getAdvisor(field.getDeclaringClass()); Class calledClass = field.getDeclaringClass(); if (isAdvised(calledClass)) { if (advisor != null && advisor.hasAspects()) { int index = advisor.getFieldIndex(field); if (index >= 0) { FieldInfo jp = advisor.getFieldReadInfos()[index]; return jp.getWrapper().invoke(null, new Object[] {targetObject}); } } } return invocation.invokeNext(); } /** * Attempt to invoke the original interceptor chain attached to the * field write in the target class. * For now we don't bother attempting to use optimized invocations since we * are using reflection anyway */ private Object invokeOriginalChainIfExists(Invocation invocation, Field field, Object targetObject, Object value) throws Throwable { //Don't attach to caller chain, since we don't have caller interception for fields //Try to attach to chain on target object ClassAdvisor advisor = AspectManager.instance().getAdvisor(field.getDeclaringClass()); Class calledClass = field.getDeclaringClass(); if (isAdvised(calledClass)) { if (advisor != null && advisor.hasAspects()) { int index = advisor.getFieldIndex(field); if (index >= 0) { FieldInfo jp = advisor.getFieldWriteInfos()[index]; return jp.getWrapper().invoke(null, new Object[] {targetObject, value}); } } } return invocation.invokeNext(); } /** * Attempt to invoke the original interceptor chain attached to the * method call in the caller class. * For now we don't bother attempting to use optimized invocations since we * are using reflection anyway */ private Object invokeOriginalChainIfExists(Invocation invocation, Method method, Object targetObject, Object[] args) throws Throwable { //Try to attach to the caller chain if (invocation instanceof MethodCalledByConstructorInvocation) { MethodCalledByConstructorInvocation inv = (MethodCalledByConstructorInvocation) invocation; Constructor callingCon = inv.getCalling(); Class callingClass = callingCon.getDeclaringClass(); if (isAdvised(callingClass)) { ClassAdvisor advisor = AspectManager.instance().getAdvisor(callingClass); if (advisor != null) { int index = advisor.getConstructorIndex(callingCon); if (index >= 0) { HashMap calledClassesMap = advisor.getMethodCalledByConInterceptors()[index]; if (calledClassesMap != null) { TLongObjectHashMap calledMethods = calledClassesMap.get(method.getDeclaringClass().getName()); if (calledMethods != null) { long calledHash = MethodHashing.calculateHash(method); //CallerMethodInfo info = (CallerMethodInfo) calledMethods.get(calledHash); MethodByConInfo info = (MethodByConInfo) calledMethods.get(calledHash); if (info != null && info.hasAdvices()) { //return advisor.invokeConstructorCaller(index, targetObject, args, info); return advisor.invokeConstructorCaller(info, inv.getCallingObject(), targetObject, args); } } } } } } } else if (invocation instanceof MethodCalledByMethodInvocation) { MethodCalledByMethodInvocation inv = (MethodCalledByMethodInvocation) invocation; Method callingMethod = inv.getCallingMethod(); if (isAdvised(callingMethod.getDeclaringClass())) { ClassAdvisor advisor = AspectManager.instance().getAdvisor(callingMethod.getDeclaringClass()); if (advisor != null) { long callingMethodHash = MethodHashing.calculateHash(callingMethod); long calledHash = MethodHashing.calculateHash(method); @SuppressWarnings("unchecked") HashMap calledClassesMap = (HashMap) advisor.getMethodCalledByMethodInterceptors().get(callingMethodHash); if (calledClassesMap != null) { TLongObjectHashMap calledMethods = (TLongObjectHashMap) calledClassesMap.get(method.getDeclaringClass().getName()); if (calledMethods != null) { //CallerMethodInfo info = (CallerMethodInfo) calledMethods.get(calledHash); MethodByMethodInfo info = (MethodByMethodInfo) calledMethods.get(calledHash); if (info != null && info.hasAdvices()) { //return advisor.invokeCaller(callingMethodHash, targetObject, args, info, inv.getCallingObject()); return advisor.invokeCaller(info, inv.getCallingObject(), targetObject, args); } } } } } } //Don't try to attach to chain on target object, since this already is handled for us //(Wrapper is method itself) return invocation.invokeNext(); } private boolean isAdvised(Class clazz) { Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(Advised.class)) { return true; } } //Is this recursive check needed Class superClass = clazz.getSuperclass(); if (superClass != null) { return isAdvised(superClass); } return false; } // Inner classes ------------------------------------------------- /* Used by interceptGetMethods() */ class GetMethodsAlreadyFound { HashMap> methodMap = new HashMap>(); public void addMethod(Method m) { String methodName = m.getName(); ArrayList methods = methodMap.get(methodName); if (methods == null) { methods = new ArrayList(); methodMap.put(methodName, methods); } methods.add(m); } public boolean existsMethod(Method method) { ArrayList methods = methodMap.get(method.getName()); if (methods == null) { return false; } Class[] methodParamTypes = method.getParameterTypes(); for (Method found : methods) { Class[] foundParamTypes = found.getParameterTypes(); if (methodParamTypes.length == foundParamTypes.length) { boolean same = true; for (int i = 0; i < methodParamTypes.length; i++) { if (!methodParamTypes[i].equals(foundParamTypes[i])) { same = false; } } if (same) { return true; } } } return false; } } private interface SecurityAction { Method[] getDeclaredMethods(Class clazz); Field[] getDeclaredFields(Class clazz); Class[] getDeclaredClasses(Class clazz); Field getDeclaredField(Class clazz, String name) throws NoSuchFieldException; Method getDeclaredMethod(Class clazz, String name, Class[] paramTypes) throws NoSuchMethodException; SecurityAction NON_PRIVILEGED = new SecurityAction() { public Field[] getDeclaredFields(Class clazz) { return clazz.getDeclaredFields(); } public Method[] getDeclaredMethods(Class clazz) { return clazz.getDeclaredMethods(); } public Class[] getDeclaredClasses(Class clazz) { return clazz.getDeclaredClasses(); } public Field getDeclaredField(Class clazz, String name) throws NoSuchFieldException { return clazz.getDeclaredField(name); } public Method getDeclaredMethod(Class clazz, String name, Class[] paramTypes) throws NoSuchMethodException { return clazz.getDeclaredMethod(name, paramTypes); } }; SecurityAction PRIVILEGED = new SecurityAction() { public Field[] getDeclaredFields(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction(){ public Field[] run() { return clazz.getDeclaredFields(); } }); } public Method[] getDeclaredMethods(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction(){ public Method[] run() { return clazz.getDeclaredMethods(); } }); } public Class[] getDeclaredClasses(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction[]>(){ public Class[] run() { return clazz.getDeclaredClasses(); } }); } public Field getDeclaredField(final Class clazz, final String name) throws NoSuchFieldException { try { return AccessController.doPrivileged(new PrivilegedExceptionAction(){ public Field run() throws Exception { return clazz.getDeclaredField(name); } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof NoSuchFieldException) { throw (NoSuchFieldException)ex; } throw new RuntimeException(ex); } } public Method getDeclaredMethod(final Class clazz, final String name, final Class[] paramTypes) throws NoSuchMethodException { try { return AccessController.doPrivileged(new PrivilegedExceptionAction(){ public Method run() throws Exception { return clazz.getDeclaredMethod(name, paramTypes); } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof NoSuchMethodException) { throw (NoSuchMethodException)ex; } throw new RuntimeException(ex); } } }; } private static Method[] getDeclaredMethods(Class clazz) { if (System.getSecurityManager() == null) { return SecurityAction.NON_PRIVILEGED.getDeclaredMethods(clazz); } else { return SecurityAction.PRIVILEGED.getDeclaredMethods(clazz); } } private static Field[] getDeclaredFields(Class clazz) { if (System.getSecurityManager() == null) { return SecurityAction.NON_PRIVILEGED.getDeclaredFields(clazz); } else { return SecurityAction.PRIVILEGED.getDeclaredFields(clazz); } } private static Class[] getDeclaredClasses(Class clazz) { if (System.getSecurityManager() == null) { return SecurityAction.NON_PRIVILEGED.getDeclaredClasses(clazz); } else { return SecurityAction.PRIVILEGED.getDeclaredClasses(clazz); } } private static Field getDeclaredField(Class clazz, String name) throws NoSuchFieldException { if (System.getSecurityManager() == null) { return SecurityAction.NON_PRIVILEGED.getDeclaredField(clazz, name); } else { return SecurityAction.PRIVILEGED.getDeclaredField(clazz, name); } } private static Method getDeclaredMethod(Class clazz, String name, Class[] paramTypes) throws NoSuchMethodException { if (System.getSecurityManager() == null) { return SecurityAction.NON_PRIVILEGED.getDeclaredMethod(clazz, name, paramTypes); } else { return SecurityAction.PRIVILEGED.getDeclaredMethod(clazz, name, paramTypes); } } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/AspectAnnotationLoaderStrategySupport.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/AspectAnnotationLoaderStrate0000644000175000017500000001041311145122062033353 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import org.jboss.aop.advice.AdviceType; import org.jboss.aop.advice.PrecedenceDefEntry; import org.jboss.aop.advice.Scope; import org.jboss.aop.pointcut.ast.ASTCFlowExpression; /** * Default implementation of AspectAnnotationLoaderStrategy. * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class AspectAnnotationLoaderStrategySupport implements AspectAnnotationLoaderStrategy { public void deployAnnotationIntroduction(AspectAnnotationLoader loader, String expr, String annotation, boolean invisible) { } public void deployAspect(AspectAnnotationLoader loader, boolean isFactory, String name, Scope scope) { } public void deployAspectMethodBinding(AspectAnnotationLoader loader, AdviceType internalAdviceType, String aspectDefName, String methodName, String bindingName, String pointcutString, String cflow, ASTCFlowExpression cflowExpression) throws Exception { } public void deployCFlow(AspectAnnotationLoader loader, CFlowStackInfo stack) { } public void deployDeclare(AspectAnnotationLoader loader, String name, String expr, boolean warning, String msg) throws Exception { } public void undeployDeclare(AspectAnnotationLoader loader, String name) throws Exception { } public void deployDynamicCFlow(AspectAnnotationLoader loader, String name, String clazz) { } public void deployInterceptor(AspectAnnotationLoader loader, boolean isFactory, String name, Scope scope) { } public void deployInterceptorBinding(AspectAnnotationLoader loader, String name, String pointcutString, String cflow, ASTCFlowExpression cflowExpression) throws Exception { } public void deployInterfaceIntroduction(AspectAnnotationLoader loader, InterfaceIntroductionInfo introduction) { } public void deployPointcut(AspectAnnotationLoader loader, String name, String expr) throws Exception { } public void deployPrecedence(AspectAnnotationLoader loader, String name, PrecedenceDefEntry[] pentries) { } public void deployTypedef(AspectAnnotationLoader loader, String name, String expr) throws Exception { } public void undeployAnnotationIntroduction(AspectAnnotationLoader loader, String expr, String annotation, boolean invisible) { } public void undeployAspect(AspectAnnotationLoader loader, String name) { } public void undeployAspectMethodBinding(AspectAnnotationLoader loader, String bindingName, String className, String methodName) { } public void undeployCFlow(AspectAnnotationLoader loader, String name) { } public void undeployDynamicCFlow(AspectAnnotationLoader loader, String name) { } public void undeployInterceptor(AspectAnnotationLoader loader, String name) { } public void undeployInterceptorBinding(AspectAnnotationLoader loader, String name) { } public void undeployInterfaceIntroduction(AspectAnnotationLoader loader, String name) { } public void undeployPointcut(AspectAnnotationLoader loader, String name) { } public void undeployPrecedence(AspectAnnotationLoader loader, String name) { } public void undeployTypedef(AspectAnnotationLoader loader, String name) { } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/GeneratedClassAdvisor.java0000644000175000017500000020117411145122066032735 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import gnu.trove.TLongObjectHashMap; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.GeneratedAdvisorInterceptor; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.advice.InterceptorFactory; import org.jboss.aop.advice.PrecedenceSorter; import org.jboss.aop.instrument.ConByConJoinPointGenerator; import org.jboss.aop.instrument.ConByMethodJoinPointGenerator; import org.jboss.aop.instrument.ConstructionJoinPointGenerator; import org.jboss.aop.instrument.ConstructorJoinPointGenerator; import org.jboss.aop.instrument.FieldJoinPointGenerator; import org.jboss.aop.instrument.JoinPointGenerator; import org.jboss.aop.instrument.MethodByConJoinPointGenerator; import org.jboss.aop.instrument.MethodByMethodJoinPointGenerator; import org.jboss.aop.instrument.MethodJoinPointGenerator; import org.jboss.aop.joinpoint.FieldJoinpoint; import org.jboss.aop.joinpoint.Joinpoint; import org.jboss.aop.joinpoint.MethodJoinpoint; import org.jboss.aop.pointcut.PointcutMethodMatch; import org.jboss.aop.util.UnmodifiableEmptyCollections; import org.jboss.aop.util.logging.AOPLogger; /** * Comment * * @author Kabir Khan * @version $Revision$ */ public class GeneratedClassAdvisor extends ClassAdvisor { public static final String ADD_METHOD_INFO = "addMethodInfo"; public static final String ADD_CONSTRUCTOR_INFO = "addConstructorInfo"; public static final String ADD_CONSTRUCTION_INFO = "addConstructionInfo"; public static final String ADD_FIELD_READ_INFO = "addFieldReadInfo"; public static final String ADD_FIELD_WRITE_INFO = "addFieldWriteInfo"; public static final String GET_PARENT_ADVISOR = "getParentAdvisor"; private static final AOPLogger logger = AOPLogger.getLogger(GeneratedClassAdvisor.class); // TODO Flavia // ArrayList constructorInfos = new ArrayList(); // ArrayList constructionInfos = new ArrayList(); // ArrayList fieldReadInfos = new ArrayList(); // ArrayList fieldWriteInfos = new ArrayList(); /** Super class methods that have been overrridden - these need special handling in this weaving mode */ ArrayList overriddenMethods = new ArrayList(); //TODO These are only needed for the class advisor really //All joinpoint generators apart from field reads, constructions and MethodCalledByXXX go in here private volatile ConcurrentHashMap joinPointGenerators = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; //Needs its own map to avoid crashing with the field write generators private volatile ConcurrentHashMap fieldReadJoinPoinGenerators = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; //Needs its own map to avoid crashing with the constructor generators private volatile ConcurrentHashMap constructionJoinPointGenerators = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; //An extra level of indirection is needed for MethodCalledByCon and MethodCalledByMethod as compared to the main joinPointGenerators map private volatile ConcurrentHashMap, JoinPointGenerator>> methodCalledByXXXJoinPointGenerators = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; ConcurrentHashMap oldInfos = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; ConcurrentHashMap oldFieldReadInfos = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; ConcurrentHashMap oldConstructionInfos = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; boolean initialisedSuperClasses; private int version; /** * Different behaviour depending on if we are a class advisor or instance advisor */ AdvisorStrategy advisorStrategy; protected GeneratedClassAdvisor(String classname) { //Generated advisors will not pass in an aspectmanager //This will be passed in via the initialise() method super(classname, null); advisorStrategy = new ClassAdvisorStrategy(); } protected GeneratedClassAdvisor(String classname, GeneratedClassAdvisor parent) { super(classname, null); advisorStrategy = new InstanceAdvisorStrategy(parent); } @Override public void cleanup() { super.cleanup(); methodInfos = null; advisorStrategy = null; Map subscribedSubDomains = getManager().getSubscribedSubDomains(); synchronized (subscribedSubDomains) { for (Iterator it = subscribedSubDomains.keySet().iterator() ; it.hasNext() ; ) { //TODO Not really sure what was attempted here //GeneratedAdvisorDomain manager = (GeneratedAdvisorDomain)it.next(); //Map advisors = manager.getAdvisors(); it.remove(); } } } protected void initialise(Class clazz, AspectManager manager) { advisorStrategy.initialise(clazz, manager); } /** * Generated class advisor sub class will override */ protected void initialiseCallers() { } /** * Generated instance advisor sub class will override */ protected void initialiseInfosForInstance() { } /** * To be called by initialiseInfosForInstance() in the generated instance advisors */ protected MethodInfo copyInfoFromClassAdvisor(MethodInfo info) { MethodInfo copy = (MethodInfo)info.copy(); copy.setAdvisor(this); addMethodInfo(copy); return copy; } /** * To be called by initialiseInfosForInstance() in the generated instance advisors */ protected FieldInfo copyInfoFromClassAdvisor(FieldInfo info) { FieldInfo copy = (FieldInfo)info.copy(); copy.setAdvisor(this); // TODO Flavia // if (copy.isRead()) // { // addFieldReadInfo(copy); // } // else // { // addFieldWriteInfo(copy); // } return copy; } /** * To be called by initialiseInfosForInstance() in the generated instance advisors */ protected ConByConInfo copyInfoFromClassAdvisor(ConByConInfo info) { ConByConInfo copy = (ConByConInfo)info.copy(); copy.setAdvisor(this); return copy; } /** * To be called by initialiseInfosForInstance() in the generated instance advisors */ protected MethodByConInfo copyInfoFromClassAdvisor(MethodByConInfo info) { MethodByConInfo copy = (MethodByConInfo)info.copy(); copy.setAdvisor(this); return copy; } /** * To be called by initialiseInfosForInstance() in the generated instance advisors */ protected ConByMethodInfo copyInfoFromClassAdvisor(ConByMethodInfo info) { ConByMethodInfo copy = (ConByMethodInfo)info.copy(); copy.setAdvisor(this); return copy; } /** * To be called by initialiseInfosForInstance() in the generated instance advisors */ protected MethodByMethodInfo copyInfoFromClassAdvisor(MethodByMethodInfo info) { MethodByMethodInfo copy = (MethodByMethodInfo)info.copy(); copy.setAdvisor(this); return copy; } @Override protected void rebuildInterceptors() { version++; advisorStrategy.rebuildInterceptors(); } @Override protected void rebuildInterceptorsForAddedBinding(AdviceBinding binding) { version++; advisorStrategy.rebuildInterceptorsForAddedBinding(binding); } @Override protected void rebuildInterceptorsForRemovedBinding(AdviceBinding binding) { version++; advisorStrategy.rebuildInterceptorsForRemovedBinding(binding); } /** * Callback for instance advisors to rebuild their interceptors when their * version number is out of sync */ protected synchronized void internalRebuildInterceptors() { super.rebuildInterceptors(); } /** * Callback for generated instance advisors to check if the version has been updated */ protected void checkVersion() { advisorStrategy.checkVersion(); } /** * Will be overridden by generated instanceadvisor classes and perform a rebuild */ protected void doRebuildForInstance() { } protected void handleOverriddenMethods(AdviceBinding binding) { if (overriddenMethods != null && overriddenMethods.size() > 0) { for(MethodInfo info : overriddenMethods) { Method method = info.getMethod(); PointcutMethodMatch match = binding.getPointcut().matchesExecution(this, method); if (match != null && match.isMatch()) { adviceBindings.add(binding); if (AspectManager.verbose) { logger.error("method matched binding " + binding.getPointcut().getExpr() + " " + method.toString()); } binding.addAdvisor(this); pointcutResolved(info, binding, new MethodJoinpoint(method)); } } } } @Override protected void resolveMethodPointcut(AdviceBinding binding) { GeneratedClassAdvisor classAdvisor = getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); if (classAdvisor == null) { //We are either the class advisor or an instanceadvisor with own data so we need to do all the work super.resolveMethodPointcut(binding); handleOverriddenMethods(binding); } } @Override protected void resolveFieldPointcut(FieldInfo[] newFieldInfos, Interceptor[][] fieldInterceptors, AdviceBinding binding, boolean write) { GeneratedClassAdvisor classAdvisor = getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); if (classAdvisor == null) { //We are either the class advisor or an instanceadvisor with own data so we need to do all the work super.resolveFieldPointcut(newFieldInfos, fieldInterceptors, binding, write); } } @Override protected void resolveConstructorPointcut( AdviceBinding binding) { advisorStrategy.resolveConstructorPointcut(binding); } @Override protected void resolveConstructionPointcut(AdviceBinding binding) { advisorStrategy.resolveConstructionPointcut(binding); } /** * Generated class advisor sub class will override */ protected void initialiseMethods() { } /** * Called by initialiseMethods() in generated advisor sub classes */ protected void addMethodInfo(MethodInfo mi) { MethodInfo old = methodInfos.getMethodInfo(mi.getHash()); if (old != null) { overriddenMethods.add(old); } methodInfos.put(mi.getHash(), mi); advisorStrategy.makeAccessibleMethod(mi); } @Override protected void initializeMethodChain() { //We have all the advised methods here, need to get all the others here too long[] keys = advisedMethods.keys(); for (int i = 0; i < keys.length; i++) { MethodMatchInfo matchInfo = methodInfos.getMatchInfo(keys[i]); if (super.initialized && matchInfo != null) { matchInfo.clear(); } if (matchInfo == null) { MethodInfo info = new MethodInfo(); Method amethod = (Method) advisedMethods.get(keys[i]); info.setAdvisedMethod(amethod); info.setUnadvisedMethod(amethod); info.setHash(keys[i]); info.setAdvisor(this); methodInfos.put(keys[i], info); } } } /** * Generated class advisor sub class will override */ protected void initialiseConstructors(Collection constructorInfos) { } /** * Called by initialiseConstructors() in generated advisor sub classes */ protected void addConstructorInfo(ConstructorInfo ci, Collection constructorInfos) { constructorInfos.add(ci); //If we do dynamic invokes the constructor will need to be accessible via reflection SecurityActions.setAccessible(ci.getConstructor()); } @Override protected void createInterceptorChains() throws Exception { advisorStrategy.createInterceptorChains(); } // TODO Flavia // @Override // protected ArrayList initializeConstructorChain() // { // if (super.initialized) // { // for (Iterator it = constructorInfos.iterator() ; it.hasNext() ; ) // { // ((ConstructorInfo)it.next()).clear(); // } // } // return constructorInfos; // } /** * Generated class advisor sub class will override */ protected void initialiseConstructions(Collection constructorInfos) { } /** * Called by initialiseConstructions() in generated advisor sub classes */ protected void addConstructionInfo(ConstructionInfo ci, Collection constructionInfos) { constructionInfos.add(ci); } // TODO Flavia // @Override // protected ArrayList initializeConstructionChain() // { // if (super.initialized) // { // for (Iterator it = constructionInfos.iterator() ; it.hasNext() ; ) // { // ((ConstructionInfo)it.next()).clear(); // } // } // return constructionInfos; // } /** * Generated class advisor sub class will override */ protected void initialiseFieldReads(Collection fieldReadInfos) { } /** * Called by initialiseFieldReads() in generated advisor sub classes */ protected void addFieldReadInfo(FieldInfo fi, Collection fieldReadInfos) { fieldReadInfos.add(fi); //If we do dynamic invokes the field will need to be accessible via reflection advisorStrategy.makeAccessibleField(fi); } // TODO Flavia remove this once the process is complete @Override protected void initializeConstructorChain() { // TODO remove this if (this.constructorInfos == null) { super.initializeConstructorChain(); } } // TODO remove this once the process is complete @Override protected void initializeConstructionChain() { // TODO remove this if (this.constructionInfos == null) { super.initializeConstructionChain(); } } @Override protected void initializeFieldReadChain() { this.fieldReadInfos = mergeFieldInfos(fieldReadInfos, true); } /** * Generated class advisor sub class will override */ protected void initialiseFieldWrites(Collection fieldWriteInfos) { } /** * Called by initialiseFieldWrites() in generated advisor sub classes */ protected void addFieldWriteInfo(FieldInfo fi, Collection fieldWriteInfos) { fieldWriteInfos.add(fi); //If we do dynamic invokes the field will need to be accessible via reflection advisorStrategy.makeAccessibleField(fi); } @Override protected void initializeFieldWriteChain() { this.fieldWriteInfos = mergeFieldInfos(fieldWriteInfos, false); } /* Creates a full list of field infos for all fields, using the ones added by * generated advisor for advised fields. */ private FieldInfo[] mergeFieldInfos(FieldInfo[] advisedInfos, boolean read) { FieldInfo[] newInfos = new FieldInfo[advisedFields.length]; int nextIndex = 0; int advisedInfosLength = advisedInfos == null? 0: advisedInfos.length; for (int i = 0 ; i < advisedFields.length ; i++) { if (nextIndex < advisedInfosLength && advisedInfos[nextIndex].getIndex() == i) { if (super.initialized) { advisedInfos[nextIndex].clear(); } newInfos[i] = advisedInfos[nextIndex]; nextIndex++; } else { FieldInfo info = new FieldInfo(this, read); info.setAdvisedField(advisedFields[i]); info.setIndex(i); newInfos[i] = info; } } return newInfos; } @Override protected void finalizeChains() { ClassAdvisor classAdvisor = getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); if (classAdvisor != null) { //We are an instance advisor who has not resolved their own pointcuts, make sure that we set the bindings that are referenced //so that they can be removed properly //Make sure that all the adviceBindings for the class advisor are referenced from us synchronized(this.adviceBindings) { this.adviceBindings.addAll(classAdvisor.adviceBindings); if (adviceBindings.size() > 0) { for (AdviceBinding binding : this.adviceBindings) { binding.addAdvisor(this); } } } } finalizeMethodChain(); finalizeFieldReadChain(); finalizeFieldWriteChain(); advisorStrategy.finalizeConstructorChain(constructorInfos); advisorStrategy.finalizeConstructionChain(constructionInfos); } @Override protected void finalizeMethodChain() { ClassAdvisor classAdvisor = getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); if (classAdvisor != null) { //We are an instance advisor with no own data influencing the chains, copy these from the parent advisor easyFinalizeMethodChainForInstance(classAdvisor, methodInfos); } else { //We are either the class advisor or an instanceadvisor with own data so we need to do all the work fullWorkFinalizeMethodChain(methodInfos); } } private void easyFinalizeMethodChainForInstance(ClassAdvisor classAdvisor, MethodInterceptors newMethodInterceptors) { long[] keys = newMethodInterceptors.keys(); for (int i = 0; i < keys.length; i++) { MethodInfo classMethodInfo = classAdvisor.getMethodInfo(keys[i]); MethodMatchInfo matchInfo = newMethodInterceptors.getMatchInfo(keys[i]); MethodInfo myMethodInfo = matchInfo.getInfo(); myMethodInfo.cloneChains(classMethodInfo); if (updateOldInfo(oldInfos, myMethodInfo, OldInfoMaps.INFOS)) { MethodJoinPointGenerator generator = getJoinPointGenerator(myMethodInfo); generator.rebindJoinpoint(myMethodInfo); } } } private void fullWorkFinalizeMethodChain(MethodInterceptors newMethodInterceptors) { //We are either the class advisor or an instanceadvisor with own data so we need to do all the work TLongObjectHashMap newMethodInfos = new TLongObjectHashMap(); long[] keys = newMethodInterceptors.keys(); for (int i = 0; i < keys.length; i++) { MethodMatchInfo matchInfo = newMethodInterceptors.getMatchInfo(keys[i]); matchInfo.populateBindings(); MethodInfo info = matchInfo.getInfo(); newMethodInfos.put(keys[i], info); MethodJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldInfos, info, generator, OldInfoMaps.INFOS); } if (AspectManager.maintainAdvisorMethodInterceptors) { methodInterceptors = newMethodInfos; } //Handle the overridden methods if (overriddenMethods != null && overriddenMethods.size() > 0) { for (MethodInfo info : overriddenMethods) { MethodJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldInfos, info, generator, OldInfoMaps.INFOS); } } } private void finalizeFieldReadChain() { ClassAdvisor classAdvisor = getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); if (classAdvisor != null) { //We are an instance advisor with no own data influencing the chains, copy these from the parent advisor easyFinalizeFieldChainForInstance(oldFieldReadInfos, classAdvisor.getFieldReadInfos(), fieldReadInfos, OldInfoMaps.FIELD_READ_INFOS); } else { //We are either the class advisor or an instanceadvisor with own data so we need to do all the work fullWorkFinalizeFieldChain(oldFieldReadInfos, fieldReadInfos, OldInfoMaps.FIELD_READ_INFOS); } } protected void finalizeFieldWriteChain() { ClassAdvisor classAdvisor = getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); if (classAdvisor != null) { //We are an instance advisor with no own data influencing the chains, copy these from the parent advisor easyFinalizeFieldChainForInstance(oldInfos, classAdvisor.getFieldWriteInfos(), fieldWriteInfos, OldInfoMaps.INFOS); } else { //We are either the class advisor or an instanceadvisor with own data so we need to do all the work fullWorkFinalizeFieldChain(oldInfos, fieldWriteInfos, OldInfoMaps.INFOS); } } private void easyFinalizeFieldChainForInstance(Map oldFieldInfos, FieldInfo[] classFieldInfos, FieldInfo[] newFieldInfos, OldInfoMaps oldInfoMapInstance) { //We are an instance advisor with no own data influencing the chains, copy these from the parent advisor for (int i = 0; i < newFieldInfos.length; i++) { FieldInfo myInfo = newFieldInfos[i]; myInfo.cloneChains(classFieldInfos[i]); if (updateOldInfo(oldFieldInfos, myInfo, oldInfoMapInstance)) { FieldJoinPointGenerator generator = getJoinPointGenerator(myInfo); generator.rebindJoinpoint(myInfo); } } } private void fullWorkFinalizeFieldChain(Map oldFieldInfos, FieldInfo[] newFieldInfos, OldInfoMaps oldInfoMapInstance) { //We are either the class advisor or an instanceadvisor with own data so we need to do all the work for (int i = 0; i < newFieldInfos.length; i++) { FieldInfo info = newFieldInfos[i]; FieldJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldFieldInfos, info, generator, oldInfoMapInstance); } } @Override protected void finalizeMethodCalledByMethodInterceptorChain(MethodByMethodInfo info) { MethodByMethodJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldInfos, info, generator, OldInfoMaps.INFOS); } @Override protected void finalizeConCalledByMethodInterceptorChain(ConByMethodInfo info) { ConByMethodJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldInfos, info, generator, OldInfoMaps.INFOS); } @Override protected void finalizeConCalledByConInterceptorChain(ConByConInfo info) { ConByConJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldInfos, info, generator, OldInfoMaps.INFOS); } @Override protected void finalizeMethodCalledByConInterceptorChain(MethodByConInfo info) { MethodByConJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldInfos, info, generator, OldInfoMaps.INFOS); } private JoinPointGenerator getJoinPointGenerator(JoinPointInfo info) { if (info instanceof MethodInfo) { return getJoinPointGenerator((MethodInfo)info); } else if (info instanceof FieldInfo) { return getJoinPointGenerator((FieldInfo)info); } else if (info instanceof ConstructionInfo) { return getJoinPointGenerator((ConstructionInfo)info); } else if (info instanceof ConstructorInfo) { return getJoinPointGenerator((ConstructorInfo)info); } else if (info instanceof ConByConInfo) { return getJoinPointGenerator((ConByConInfo)info); } else if (info instanceof ConByMethodInfo) { return getJoinPointGenerator((ConByMethodInfo)info); } else if (info instanceof MethodByMethodInfo) { return getJoinPointGenerator((MethodByMethodInfo)info); } else if (info instanceof MethodByConInfo) { return getJoinPointGenerator((MethodByConInfo)info); } else { throw new RuntimeException("Invalid JoinPointInfo passed in: " + info.getClass().getName()); } } protected MethodJoinPointGenerator getJoinPointGenerator(MethodInfo info) { return advisorStrategy.getJoinPointGenerator(info); } protected FieldJoinPointGenerator getJoinPointGenerator(FieldInfo info) { return advisorStrategy.getJoinPointGenerator(info); } protected ConstructorJoinPointGenerator getJoinPointGenerator(ConstructorInfo info) { return advisorStrategy.getJoinPointGenerator(info); } protected ConstructionJoinPointGenerator getJoinPointGenerator(ConstructionInfo info) { return advisorStrategy.getJoinPointGenerator(info); } protected MethodByMethodJoinPointGenerator getJoinPointGenerator(MethodByMethodInfo info) { return advisorStrategy.getJoinPointGenerator(info); } protected ConByMethodJoinPointGenerator getJoinPointGenerator(ConByMethodInfo info) { return advisorStrategy.getJoinPointGenerator(info); } protected ConByConJoinPointGenerator getJoinPointGenerator(ConByConInfo info) { return advisorStrategy.getJoinPointGenerator(info); } protected MethodByConJoinPointGenerator getJoinPointGenerator(MethodByConInfo info) { return advisorStrategy.getJoinPointGenerator(info); } /** * Override default behaviour of when a pointcut is matched, populate the factories since this * is what is needed for generating the optimized invocation method */ @Override protected void pointcutResolved(JoinPointInfo info, AdviceBinding binding, Joinpoint joinpoint) { ArrayList curr = info.getInterceptorChain(); if (binding.getCFlow() != null) { InterceptorFactory[] factories = binding.getInterceptorFactories(); for (int i = 0 ; i < factories.length ; i++) { curr.add(new GeneratedAdvisorInterceptor(factories[i], this, joinpoint, binding.getCFlowString(), binding.getCFlow())); } } else { InterceptorFactory[] factories = binding.getInterceptorFactories(); for (int i = 0 ; i < factories.length ; i++) { curr.add(new GeneratedAdvisorInterceptor(factories[i], this, joinpoint)); } } } private void finalizeChainAndRebindJoinPoint(Map oldInfos, JoinPointInfo info, JoinPointGenerator generator, OldInfoMaps oldInfoMapInstance) { adjustInfoForAddedBinding(info); List list = info.getInterceptorChain(); GeneratedAdvisorInterceptor[] factories = null; if (list.size() > 0) { factories = applyPrecedence(list.toArray(new GeneratedAdvisorInterceptor[list.size()])); } info.setInterceptors(factories); if (updateOldInfo(oldInfos, info, oldInfoMapInstance)) { generator.rebindJoinpoint(info); } } @Override public String toString() { Class clazz = this.getClass(); StringBuffer sb = new StringBuffer("CLASS: " + clazz.getName()); Field[] fields = clazz.getFields(); for (int i = 0 ; i < fields.length ; i++) { sb.append("\n\t" + fields[i]); } return sb.toString(); } GeneratedAdvisorInterceptor[] applyPrecedence(GeneratedAdvisorInterceptor[] interceptors) { return PrecedenceSorter.applyPrecedence(interceptors, manager); } /** * If this is an instance advisor, will check with parent class advisor if the aspect * is already registered. If so, we should use the one from the parent advisor */ @Override public Object getPerClassAspect(AspectDefinition def) { return advisorStrategy.getPerClassAspect(def); } /** * Generated ClassAdvisors and InstanceAdvisors will be different instances, * so keep track of what per_class_joinpoint aspects have been added where */ ConcurrentHashMap> perClassJoinpointAspectDefinitions = new ConcurrentHashMap>(); public Object getPerClassJoinpointAspect(AspectDefinition def, Joinpoint joinpoint) { return advisorStrategy.getPerClassJoinpointAspect(def, joinpoint); } public synchronized void addPerClassJoinpointAspect(AspectDefinition def, Joinpoint joinpoint) { Map joinpoints = perClassJoinpointAspectDefinitions.get(def); if (joinpoints == null) { joinpoints = new ConcurrentHashMap(); perClassJoinpointAspectDefinitions.put(def, joinpoints); } if (!joinpoints.containsKey(joinpoint)) { Object aspect = def.getFactory().createPerJoinpoint(this, joinpoint); if (aspect == null) { joinpoints.put(joinpoint, NULL_ASPECT); } else { joinpoints.put(joinpoint, aspect); } } def.registerAdvisor(this); } public synchronized void removePerClassJoinpointAspect(AspectDefinition def) { perClassJoinpointAspectDefinitions.remove(def); } /** * @see Advisor#chainOverridingForInheritedMethods() */ @Override public boolean chainOverridingForInheritedMethods() { return true; } @Override public Object getFieldAspect(FieldJoinpoint joinpoint, AspectDefinition def) { Object instance = getPerClassJoinpointAspect(def, joinpoint); if (instance == null) { addPerClassJoinpointAspect(def, joinpoint); instance = getPerClassJoinpointAspect(def, joinpoint); } return instance; } private GeneratedClassAdvisor getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices() { return advisorStrategy.getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); } /** * Optimization so that when we create instance advisors we don't have to create the method tables again, * they were already created for the class advisor */ @Override protected void createMethodTables() throws Exception { advisorStrategy.createMethodTables(); } /** * Optimization so that when we create instance advisors we don't have to create the field tables again, * they were already created for the class advisor */ @Override protected void createFieldTable() throws Exception { advisorStrategy.createFieldTable(); } /** * Optimization so that when we create instance advisors we don't have to create the constructor tables again, * they were already created for the class advisor */ @Override protected void createConstructorTables() throws Exception { advisorStrategy.createConstructorTables(); } @Override public Set getPerInstanceAspectDefinitions() { return advisorStrategy.getPerInstanceAspectDefinitions(); } @Override public Map> getPerInstanceJoinpointAspectDefinitions() { return advisorStrategy.getPerInstanceJoinpointAspectDefinitions(); } /** * Caches the old info and checks if the chains have been updated */ private boolean updateOldInfo(Map oldInfos, JoinPointInfo newInfo, OldInfoMaps oldInfoMapInstance) { Interceptor[] oldChain = oldInfos.get(newInfo.getJoinpoint()); if (oldChain != null) { //We are not changing any of the bindings if (newInfo.equalChains(oldChain)) { return false; } } Interceptor[] currentOldChain = newInfo.getInterceptors(); if (oldInfoMapInstance == OldInfoMaps.INFOS) { oldInfos = initOldInfosMap(); } else if (oldInfoMapInstance == OldInfoMaps.FIELD_READ_INFOS) { oldInfos = initOldFieldReadInfosMap(); } else if (oldInfoMapInstance == OldInfoMaps.CONSTRUCTION_INFOS) { oldInfos = initOldConstructionInfosMap(); } else { throw new RuntimeException("Unrecognised map"); } if (currentOldChain != null) { oldInfos.put(newInfo.getJoinpoint(), currentOldChain); } else if (oldChain != null) { oldInfos.remove(newInfo.getJoinpoint()); } return true; } protected void generateJoinPointClass(MethodInfo info) { MethodJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected void generateJoinPointClass(FieldInfo info) { FieldJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected void generateJoinPointClass(ConstructorInfo info) { ConstructorJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected void generateJoinPointClass(ConstructionInfo info) { ConstructionJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected void generateJoinPointClass(MethodByMethodInfo info) { MethodByMethodJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected void generateJoinPointClass(ConByMethodInfo info) { ConByMethodJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected void generateJoinPointClass(ConByConInfo info) { ConByConJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected void generateJoinPointClass(MethodByConInfo info) { MethodByConJoinPointGenerator generator = getJoinPointGenerator(info); generator.generateJoinPointClass(getClassLoader(), info); } protected Object rebindJoinPointWithInstanceInformation(JoinPointInfo info) { info.getInterceptorChainReadWriteLock().readLock().lock(); try { JoinPointGenerator generator = getJoinPointGenerator(info); generator.rebindJoinpoint(info); return generator.generateJoinPointClass(getClassLoader(), info); } finally { info.getInterceptorChainReadWriteLock().readLock().unlock(); } } /** * Called back from generated code */ public Object createAndRebindJoinPointForInstance(JoinPointInfo info) { JoinPointInfo newinfo = info.copy(); newinfo.setAdvisor(this); return rebindJoinPointWithInstanceInformation(newinfo); } protected void initJoinPointGeneratorsMap() { if (joinPointGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (joinPointGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { joinPointGenerators = new ConcurrentHashMap(); } } } } protected void initFieldReadJoinPointGeneratorsMap() { if (fieldReadJoinPoinGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (fieldReadJoinPoinGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { fieldReadJoinPoinGenerators = new ConcurrentHashMap(); } } } } protected void initConstructionJoinPointGeneratorsMap() { if (constructionJoinPointGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (constructionJoinPointGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { constructionJoinPointGenerators = new ConcurrentHashMap(); } } } } protected void initMethodCalledByConJoinPointGeneratorsMap() { if (methodCalledByXXXJoinPointGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (methodCalledByXXXJoinPointGenerators == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { methodCalledByXXXJoinPointGenerators = new ConcurrentHashMap, JoinPointGenerator>>(); } } } } protected ConcurrentHashMap initOldInfosMap() { if (oldInfos == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (oldInfos == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { oldInfos = new ConcurrentHashMap(); } } } return oldInfos; } protected ConcurrentHashMap initOldFieldReadInfosMap() { if (oldFieldReadInfos == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (oldFieldReadInfos == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { oldFieldReadInfos = new ConcurrentHashMap(); } } } return oldFieldReadInfos; } protected ConcurrentHashMap initOldConstructionInfosMap() { if (oldConstructionInfos == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (oldConstructionInfos == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { oldConstructionInfos = new ConcurrentHashMap(); } } } return oldConstructionInfos; } /** * Encapsulates different behaviours depending on if this is an instance or class advisor */ private interface AdvisorStrategy { void initialise(Class clazz, AspectManager manager); void checkVersion(); void createInterceptorChains() throws Exception; MethodJoinPointGenerator getJoinPointGenerator(MethodInfo info); FieldJoinPointGenerator getJoinPointGenerator(FieldInfo info); ConstructorJoinPointGenerator getJoinPointGenerator(ConstructorInfo info); ConstructionJoinPointGenerator getJoinPointGenerator(ConstructionInfo info); MethodByMethodJoinPointGenerator getJoinPointGenerator(MethodByMethodInfo info); ConByMethodJoinPointGenerator getJoinPointGenerator(ConByMethodInfo info); ConByConJoinPointGenerator getJoinPointGenerator(ConByConInfo info); MethodByConJoinPointGenerator getJoinPointGenerator(MethodByConInfo info); Object getPerClassAspect(AspectDefinition def); Object getPerClassJoinpointAspect(AspectDefinition def, Joinpoint joinpoint); GeneratedClassAdvisor getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices(); void createMethodTables() throws Exception; void createFieldTable() throws Exception; void createConstructorTables() throws Exception; Set getPerInstanceAspectDefinitions(); Map> getPerInstanceJoinpointAspectDefinitions(); void rebuildInterceptors(); void rebuildInterceptorsForAddedBinding(AdviceBinding binding); void rebuildInterceptorsForRemovedBinding(AdviceBinding binding); void resolveConstructorPointcut(AdviceBinding binding); void resolveConstructionPointcut(AdviceBinding binding); void finalizeConstructorChain(ConstructorInfo[] newConstructorInfos); void finalizeConstructionChain(ConstructionInfo[] newConstructionInfos); void makeAccessibleField(FieldInfo fi); void makeAccessibleMethod(MethodInfo mi); } private class ClassAdvisorStrategy implements AdvisorStrategy { GeneratedClassAdvisor parent; public void initialise(Class clazz, AspectManager manager) { methodInfos = new MethodInterceptors(GeneratedClassAdvisor.this); initialiseMethods(); // initialise constructor info array Collection constructorInfoCol = new ArrayList(); initialiseConstructors(constructorInfoCol); constructorInfos = constructorInfoCol.toArray(new ConstructorInfo[constructorInfoCol.size()]); // initialise construction info array Collection constructionInfoCol = new ArrayList(); initialiseConstructions(constructionInfoCol); constructionInfos = constructionInfoCol.toArray(new ConstructionInfo[constructionInfoCol.size()]); // initalise field read info array Collection fieldReadInfoCol = new ArrayList(); initialiseFieldReads(fieldReadInfoCol); fieldReadInfos = fieldReadInfoCol.toArray(new FieldInfo[fieldReadInfoCol.size()]); // initalise field write info array Collection fieldWriteInfoCol = new ArrayList(); initialiseFieldWrites(fieldWriteInfoCol); fieldWriteInfos = fieldWriteInfoCol.toArray(new FieldInfo[fieldWriteInfoCol.size()]); GeneratedClassAdvisor.super.setManager(manager); //Make sure that we copy across per class and per joinpoint aspects from the old advisor if it exists //Generated advisors get created when the class is first accessed (not loaded), meaning that there could be an exisiting advisor //used for mathcing already when setting up the microcontainer. Advisor existing = AspectManager.instance().getAnyAdvisorIfAdvised(clazz); if (existing != null) { GeneratedClassAdvisor.this.aspects = existing.aspects; if (existing instanceof GeneratedClassAdvisor) { GeneratedClassAdvisor.this.perClassJoinpointAspectDefinitions = ((GeneratedClassAdvisor)existing).perClassJoinpointAspectDefinitions; } } manager.initialiseClassAdvisor(clazz, GeneratedClassAdvisor.this); initialiseCallers(); } public void checkVersion() { //The version is only has any significance for instance advisors } public void createInterceptorChains() throws Exception { GeneratedClassAdvisor.super.createInterceptorChains(); } public MethodJoinPointGenerator getJoinPointGenerator(MethodInfo info) { MethodJoinPointGenerator generator = (MethodJoinPointGenerator)joinPointGenerators.get(info.getJoinpoint()); if (generator == null) { generator = new MethodJoinPointGenerator(GeneratedClassAdvisor.this, info); initJoinPointGeneratorsMap(); MethodJoinPointGenerator existing = (MethodJoinPointGenerator)joinPointGenerators.putIfAbsent(info.getJoinpoint(), generator); if (existing != null) { generator = existing; } } return generator; } public FieldJoinPointGenerator getJoinPointGenerator(FieldInfo info) { if (info.isRead()) { FieldJoinPointGenerator generator = fieldReadJoinPoinGenerators.get(info.getJoinpoint()); if (generator == null) { generator = new FieldJoinPointGenerator(GeneratedClassAdvisor.this, info); initFieldReadJoinPointGeneratorsMap(); FieldJoinPointGenerator existing = fieldReadJoinPoinGenerators.putIfAbsent(info.getJoinpoint(), generator); if (existing != null) { generator = existing; } } return generator; } else { FieldJoinPointGenerator generator = (FieldJoinPointGenerator)joinPointGenerators.get(info.getJoinpoint()); if (generator == null) { generator = new FieldJoinPointGenerator(GeneratedClassAdvisor.this, info); initJoinPointGeneratorsMap(); FieldJoinPointGenerator existing = (FieldJoinPointGenerator)joinPointGenerators.putIfAbsent(info.getJoinpoint(), generator); if (existing != null) { generator = existing; } } return generator; } } public ConstructorJoinPointGenerator getJoinPointGenerator(ConstructorInfo info) { //We are the class advisor ConstructorJoinPointGenerator generator = constructionJoinPointGenerators.get(info.getJoinpoint()); if (generator == null) { generator = new ConstructorJoinPointGenerator(GeneratedClassAdvisor.this, info); initConstructionJoinPointGeneratorsMap(); ConstructorJoinPointGenerator existing = constructionJoinPointGenerators.putIfAbsent(info.getJoinpoint(), generator); if (existing != null) { generator = existing; } } return generator; } public ConstructionJoinPointGenerator getJoinPointGenerator(ConstructionInfo info) { ConstructionJoinPointGenerator generator = (ConstructionJoinPointGenerator)joinPointGenerators.get(info.getJoinpoint()); if (generator == null) { generator = new ConstructionJoinPointGenerator(GeneratedClassAdvisor.this, info); initJoinPointGeneratorsMap(); ConstructionJoinPointGenerator existing = (ConstructionJoinPointGenerator)joinPointGenerators.putIfAbsent(info.getJoinpoint(), generator); if (existing != null) { generator = existing; } } return generator; } public MethodByMethodJoinPointGenerator getJoinPointGenerator(MethodByMethodInfo info) { //An extra level of indirection since we distinguish between callers of method depending on //where the called method is defined (sub/super interfaces) ConcurrentHashMap, JoinPointGenerator> map = methodCalledByXXXJoinPointGenerators.get(info.getJoinpoint()); if (map == null) { map = new ConcurrentHashMap, JoinPointGenerator>(); initMethodCalledByConJoinPointGeneratorsMap(); ConcurrentHashMap, JoinPointGenerator> existing = methodCalledByXXXJoinPointGenerators.putIfAbsent(info.getJoinpoint(), map); if (existing != null) { map = existing; } } MethodByMethodJoinPointGenerator generator = (MethodByMethodJoinPointGenerator)map.get(info.getCalledClass()); if (generator == null) { generator = new MethodByMethodJoinPointGenerator(GeneratedClassAdvisor.this, info); MethodByMethodJoinPointGenerator existing = (MethodByMethodJoinPointGenerator)map.putIfAbsent(info.getCalledClass(), generator); if (existing != null) { generator = existing; } } return generator; } public ConByMethodJoinPointGenerator getJoinPointGenerator(ConByMethodInfo info) { ConByMethodJoinPointGenerator generator = (ConByMethodJoinPointGenerator)joinPointGenerators.get(info.getJoinpoint()); if (generator == null) { generator = new ConByMethodJoinPointGenerator(GeneratedClassAdvisor.this, info); initJoinPointGeneratorsMap(); ConByMethodJoinPointGenerator existing = (ConByMethodJoinPointGenerator)joinPointGenerators.putIfAbsent(info.getJoinpoint(), generator); if (existing != null) { generator = existing; } } return generator; } public ConByConJoinPointGenerator getJoinPointGenerator(ConByConInfo info) { //We are the class advisor ConByConJoinPointGenerator generator = (ConByConJoinPointGenerator)joinPointGenerators.get(info.getJoinpoint()); if (generator == null) { generator = new ConByConJoinPointGenerator(GeneratedClassAdvisor.this, info); initJoinPointGeneratorsMap(); ConByConJoinPointGenerator existing = (ConByConJoinPointGenerator)joinPointGenerators.putIfAbsent(info.getJoinpoint(), generator); if (existing != null) { generator = existing; } } return generator; } public MethodByConJoinPointGenerator getJoinPointGenerator(MethodByConInfo info) { //An extra level of indirection since we distinguish between callers of method depending on //where the called method is defined (sub/super interfaces) ConcurrentHashMap, JoinPointGenerator> map = methodCalledByXXXJoinPointGenerators.get(info.getJoinpoint()); if (map == null) { map = new ConcurrentHashMap, JoinPointGenerator>(); initMethodCalledByConJoinPointGeneratorsMap(); ConcurrentHashMap, JoinPointGenerator> exisiting = methodCalledByXXXJoinPointGenerators.putIfAbsent(info.getJoinpoint(), map); if (exisiting != null) { map = exisiting; } } MethodByConJoinPointGenerator generator = (MethodByConJoinPointGenerator)map.get(info.getCalledClass()); if (generator == null) { generator = new MethodByConJoinPointGenerator(GeneratedClassAdvisor.this, info); MethodByConJoinPointGenerator existing = (MethodByConJoinPointGenerator)map.putIfAbsent(info.getCalledClass(), generator); if (existing != null) { generator = existing; } } return generator; } public Object getPerClassAspect(AspectDefinition def) { return GeneratedClassAdvisor.super.getPerClassAspect(def); } public Object getPerClassJoinpointAspect(AspectDefinition def, Joinpoint joinpoint) { Map joinpoints = perClassJoinpointAspectDefinitions.get(def); if (joinpoints != null) { Object aspect = joinpoints.get(joinpoint); if (aspect != NULL_ASPECT) { return aspect; } } return null; } public GeneratedClassAdvisor getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices() { return null; } public void createMethodTables() throws Exception { GeneratedClassAdvisor.super.createMethodTables(); } public void createFieldTable() throws Exception { GeneratedClassAdvisor.super.createFieldTable(); } public void createConstructorTables() throws Exception { GeneratedClassAdvisor.super.createConstructorTables(); } public Set getPerInstanceAspectDefinitions() { return GeneratedClassAdvisor.super.getPerInstanceAspectDefinitions(); } public Map> getPerInstanceJoinpointAspectDefinitions() { return GeneratedClassAdvisor.super.getPerInstanceJoinpointAspectDefinitions(); } public void rebuildInterceptors() { version++; GeneratedClassAdvisor.super.rebuildInterceptors(); } public void rebuildInterceptorsForAddedBinding(AdviceBinding binding) { version++; GeneratedClassAdvisor.super.rebuildInterceptorsForAddedBinding(binding); } public void rebuildInterceptorsForRemovedBinding(AdviceBinding binding) { version++; GeneratedClassAdvisor.super.rebuildInterceptorsForRemovedBinding(binding); } public void resolveConstructorPointcut(AdviceBinding binding) { GeneratedClassAdvisor.super.resolveConstructorPointcut(binding); } public void resolveConstructionPointcut(AdviceBinding binding) { GeneratedClassAdvisor.super.resolveConstructionPointcut(binding); } public void finalizeConstructorChain(ConstructorInfo[] newConstructorInfos) { for (int i = 0; i < newConstructorInfos.length; i++) { ConstructorInfo info = newConstructorInfos[i]; ConstructorJoinPointGenerator generator = getJoinPointGenerator(info); Class clazz = info.getClazz(); if (clazz != null) finalizeChainAndRebindJoinPoint(oldInfos, info, generator, OldInfoMaps.INFOS); } } public void finalizeConstructionChain(ConstructionInfo[] newConstructionInfos) { for (int i = 0; i < newConstructionInfos.length; i++) { ConstructionInfo info = newConstructionInfos[i]; ConstructionJoinPointGenerator generator = getJoinPointGenerator(info); finalizeChainAndRebindJoinPoint(oldConstructionInfos, info, generator, OldInfoMaps.CONSTRUCTION_INFOS); } } public void makeAccessibleField(FieldInfo fi) { //If we do dynamic invokes the field will need to be accessible via reflection SecurityActions.setAccessible(fi.getField()); } public void makeAccessibleMethod(MethodInfo mi) { //If we do dynamic invokes the method will need to be accessible via reflection if private/protected SecurityActions.setAccessible(mi.getMethod()); } } private class InstanceAdvisorStrategy implements AdvisorStrategy { GeneratedClassAdvisor parent; boolean needsRebuild = true; public InstanceAdvisorStrategy(GeneratedClassAdvisor parent) { this.parent = parent; GeneratedClassAdvisor.this.version = parent.version; } public void initialise(Class clazz, AspectManager manager) { initialiseInfosForInstance(); GeneratedClassAdvisor.super.setManager(manager); manager.initialiseClassAdvisor(clazz, GeneratedClassAdvisor.this); } public void checkVersion() { if (needsRebuild || parent.version != GeneratedClassAdvisor.this.version) { doRebuildForInstance(); needsRebuild = false; } } public void createInterceptorChains() throws Exception { if (GeneratedClassAdvisor.super.initialized) { GeneratedClassAdvisor.super.createInterceptorChains(); } else { //Instance advisor copies the chains from the class advisor during its initialise stage GeneratedClassAdvisor.super.initialized = true; } } public MethodJoinPointGenerator getJoinPointGenerator(MethodInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } public FieldJoinPointGenerator getJoinPointGenerator(FieldInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } public ConstructorJoinPointGenerator getJoinPointGenerator(ConstructorInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } public ConstructionJoinPointGenerator getJoinPointGenerator(ConstructionInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } public MethodByMethodJoinPointGenerator getJoinPointGenerator(MethodByMethodInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } public ConByMethodJoinPointGenerator getJoinPointGenerator(ConByMethodInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } public ConByConJoinPointGenerator getJoinPointGenerator(ConByConInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } public MethodByConJoinPointGenerator getJoinPointGenerator(MethodByConInfo info) { //We are an instance advisor, get the generator from the class advisor return parent.getJoinPointGenerator(info); } /** * This is an instance advisor, so we will check with parent class advisor if the aspect * is already registered. If so, we should use the one from the parent advisor */ public Object getPerClassAspect(AspectDefinition def) { Object aspect = parent.getPerClassAspect(def); if (aspect != null) return aspect; return GeneratedClassAdvisor.super.getPerClassAspect(def); } /** * This is an instance advisor, so we will check with parent class advisor if the aspect * is already registered. If so, we should use the one from the parent advisor */ public Object getPerClassJoinpointAspect(AspectDefinition def, Joinpoint joinpoint) { Object aspect = parent.getPerClassJoinpointAspect(def, joinpoint); if (aspect != null)return aspect; return parent.getPerClassJoinpointAspect(def, joinpoint); } public GeneratedClassAdvisor getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices() { if (((Domain)getManager()).hasOwnDataWithEffectOnAdvices()) { return null; } return parent; } public void createMethodTables() throws Exception { GeneratedClassAdvisor.this.unadvisedMethods = parent.unadvisedMethods; GeneratedClassAdvisor.this.advisedMethods = parent.advisedMethods; } public void createFieldTable() throws Exception { GeneratedClassAdvisor.this.advisedFields = parent.advisedFields; } public void createConstructorTables() throws Exception { GeneratedClassAdvisor.this.constructors = parent.constructors; methodCalledByConBindings = new HashMap[constructors.length]; methodCalledByConInterceptors = new HashMap[constructors.length]; conCalledByConBindings = new HashMap[constructors.length]; conCalledByConInterceptors = new HashMap[constructors.length]; } public Set getPerInstanceAspectDefinitions() { return parent.getPerInstanceAspectDefinitions(); } public Map> getPerInstanceJoinpointAspectDefinitions() { return parent.getPerInstanceJoinpointAspectDefinitions(); } public synchronized void rebuildInterceptors() { if (getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices() != null && GeneratedClassAdvisor.this.version != parent.version) { adviceBindings.clear(); needsRebuild = true; } else { // check if it is initialized if (GeneratedClassAdvisor.this.fieldReadInfos == null) { try { GeneratedClassAdvisor.this.createInterceptorChains(); } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } else { GeneratedClassAdvisor.super.rebuildInterceptors(); } } } public void rebuildInterceptorsForAddedBinding(AdviceBinding binding) { if (getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices() != null && GeneratedClassAdvisor.this.version != parent.version) { adviceBindings.clear(); needsRebuild = true; } else { // check if it is initialized if (!GeneratedClassAdvisor.this.initialized) { try { GeneratedClassAdvisor.this.createInterceptorChains(); } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } else { GeneratedClassAdvisor.super.rebuildInterceptorsForAddedBinding(binding); } } } public void rebuildInterceptorsForRemovedBinding(AdviceBinding binding) { if (getClassAdvisorIfInstanceAdvisorWithNoOwnDataWithEffectOnAdvices() != null && GeneratedClassAdvisor.this.version != parent.version) { adviceBindings.clear(); needsRebuild = true; } else { // check if it is initialized if (!GeneratedClassAdvisor.this.initialized) { try { GeneratedClassAdvisor.this.createInterceptorChains(); } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } else { GeneratedClassAdvisor.super.rebuildInterceptorsForRemovedBinding(binding); } } } public void resolveConstructorPointcut(AdviceBinding binding) { //Since the instance already exists it makes no sense to have bindings for constructors } public void resolveConstructionPointcut(AdviceBinding binding) { //Since the instance already exists it makes no sense to have bindings for constructors } public void finalizeConstructorChain(ConstructorInfo[] newConstructorInfos) { //Since the instance already exists it makes no sense to have bindings for constructors } public void finalizeConstructionChain(ConstructionInfo[] newConstructionInfos) { //Since the instance already exists it makes no sense to have bindings for constructors } public void makeAccessibleField(FieldInfo fi) { //Do nothing, field was already made accessible in class advisor } public void makeAccessibleMethod(MethodInfo mi) { //Do nothing, field was already made accessible in class advisor } } enum OldInfoMaps{ INFOS, FIELD_READ_INFOS, CONSTRUCTION_INFOS; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/MethodInfo.java0000644000175000017500000000744611145122066030563 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import org.jboss.aop.joinpoint.MethodExecution; import org.jboss.aop.joinpoint.Joinpoint; import org.jboss.aop.joinpoint.MethodJoinpoint; import org.jboss.aop.util.MethodHashing; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * This class is here to eliminate a hash lookup in invokeMethod */ public class MethodInfo extends JoinPointInfo implements MethodExecution { private Method advisedMethod; /** @deprecated Use the accessors. Only public for backwards compatiblity with EJB3*/ public Method unadvisedMethod; private long hash; public MethodInfo() { } @SuppressWarnings("deprecation") public MethodInfo(Class clazz, long hash, long unadvisedHash, Advisor advisor) { super(advisor, clazz); try { this.hash = hash; advisedMethod = MethodHashing.findMethodByHash(clazz, hash); unadvisedMethod = MethodHashing.findMethodByHash(clazz, unadvisedHash); this.setAdvisor(advisor); } catch (Exception e) { throw new RuntimeException(e); } } /* * For copying */ @SuppressWarnings("deprecation") private MethodInfo(MethodInfo other) { super(other); this.advisedMethod = other.advisedMethod; this.unadvisedMethod = other.unadvisedMethod; this.hash = other.hash; } protected Joinpoint internalGetJoinpoint() { return new MethodJoinpoint(advisedMethod); } public JoinPointInfo copy() { return new MethodInfo(this); } @Deprecated public Method getAdvisedMethod() { return advisedMethod; } public Method getMethod() { return advisedMethod; } public void setAdvisedMethod(Method advisedMethod) { this.advisedMethod = advisedMethod; } public long getHash() { return hash; } public void setHash(long hash) { this.hash = hash; } @SuppressWarnings("deprecation") public Method getUnadvisedMethod() { return unadvisedMethod; } @SuppressWarnings("deprecation") public void setUnadvisedMethod(Method unadvisedMethod) { this.unadvisedMethod = unadvisedMethod; } public String toString() { StringBuffer sb = new StringBuffer("Method"); sb.append("["); sb.append("method=" + advisedMethod); sb.append("]"); return sb.toString(); } public T resolveAnnotation(Class annotation) { T val = super.resolveAnnotation(annotation); if (val != null) { return val; } Advisor advisor = getAdvisor(); if (advisor != null) { return getAdvisor().resolveTypedAnnotation(hash, advisedMethod, annotation); } return null; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/0000755000175000017500000000000011145122070026762 5ustar twernertwerner././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ElementArrayRegistryEntry.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ElementArrayRegistryEn0000644000175000017500000000271111145122062033313 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ElementArrayRegistryEntry extends ArrayRegistryEntry { Integer index;; ElementArrayRegistryEntry(Object owner, Integer index, Object array) { super(owner, false, array); this.index = index; } public Integer getIndex() { return index; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ShortArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ShortArrayElementReadI0000644000175000017500000000317311145122060033225 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ShortArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = -6743791579057380824L; short[] array; public ShortArrayElementReadInvocation(Interceptor[] interceptors, short[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Short(array[index]); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayAdvisor.java0000644000175000017500000004324111145122066032244 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.jboss.aop.AspectManager; import org.jboss.aop.advice.AdviceFactory; import org.jboss.aop.advice.GeneratedAdvisorInterceptor; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.advice.InterceptorFactory; import org.jboss.aop.advice.PerVmAdvice; import org.jboss.aop.advice.PrecedenceSorter; import org.jboss.aop.advice.ScopedInterceptorFactory; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ArrayAdvisor { static HashSet bindings = new LinkedHashSet(); static boolean updated; public static void addBinding(ArrayBinding arrayBinding) { ChainCreator.addBinding(arrayBinding); } public static void removeBinding(ArrayBinding arrayBinding) { ChainCreator.removeBinding(arrayBinding); } public static Interceptor[] getReadInterceptors() { return ChainCreator.getReadInterceptors(); } public static Interceptor[] getWriteInterceptors() { return ChainCreator.getWriteInterceptors(); } public static void updateArrayField(Object target, String fieldName, Object oldValue, Object newValue) { ArrayRegistry registry = ArrayRegistry.getInstance(); registry.removeFieldReference(target, fieldName, oldValue); registry.addFieldReference(target, fieldName, newValue); } public static void arrayWriteObject(Object array, int index, Object value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); ArrayRegistry registry = ArrayRegistry.getInstance(); if (registry.isRegistered(array)) { //The old value might be an array, remove references to that Object oldValue = ((Object[])array)[index]; boolean ignoreUpdate = (oldValue == value); if (!ignoreUpdate) { registry.removeElementReference(array, index, oldValue); //The new value might be an array if (value != null && value.getClass().isArray()) { registry.addElementReference(array, index, value); } if (interceptors != null) { ObjectArrayElementWriteInvocation invocation = new ObjectArrayElementWriteInvocation(interceptors, (Object[])array, index, value); invocation.invokeNext(); return; } } } ((Object[])array)[index] = value; } public static void arrayWriteInt(Object array, int index, int value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array) && ((int[])array)[index] != value) { IntArrayElementWriteInvocation invocation = new IntArrayElementWriteInvocation(interceptors, ((int[])array), index, value); invocation.invokeNext(); } else { ((int[])array)[index] = value; } } public static void arrayWriteByteOrBoolean(Object array, int index, byte value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { if (array instanceof boolean[]) { if (((boolean[])array)[index] != ByteBooleanConverter.toBoolean(value)) { BooleanArrayElementWriteInvocation invocation = new BooleanArrayElementWriteInvocation(interceptors, ((boolean[])array), index, ByteBooleanConverter.toBoolean(value)); invocation.invokeNext(); return; } ((boolean[])array)[index] = ByteBooleanConverter.toBoolean(value); } else { if (((byte[])array)[index] != value) { ByteArrayElementWriteInvocation invocation = new ByteArrayElementWriteInvocation(interceptors, ((byte[])array), index, value); invocation.invokeNext(); return; } ((byte[])array)[index] = value; } } } public static void arrayWriteChar(Object array, int index, char value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array) && ((char[])array)[index] != value) { CharArrayElementWriteInvocation invocation = new CharArrayElementWriteInvocation(interceptors, ((char[])array), index, value); invocation.invokeNext(); } else { ((char[])array)[index] = value; } } public static void arrayWriteDouble(Object array, int index, double value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array) && ((double[])array)[index] != value) { DoubleArrayElementWriteInvocation invocation = new DoubleArrayElementWriteInvocation(interceptors, ((double[])array), index, value); invocation.invokeNext(); } else { ((double[])array)[index] = value; } } public static void arrayWriteShort(Object array, int index, short value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array) && ((short[])array)[index] != value) { ShortArrayElementWriteInvocation invocation = new ShortArrayElementWriteInvocation(interceptors, ((short[])array), index, value); invocation.invokeNext(); } else { ((short[])array)[index] = value; } } public static void arrayWriteFloat(Object array, int index, float value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array) && ((float[])array)[index] != value) { FloatArrayElementWriteInvocation invocation = new FloatArrayElementWriteInvocation(interceptors, ((float[])array), index, value); invocation.invokeNext(); } else { ((float[])array)[index] = value; } } public static void arrayWriteLong(Object array, int index, long value) throws Throwable { Interceptor[] interceptors = getWriteInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array) && ((long[])array)[index] != value) { LongArrayElementWriteInvocation invocation = new LongArrayElementWriteInvocation(interceptors, ((long[])array), index, value); invocation.invokeNext(); } else { ((long[])array)[index] = value; } } public static Object arrayReadObject(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { ObjectArrayElementReadInvocation invocation = new ObjectArrayElementReadInvocation(interceptors, (Object[])array, index); return invocation.invokeNext(); } else { return ((Object[])array)[index]; } } public static int arrayReadInt(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { IntArrayElementReadInvocation invocation = new IntArrayElementReadInvocation(interceptors, (int[])array, index); return ((Integer)invocation.invokeNext()).intValue(); } else { return ((int[])array)[index]; } } public static byte arrayReadByteOrBoolean(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { if (array instanceof boolean[]) { BooleanArrayElementReadInvocation invocation = new BooleanArrayElementReadInvocation(interceptors, (boolean[])array, index); boolean b = ((Boolean)invocation.invokeNext()).booleanValue(); return ByteBooleanConverter.toByte(b); } else { ByteArrayElementReadInvocation invocation = new ByteArrayElementReadInvocation(interceptors, (byte[])array, index); return ((Byte)invocation.invokeNext()).byteValue(); } } else { if (array instanceof boolean[]) { return ByteBooleanConverter.toByte(((boolean[])array)[index]); } else { return ((byte[])array)[index]; } } } public static char arrayReadChar(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { CharArrayElementReadInvocation invocation = new CharArrayElementReadInvocation(interceptors, (char[])array, index); return ((Character)invocation.invokeNext()).charValue(); } else { return ((char[])array)[index]; } } public static double arrayReadDouble(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { DoubleArrayElementReadInvocation invocation = new DoubleArrayElementReadInvocation(interceptors, (double[])array, index); return ((Double)invocation.invokeNext()).doubleValue(); } else { return ((double[])array)[index]; } } public static float arrayReadFloat(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { FloatArrayElementReadInvocation invocation = new FloatArrayElementReadInvocation(interceptors, (float[])array, index); return ((Float)invocation.invokeNext()).floatValue(); } else { return ((float[])array)[index]; } } public static long arrayReadLong(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { LongArrayElementReadInvocation invocation = new LongArrayElementReadInvocation(interceptors, (long[])array, index); return ((Long)invocation.invokeNext()).longValue(); } else { return ((long[])array)[index]; } } public static short arrayReadShort(Object array, int index) throws Throwable { Interceptor[] interceptors = getReadInterceptors(); if (interceptors != null && ArrayRegistry.getInstance().isRegistered(array)) { ShortArrayElementReadInvocation invocation = new ShortArrayElementReadInvocation(interceptors, (short[])array, index); return ((Short)invocation.invokeNext()).shortValue(); } else { return ((short[])array)[index]; } } private static class ChainCreator { private static ReadWriteLock lock = new ReentrantReadWriteLock(); static Interceptor[] readInterceptors; static Interceptor[] writeInterceptors; public static void addBinding(ArrayBinding arrayBinding) { Lock writeLock = lock.writeLock(); writeLock.lock(); try { bindings.add(arrayBinding); updated = true; } finally { writeLock.unlock(); } } public static void removeBinding(ArrayBinding arrayBinding) { Lock writeLock = lock.writeLock(); writeLock.lock(); try { bindings.remove(arrayBinding); updated = true; } finally { writeLock.unlock(); } } public static Interceptor[] getReadInterceptors() { return getInterceptors(true); } public static Interceptor[] getWriteInterceptors() { return getInterceptors(false); } private static Interceptor[] getInterceptors(boolean read) { Lock readLock = lock.readLock(); readLock.lock(); boolean lockedRead = true; try { if (updated) { readLock.unlock(); lockedRead = false; Lock writeLock = lock.writeLock(); writeLock.lock(); try { if (updated) { //Create the interceptor chains ArrayList newReadInterceptors = new ArrayList(); ArrayList newWriteInterceptors = new ArrayList(); for (ArrayBinding binding : bindings) { InterceptorFactory[] factories = binding.getInterceptorFactories(); for (int i = 0; i < factories.length; i++) { Interceptor icptr = createInterceptor(factories[i]); if (icptr != null) { if (binding.isWrite()) { newWriteInterceptors.add(icptr); } if (binding.isRead()) { newReadInterceptors.add(icptr); } } } } readInterceptors = finalizeChain(newReadInterceptors); writeInterceptors = finalizeChain(newWriteInterceptors); updated = false; return (read) ? readInterceptors : writeInterceptors; } } finally { writeLock.unlock(); } } return (read) ? readInterceptors : writeInterceptors; } finally { if (lockedRead) { readLock.unlock(); } } } private static Interceptor[] finalizeChain(ArrayList newinterceptors) { Interceptor[] interceptors = (newinterceptors.size() > 0) ? newinterceptors.toArray(new Interceptor[newinterceptors.size()]) : null; if (interceptors != null) { if (interceptors[0] instanceof GeneratedAdvisorInterceptor) { } interceptors = PrecedenceSorter.applyPrecedence(interceptors, AspectManager.instance()); } return interceptors; } private static Interceptor createInterceptor(InterceptorFactory factory) { //TODO: must be fixed! // if (factory instanceof GeneratedOnly) // { // throw new RuntimeException("Before/After/Throwing is only supported for Generated Advisors"); // } try { if (factory.isDeployed()) { if (factory instanceof AdviceFactory) { return PerVmAdvice.generateOptimized(null, AspectManager.instance(), factory.getAdvice(), factory.getAspect()); } else if (factory instanceof ScopedInterceptorFactory) { return (Interceptor) AspectManager.instance().getPerVMAspect(factory.getAspect()); } } return null; } catch (Exception e) { throw new RuntimeException(e); } } } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/DoubleArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/DoubleArrayElementRead0000644000175000017500000000317711145122060033233 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class DoubleArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = 4414714543578046462L; double[] array; public DoubleArrayElementReadInvocation(Interceptor[] interceptors, double[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Double(array[index]); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayElementWriteInvoc0000644000175000017500000000301011145122060033300 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public abstract class ArrayElementWriteInvocation extends ArrayElementInvocation { private static final long serialVersionUID = 1L; public ArrayElementWriteInvocation(Interceptor[] interceptors, Object array, int index) { super(interceptors, array, index); } public abstract Object getValue(); } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayRegistryEntry.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayRegistryEntry.jav0000644000175000017500000000463611145122070033326 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import java.lang.ref.WeakReference; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public abstract class ArrayRegistryEntry { /** WeakReference to the object or array containing the reference */ WeakReference owner; /** WeakReference to the referenced array */ WeakReference array; /** True if the object referencing the array is a "normal" object, false if it ia an array */ boolean ownerIsRoot; ArrayRegistryEntry(Object owner, boolean ownerIsRoot, Object array) { this.owner = new WeakReference(owner); this.array = new WeakReference(array); this.ownerIsRoot = ownerIsRoot; if (ownerIsRoot && owner.getClass().isArray()) { throw new RuntimeException("Owner is root and an array was passed in"); } if (!ownerIsRoot && !owner.getClass().isArray()) { throw new RuntimeException("Owner is not root and no array was passed in"); } } public Object getArray() { if (array != null) { return array.get(); } return null; } public Object getOwner() { if (owner != null) { return owner.get(); } return null; } public boolean isOwnerRoot() { return ownerIsRoot; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ByteArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ByteArrayElementWriteI0000644000175000017500000000355011145122054033252 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ByteArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = -3311231820298166088L; byte[] array; byte value; public ByteArrayElementWriteInvocation(Interceptor[] interceptors, byte[] target, int index, byte value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Byte(value); } public byte getByteValue() { return value; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/IntArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/IntArrayElementReadInv0000644000175000017500000000316311145122066033231 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class IntArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = 407921822383443705L; int[] array; public IntArrayElementReadInvocation(Interceptor[] interceptors, int[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Integer(array[index]); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/IntArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/IntArrayElementWriteIn0000644000175000017500000000354311145122056033263 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class IntArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = -3311231820298166088L; int[] array; int value; public IntArrayElementWriteInvocation(Interceptor[] interceptors, int[] target, int index, int value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Integer(value); } public int getIntValue() { return value; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayRegistry.java0000644000175000017500000003022511145122054032440 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.WeakHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ArrayRegistry { private final static ArrayRegistryEntryFactory ELEMENT_ARRAY_REGISTRY_ENTRY_FACTORY = new ElementArrayRegistryEntryFactory(); private final static ArrayRegistryEntryFactory FIELD_ARRAY_REGISTRY_ENTRY_FACTORY = new FieldArrayRegistryEntryFactory(); private ArrayReferenceBuilder referenceBuilder = new ArrayReferenceBuilder(); private static ArrayRegistry singleton = new ArrayRegistry(); private ReadWriteLock lock = new ReentrantReadWriteLock(); private WeakHashMap>> cache = new WeakHashMap>>(); public static ArrayRegistry getInstance() { return singleton; } private ArrayRegistry() { } public void addFieldReference(Object owner, String fieldName, Object array) { if (array == null) { return; } addReference(owner, fieldName, array, FIELD_ARRAY_REGISTRY_ENTRY_FACTORY); } public void addElementReference(Object owner, int index, Object array) { if (array == null) { return; } addReference(owner, new Integer(index), array, ELEMENT_ARRAY_REGISTRY_ENTRY_FACTORY); } public void addReference(Object owner, Object qualifier, Object array, ArrayRegistryEntryFactory factory) { if (array == null) { return; } Lock writeLock = lock.writeLock(); writeLock.lock(); try { WeakHashMap> arrayReferences = cache.get(array); if (arrayReferences == null) { arrayReferences = new WeakHashMap>(); cache.put(array, arrayReferences); } HashMap ownerReferences = arrayReferences.get(owner); if (ownerReferences == null) { ownerReferences = new HashMap(); arrayReferences.put(owner, ownerReferences); } ArrayRegistryEntry regEntry = ownerReferences.get(qualifier); if (regEntry == null || regEntry.getArray() != array) { ArrayRegistryEntry entry = factory.createArrayRegistryEntry(owner, qualifier, factory); ownerReferences.put(qualifier, entry); } addNestedArrays(array); } finally { writeLock.unlock(); } } public void removeFieldReference(Object owner, String fieldName, Object array) { if (array == null) { return; } removeReference(owner, fieldName, array); } public void removeElementReference(Object owner, int index, Object array) { if (array == null) { return; } removeReference(owner, new Integer(index), array); } public void removeReference(Object owner, Object qualifier, Object array) { if (array == null) { return; } Lock writeLock = lock.writeLock(); writeLock.lock(); try { WeakHashMap> arrayReferences = cache.get(array); if (arrayReferences != null) { HashMap ownerReferences = arrayReferences.get(owner); if (ownerReferences != null) { ArrayRegistryEntry regEntry = ownerReferences.remove(qualifier); if (regEntry != null) { if (ownerReferences.size() == 0) { arrayReferences.remove(owner); if (arrayReferences.size() == 0) { cache.remove(array); } } ///Should this be here or below? removeNestedArrays(array); } } } // removeNestedArrays(owner, array); } finally { writeLock.unlock(); } } public boolean isRegistered(Object array) { Lock readLock = lock.readLock(); readLock.lock(); try { WeakHashMap> arrayReferences = cache.get(array); if (arrayReferences == null) { return false; } return true; } finally { readLock.unlock(); } } public List getArrayOwners(Object array) { Lock readLock = lock.readLock(); readLock.lock(); try { return referenceBuilder.getArrayReferences(array); } finally { readLock.unlock(); } } private void addNestedArrays(Object array) { if (array == null) { return; } ArrayType type = isArray(array); if (type == ArrayType.MULTIDIM_ARRAY) { for (int i = 0 ; i < ((Object[])array).length ; i++) { addElementReference(array, i, ((Object[])array)[i]); addNestedArrays(((Object[])array)[i]); } } else if (type == ArrayType.OBJECT_ARRAY) { for (int i = 0 ; i < ((Object[])array).length ; i++) { Object val = ((Object[])array)[i]; if (val != null && val.getClass().isArray()) { addElementReference(array, i, ((Object[])array)[i]); addNestedArrays(((Object[])array)[i]); } } } } private void removeNestedArrays(Object array) { if (array == null) { return; } ArrayType type = isArray(array); if (type == ArrayType.MULTIDIM_ARRAY) { for (int i = 0 ; i < ((Object[])array).length ; i++) { removeElementReference(array, i, ((Object[])array)[i]); removeNestedArrays(((Object[])array)[i]); } } else if (type == ArrayType.OBJECT_ARRAY) { for (int i = 0 ; i < ((Object[])array).length ; i++) { Object val = ((Object[])array)[i]; if (val != null && val.getClass().isArray()) { removeElementReference(array, i, ((Object[])array)[i]); removeNestedArrays(((Object[])array)[i]); } } } } private ArrayType isArray(Object arrayCandidate) { Class candidateClass = arrayCandidate.getClass(); if (candidateClass.isArray()) { Class componentType = candidateClass.getComponentType(); if (componentType.isArray()) { return ArrayType.MULTIDIM_ARRAY; } if (componentType == Object.class) { return ArrayType.OBJECT_ARRAY; } } return ArrayType.NOT_ARRAY; } private interface ArrayRegistryEntryFactory { ArrayRegistryEntry createArrayRegistryEntry(Object owner, Object qualifier, Object array); } private static class FieldArrayRegistryEntryFactory implements ArrayRegistryEntryFactory { public ArrayRegistryEntry createArrayRegistryEntry(Object owner, Object qualifier, Object array) { return new FieldArrayRegistryEntry(owner, (String)qualifier, array); } } private static class ElementArrayRegistryEntryFactory implements ArrayRegistryEntryFactory { public ArrayRegistryEntry createArrayRegistryEntry(Object owner, Object qualifier, Object array) { return new ElementArrayRegistryEntry(owner, (Integer)qualifier, array); } } private class ArrayReferenceBuilder { private List getArrayReferences(Object array) { List references = null; WeakHashMap> arrayReferences = cache.get(array); if (arrayReferences != null && arrayReferences.size() > 0) { for (Object owner : arrayReferences.keySet()) { HashMap ownerReferences = arrayReferences.get(owner); for (Object qualifier : ownerReferences.keySet()) { ArrayRegistryEntry regEntry = ownerReferences.get(qualifier); if (regEntry.isOwnerRoot()) { ArrayReference reference = getRootReference((FieldArrayRegistryEntry)regEntry); if (reference != null) { if (references == null) { references = new ArrayList(); } references.add(reference); } } else { List parentReferences = getElementReferences((ElementArrayRegistryEntry)regEntry); if (parentReferences != null) { if (references == null) { references = new ArrayList(); } references.addAll(parentReferences); } } } } } return references; } private ArrayReference getRootReference(FieldArrayRegistryEntry regEntry) { Object root = regEntry.getOwner(); if (root != null) { String fieldName = regEntry.getFieldName(); return new ArrayReferenceImpl(root, fieldName); } return null; } private List getElementReferences(ElementArrayRegistryEntry regEntry) { Object ownerArray = regEntry.getOwner(); if (ownerArray != null) { List references = getArrayReferences(ownerArray); if (references != null && references.size() > 0) { for (ArrayReference reference : references) { ((ArrayReferenceImpl)reference).addNestedArrayIndex(regEntry.getIndex()); } } return references; } return null; } } private enum ArrayType { NOT_ARRAY,MULTIDIM_ARRAY,OBJECT_ARRAY; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ByteArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ByteArrayElementReadIn0000644000175000017500000000316411145122062033211 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ByteArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = 407921822383443705L; byte[] array; public ByteArrayElementReadInvocation(Interceptor[] interceptors, byte[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Byte(array[index]); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/CharArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/CharArrayElementReadIn0000644000175000017500000000317311145122054033164 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class CharArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = -8421466785835226302L; char[] array; public CharArrayElementReadInvocation(Interceptor[] interceptors, char[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Character(array[index]); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayReferenceImpl.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayReferenceImpl.jav0000644000175000017500000000447211145122064033215 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import java.util.ArrayList; import java.util.List; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ArrayReferenceImpl implements ArrayReference { Object root; String rootField; ArrayList nestedArrayIndices; public ArrayReferenceImpl(Object root, String rootField) { this.root = root; this.rootField = rootField; } public Object getRootObject() { return root; } public String getRootField() { return rootField; } public void addNestedArrayIndex(Integer index) { if (nestedArrayIndices == null) { nestedArrayIndices = new ArrayList(); } nestedArrayIndices.add(index); } public List getNestedArrayIndices() { return nestedArrayIndices; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(root + "." + rootField); if (nestedArrayIndices != null && nestedArrayIndices.size() > 0) { for (Integer index : nestedArrayIndices) { sb.append("[" + index + "]"); } } return sb.toString(); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayReference.java0000644000175000017500000000476111145122056032536 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import java.util.List; /** * Contains information about one reference to a particular array. * * @author Kabir Khan * @version $Revision: 1.1 $ */ public interface ArrayReference { /** * @return The object containing the field with the array reference. If the root field is non static this * will be the reference of the instance, if the field is static it will be the class */ Object getRootObject(); /** * @return The field with the array reference */ String getRootField(); /** * If the root field is a direct reference to the array this will be null. If the field is an array and the reference is from within * a nested array, this will be a list of the indexes from the top to get to the array.
* * So if we have: *
    * class POJO{
    *   int[] i;
    * }
    * POJO pojo = new POJO();
    * int[] i arr = new int[]{1};
    * pojo.i = arr;
    * 
* getNestedArrayIndices will be null for arr.If we have: *
    * class POJO{
    *   int[][][] i;
    * }
    * POJO pojo = new POJO();
    * int[] arr = new int[]{1};
    * pojo.i = new int[][][]{new int[][]{new int[]{1}}, new int[][]{new int[]{2}, new int[]{3}, arr}};
    * 
* getNestedArrayIndices will {1,2} for arr. * @ return the nested indices of the array. */ List getNestedArrayIndices(); } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ObjectArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ObjectArrayElementRead0000644000175000017500000000316311145122066033230 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ObjectArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = 2579696791090966825L; Object[] array; public ObjectArrayElementReadInvocation(Interceptor[] interceptors, Object[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return array[index]; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ShortArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ShortArrayElementWrite0000644000175000017500000000356111145122064033340 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ShortArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = -8003520567342434348L; short[] array; short value; public ShortArrayElementWriteInvocation(Interceptor[] interceptors, short[] target, int index, short value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Short(value); } public short getShortValue() { return value; } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ByteBooleanConverter.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ByteBooleanConverter.j0000644000175000017500000000321011145122054033226 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ByteBooleanConverter { private static final byte BOOLEAN_FALSE = 0; private static final byte BOOLEAN_TRUE = 1; public static byte toByte(boolean b) { return (b) ? BOOLEAN_TRUE : BOOLEAN_FALSE; } public static boolean toBoolean(byte b) { if (b == BOOLEAN_FALSE) return false; else if (b == BOOLEAN_TRUE) return true; throw new RuntimeException("Invalid byte " + b + " cannot be converted to a boolean"); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/FieldArrayRegistryEntry.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/FieldArrayRegistryEntr0000644000175000017500000000273011145122056033317 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class FieldArrayRegistryEntry extends ArrayRegistryEntry { String fieldName; FieldArrayRegistryEntry(Object owner, String fieldName, Object array) { super(owner, true, array); this.fieldName = fieldName; } public String getFieldName() { return fieldName; } }././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/CharArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/CharArrayElementWriteI0000644000175000017500000000355511145122060033226 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class CharArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = -7731135396849504354L; char[] array; char value; public CharArrayElementWriteInvocation(Interceptor[] interceptors, char[] target, int index, char value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Character(value); } public char getCharValue() { return value; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayBinding.java0000644000175000017500000000512511145122060032200 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jboss.aop.advice.InterceptorFactory; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ArrayBinding { protected String name; protected Type type; protected InterceptorFactory[] interceptorFactories = new InterceptorFactory[0]; public ArrayBinding(String name, InterceptorFactory[] factories, Type type) { this.name = name; interceptorFactories = factories; this.type = type; } public void addInterceptorFactory(InterceptorFactory factory) { List list = Arrays.asList(interceptorFactories); list = new ArrayList(list); list.add(factory); interceptorFactories = list.toArray(new InterceptorFactory[list.size()]); } public String getName() { return name; } public InterceptorFactory[] getInterceptorFactories() { return interceptorFactories; } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof ArrayBinding)) return false; return ((ArrayBinding) obj).getName().equals(name); } public int hashCode() { return name.hashCode(); } public boolean isRead() { return type == Type.READ_ONLY || type == Type.READ_WRITE; } public boolean isWrite() { return type == Type.WRITE_ONLY || type == Type.READ_WRITE; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/Type.java0000644000175000017500000000232111145122054030546 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public enum Type { READ_WRITE, READ_ONLY, WRITE_ONLY } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ObjectArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ObjectArrayElementWrit0000644000175000017500000000344711145122062033303 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ObjectArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = 4256767659280908515L; Object[] array; Object value; public ObjectArrayElementWriteInvocation(Interceptor[] interceptors, Object[] target, int index, Object value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return value; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayElementReadInvoca0000644000175000017500000000273511145122060033237 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public abstract class ArrayElementReadInvocation extends ArrayElementInvocation { private static final long serialVersionUID = 1L; public ArrayElementReadInvocation(Interceptor[] interceptors, Object array, int index) { super(interceptors, array, index); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/FloatArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/FloatArrayElementReadI0000644000175000017500000000317211145122054033175 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class FloatArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = 1588317122571729022L; float[] array; public FloatArrayElementReadInvocation(Interceptor[] interceptors, float[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Float(array[index]); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/LongArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/LongArrayElementReadIn0000644000175000017500000000316611145122064033211 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class LongArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = -6196706501416214971L; long[] array; public LongArrayElementReadInvocation(Interceptor[] interceptors, long[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Long(array[index]); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/LongArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/LongArrayElementWriteI0000644000175000017500000000354711145122062033253 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class LongArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = -609480261599580470L; long[] array; long value; public LongArrayElementWriteInvocation(Interceptor[] interceptors, long[] target, int index, long value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Long(value); } public long getLongValue() { return value; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayElementInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayElementInvocation0000644000175000017500000001171711145122062033337 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; import org.jboss.aop.Advisor; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.joinpoint.Invocation; import org.jboss.aop.joinpoint.InvocationBase; import org.jboss.aop.metadata.MetaDataResolver; import org.jboss.util.NotImplementedException; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public abstract class ArrayElementInvocation extends InvocationBase { private static final long serialVersionUID = 1L; int index; public ArrayElementInvocation(Interceptor[] interceptors, Object array, int index) { super(interceptors); super.setTargetObject(array); this.index = index; } public int getIndex() { return index; } /** * Invoke on the next interceptor in the chain. If this is already * the end of the chain, reflection will call the constructor, field, or * method you are invoking on. */ public Object invokeNext() throws Throwable { if (interceptors != null && currentInterceptor < interceptors.length) { try { return interceptors[currentInterceptor++].invoke(this); } finally { // so that interceptors like clustering can reinvoke down the chain currentInterceptor--; } } return invokeTarget(); } public abstract Object invokeTarget(); @Override public void addResponseAttachment(Object key, Object val) { throw new NotImplementedException(); } @Override public Advisor getAdvisor() { throw new NotImplementedException(); } @Override public int getCurrentInterceptor() { throw new NotImplementedException(); } @Override public Object getResponseAttachment(Object key) { throw new NotImplementedException(); } @Override public Map getResponseContextInfo() { throw new NotImplementedException(); } @Override public Object resolveAnnotation(Class annotation) { throw new NotImplementedException(); } @Override public Object resolveAnnotation(Class[] annotations) { throw new NotImplementedException(); } @Override public Object resolveClassAnnotation(Class annotation) { throw new NotImplementedException(); } @Override public T resolveTypedAnnotation(Class annotation) { throw new NotImplementedException(); } @Override public T resolveTypedAnnotation(Class[] annotations) { throw new NotImplementedException(); } @Override public T resolveTypedClassAnnotation(Class annotation) { throw new NotImplementedException(); } @Override public Object resolveClassMetaData(Object key, Object attr) { throw new NotImplementedException(); } @Override public void setAdvisor(Advisor advisor) { throw new NotImplementedException(); } @Override public void setInstanceResolver(MetaDataResolver instanceResolver) { throw new NotImplementedException(); } @Override public void setResponseContextInfo(Map responseContextInfo) { throw new NotImplementedException(); } public Invocation copy() { throw new NotImplementedException(); } public Invocation getWrapper(Interceptor[] newchain) { throw new NotImplementedException(); } public List getArrayOwners() { ArrayRegistry registry = ArrayRegistry.getInstance(); return registry.getArrayOwners(targetObject); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/FloatArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/FloatArrayElementWrite0000644000175000017500000000356011145122066033307 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class FloatArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = 2124265298388536292L; float[] array; float value; public FloatArrayElementWriteInvocation(Interceptor[] interceptors, float[] target, int index, float value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Float(value); } public float getFloatValue() { return value; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/DoubleArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/DoubleArrayElementWrit0000644000175000017500000000357111145122056033310 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class DoubleArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = 4952638087031381514L; double[] array; double value; public DoubleArrayElementWriteInvocation(Interceptor[] interceptors, double[] target, int index, double value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Double(value); } public double getDoubleValue() { return value; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/ArrayReplacement.java0000644000175000017500000000573111145122062033072 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import javassist.CtClass; import org.jboss.aop.Advisor; import org.jboss.aop.pointcut.TypeMatcher; import org.jboss.aop.pointcut.Util; import org.jboss.aop.pointcut.ast.ASTStart; import org.jboss.aop.pointcut.ast.ClassExpression; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class ArrayReplacement { private String name; protected ClassExpression classExpr; protected ASTStart ast; public ArrayReplacement(String name, String exp) { this.name = name; this.classExpr = new ClassExpression(exp); } public ArrayReplacement(String name, ASTStart ast) { this.name = name; this.ast = ast; } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof ArrayReplacement)) return false; return ((ArrayReplacement) obj).getName().equals(name); } public int hashCode() { return name.hashCode(); } public String getName() { return name; } public String getClassExpr() { if (classExpr == null) return null; return classExpr.getOriginal(); } public ASTStart getAst() { return ast; } public boolean matches(Advisor advisor, CtClass clazz) throws Exception { if (classExpr != null) return Util.matchesClassExpr(classExpr, clazz, advisor); else { TypeMatcher matcher = new TypeMatcher(advisor, clazz); return ((Boolean) ast.jjtAccept(matcher, null)).booleanValue(); } } public boolean matches(Advisor advisor, Class clazz) { if (classExpr != null) return Util.matchesClassExpr(classExpr, clazz, advisor); else { TypeMatcher matcher = new TypeMatcher(advisor, clazz); return ((Boolean) ast.jjtAccept(matcher, null)).booleanValue(); } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/BooleanArrayElementWriteInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/BooleanArrayElementWri0000644000175000017500000000360311145122064033264 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class BooleanArrayElementWriteInvocation extends ArrayElementWriteInvocation { private static final long serialVersionUID = -8806734067322751711L; boolean[] array; boolean value; public BooleanArrayElementWriteInvocation(Interceptor[] interceptors, boolean[] target, int index, boolean value) { super(interceptors, target, index); this.value = value; this.array = target; } @Override public Object invokeTarget() { array[index] = value; return null; } @Override public Object getValue() { return new Boolean(value); } public boolean getBooleanValue() { return value; } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/BooleanArrayElementReadInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/array/BooleanArrayElementRea0000644000175000017500000000320411145122056033230 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.array; import org.jboss.aop.advice.Interceptor; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class BooleanArrayElementReadInvocation extends ArrayElementReadInvocation { private static final long serialVersionUID = 4894358007089083877L; boolean[] array; public BooleanArrayElementReadInvocation(Interceptor[] interceptors, boolean[] target, int index) { super(interceptors, target, index); array = target; } public Object invokeTarget() { return new Boolean(array[index]); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/NotFoundInDispatcherException.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/NotFoundInDispatcherExceptio0000644000175000017500000000271611145122060033327 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; /** * * @author Kabir Khan * @version $Revision$ */ public class NotFoundInDispatcherException extends DispatcherConnectException { private static final long serialVersionUID = -5020740195889379757L; Object oid; public NotFoundInDispatcherException(Object oid) { super("Object with oid: " + oid + " was not found in the Dispatcher"); this.oid = oid; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/ClassAdvisor.java0000644000175000017500000033257311145122066031126 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import gnu.trove.TLongObjectHashMap; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.ClassifiedBindingAndPointcutCollection; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.instrument.ConstructorExecutionTransformer; import org.jboss.aop.instrument.FieldAccessTransformer; import org.jboss.aop.instrument.MethodExecutionTransformer; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.joinpoint.ConstructorCalledByConstructorInvocation; import org.jboss.aop.joinpoint.ConstructorCalledByConstructorJoinpoint; import org.jboss.aop.joinpoint.ConstructorCalledByMethodInvocation; import org.jboss.aop.joinpoint.ConstructorCalledByMethodJoinpoint; import org.jboss.aop.joinpoint.ConstructorInvocation; import org.jboss.aop.joinpoint.FieldJoinpoint; import org.jboss.aop.joinpoint.FieldReadInvocation; import org.jboss.aop.joinpoint.FieldWriteInvocation; import org.jboss.aop.joinpoint.Invocation; import org.jboss.aop.joinpoint.MethodCalledByConstructorInvocation; import org.jboss.aop.joinpoint.MethodCalledByConstructorJoinpoint; import org.jboss.aop.joinpoint.MethodCalledByMethodInvocation; import org.jboss.aop.joinpoint.MethodCalledByMethodJoinpoint; import org.jboss.aop.joinpoint.MethodInvocation; import org.jboss.aop.metadata.ClassMetaDataBinding; import org.jboss.aop.metadata.ClassMetaDataLoader; import org.jboss.aop.util.Advisable; import org.jboss.aop.util.BindingClassifier; import org.jboss.aop.util.ConstructorComparator; import org.jboss.aop.util.FieldComparator; import org.jboss.aop.util.MethodHashing; import org.jboss.aop.util.ReflectUtils; import org.jboss.aop.util.UnmodifiableEmptyCollections; import org.jboss.aop.util.logging.AOPLogger; import org.jboss.util.NotImplementedException; /** * Advises a class and provides access to the class's aspect chain. * Each advisable class has an associated Advisor instance. * References methods using int IDs rather than the actual * instances for * optimal performance. Provides ability to invoke methods on an advised * object without advice (see * Advisor.invokeWithoutAdvisement()). * * @author Bill Burke * @version $Revision: 81449 $ */ public class ClassAdvisor extends Advisor { private static final AOPLogger logger = AOPLogger.getLogger(ClassAdvisor.class); /** * Suffix added to unadvised methods. */ public static final String NOT_TRANSFORMABLE_SUFFIX = "$aop"; //Common sense suggests that this should be lazily initialised for generated advisors, profiling shows that is a major performance hit... protected TLongObjectHashMap unadvisedMethods = new TLongObjectHashMap(); //Information about method by method caller pointcuts, lazy initialized when needed private volatile MethodByMethodData methodByMethodData; //Information about con by method caller pointcuts, lazy initialized when needed private volatile ConByMethodData conByMethodData; // caller pointcut support for constructors calling methods protected HashMap[] methodCalledByConBindings; // TLongObjectHashMap contains Objects of type ArrayList protected HashMap[] methodCalledByConInterceptors; //TLongObjectHashMap contains Objects of type MethodByConInfo protected HashMap>> backrefMethodCalledByConstructorBindings = new HashMap>>(); // caller pointcut support for constructors calling methods protected HashMap[] conCalledByConBindings; // TLongObjectHashMap contains Objects of type ArrayList protected HashMap[] conCalledByConInterceptors; //TLongObjectHashMap contains Objects of type ConByConInfo protected HashMap>> backrefConCalledByConstructorBindings = new HashMap>>(); // Used by instrumentor to access separate interceptor chains for read and write access /** @deprecated Use fieldReadInfos instead*/ private Interceptor[][] fieldReadInterceptors; protected FieldInfo[] fieldReadInfos; /** @deprecated Use fieldWriteInfos instead */ private Interceptor[][] fieldWriteInterceptors; protected FieldInfo[] fieldWriteInfos; protected Field[] advisedFields; //PER_JOINPOINT aspects for static fields or PER_CLASS_JOINPOINT aspects //all apply to fields, and we need this since the same aspect should be used for //read and write private volatile HashMap> fieldAspectsWithNoInstance = new HashMap>(); protected boolean initialized = false; public ClassAdvisor(String classname, AspectManager manager) { super(classname, manager); } public ClassAdvisor(Class clazz, AspectManager manager) { this(clazz.getName(), manager); this.clazz = clazz; } /** * This method is to support PER_JOINPOINT scoping of Aspects for static fields * Fields are special in that a get and set do not create separate aspect instances. * * Also used to support PER_CLASS_JOINPOINT, since that behaves similarly to static fields * * @param joinpoint * @param def * @return */ public Object getFieldAspect(FieldJoinpoint joinpoint, AspectDefinition def) { HashMap map = fieldAspectsWithNoInstance.get(def); if (map == null) { synchronized (fieldAspectsWithNoInstance) { map = fieldAspectsWithNoInstance.get(def); if (map == null) { map = new HashMap(); fieldAspectsWithNoInstance.put(def, map); } } } if (map.containsKey(joinpoint)) { return map.get(joinpoint); } synchronized (map) { if (map.containsKey(joinpoint)) { return map.get(joinpoint); } Object aspect = def.getFactory().createPerJoinpoint(this, joinpoint); map.put(joinpoint, aspect); return aspect; } } public Field[] getAdvisedFields() { return advisedFields; } public TLongObjectHashMap getAdvisedMethods() { return advisedMethods; } protected TLongObjectHashMap getUnadvisedMethods() { return unadvisedMethods; } @Override public Constructor[] getConstructors() { return constructors; } public TLongObjectHashMap getMethodCalledByMethodInterceptors() { return getMethodByMethodData().getMethodCalledByMethodInterceptors(); } public HashMap[] getMethodCalledByConInterceptors() { return methodCalledByConInterceptors; } public HashMap[] getConCalledByConInterceptors() { return conCalledByConInterceptors; } public TLongObjectHashMap getConCalledByMethodInterceptors() { return getConByMethodData().getConCalledByMethodInterceptors(); } public TLongObjectHashMap getMethodCalledByMethodBindings() { return getMethodByMethodData().getMethodCalledByMethodBindings(); } /** @deprecated use getFieldReadInfos instead */ public Interceptor[][] getFieldReadInterceptors() { throw new NotImplementedException("Use getFieldReadInfos"); } public FieldInfo[] getFieldReadInfos() { return fieldReadInfos; } /** @deprecated use getFieldWriteInfos instead */ public Interceptor[][] getFieldWriteInterceptors() { throw new NotImplementedException("Use getFieldWriteInfos"); } public FieldInfo[] getFieldWriteInfos() { return fieldWriteInfos; } public TLongObjectHashMap getMethodInterceptors() { return methodInfos.infos; } /** * Constructs a new helper. */ public synchronized void attachClass(final Class clazz) { if (initialized) return; try { //long start = System.currentTimeMillis(); final AspectManager theManager = manager; //register class loader: necessary when clazz was precompiled through aopc manager.registerClassLoader(SecurityActions.getClassLoader(clazz)); AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { theManager.attachMetaData(ClassAdvisor.this, clazz); interfaceIntroductions.clear(); // metadata should always come before creation of interceptor chain // so that the interceptor factories have access to metadata. // and so that metadata joinpoints can be checked // ClassAdvisor.this.clazz = clazz; // Also metadata needs to be applied before applyIntroductionPointcuts because // an annotation may be triggered by XML metadata as well as // after populateMixinMethods so that proper metadata is applied to added methods rebindClassMetaData(); theManager.applyInterfaceIntroductions(ClassAdvisor.this, clazz); createFieldTable(); createMethodTables(); createConstructorTables(); populateMixinMethods(); // metadata should always come before creation of interceptor chain // so that the interceptor factories have access to metadata. // and so that metadata joinpoints can be checked // // Also metadata needs to be applied before applyIntroductionPointcuts because // an annotation may be triggered by XML metadata as well as // after populateMixinMethods so that proper metadata is applied to added methods rebindClassMetaData(); createInterceptorChains(); initialized = true; return null; } }); /* // System.out.println("******************"); // System.out.println("attachClass: " + clazz.getName() + " took " + (System.currentTimeMillis() - start)); // System.out.println("******************"); */ } catch (PrivilegedActionException e) { throw new RuntimeException(e.getException()); } } /** * Get method from clazz .If method not found,get the method * from the clazz's parent. */ static private Method getMethod(Class clazz, Method method) throws NoSuchMethodException { if ((clazz == null) || (clazz.equals(Object.class))) throw new NoSuchMethodException(method.getName()); try { String wrappedName = ClassAdvisor.notAdvisedMethodName(clazz.getName(), method.getName()); return clazz.getMethod(wrappedName, method.getParameterTypes()); } catch (NoSuchMethodException e) { return getMethod(clazz.getSuperclass(), method); } } /** * Get a constructor's index in the class. Returns -1 if not there */ public int getConstructorIndex(Constructor constructor) { for (int i = 0; i < constructors.length; i++) { if (constructor.equals(constructors[i])) { return i; } } return -1; } /** * Get a field's index in the class. Returns -1 if not there */ public int getFieldIndex(Field field) { for (int i = 0; i < advisedFields.length; i++) { if (field.equals(advisedFields[i])) { return i; } } return -1; } /** * Put mixin methods from mixin class into unadvisedMethods map so that * they can be correctly invoked upon. */ protected void populateMixinMethods() throws Exception { ArrayList introductions = getInterfaceIntroductions(); for (InterfaceIntroduction introduction : introductions) { ArrayList mixins = introduction.getMixins(); for (int i = 0; i < mixins.size(); i++) { InterfaceIntroduction.Mixin mixin = mixins.get(i); ClassLoader cl = getClassLoader(); if (cl == null) { // Fall back to context classloader cl = SecurityActions.getContextClassLoader(); } cl.loadClass(mixin.getClassName()); String[] interfaces = mixin.getInterfaces(); for (int j = 0; j < interfaces.length; j++) { Class intf = cl.loadClass(interfaces[j]); if (intf.isAssignableFrom(clazz))//This is a fix for JBAOP-365. Class may have been woven, with the extra mixin information only available at init time { Method[] methods = intf.getMethods(); for (int k = 0; k < methods.length; k++) { //Put wrapped method in the class itself into the unadvisedMethods map // String wrappedName = ClassAdvisor.notAdvisedMethodName(clazz.getName(), methods[k].getName()); // Method method = clazz.getMethod(wrappedName, methods[k].getParameterTypes()); Method method = getMethod(clazz, methods[k]); long hash = MethodHashing.methodHash(method); unadvisedMethods.put(hash, method); } } } } } } @Override public synchronized void removeAdviceBinding(AdviceBinding binding) { removeCallerPointcut(binding); // if binding is a caller remove references to it super.removeAdviceBinding(binding); } @Override public synchronized void removeAdviceBindings(ArrayList bindings) { for (int i = 0; i < bindings.size(); i++) { AdviceBinding binding = bindings.get(i); removeCallerPointcut(binding); } adviceBindings.removeAll(bindings); rebuildInterceptors(); doesHaveAspects = adviceBindings.size() > 0; } protected void resolveFieldPointcut(FieldInfo[] newFieldInfos, Interceptor[][] interceptors, AdviceBinding binding, boolean write) { for (int i = 0; i < newFieldInfos.length; i++) { Field field = newFieldInfos[i].getField(); if ((!write && binding.getPointcut().matchesGet(this, field)) || (write && binding.getPointcut().matchesSet(this, field))) { if (AspectManager.verbose) logger.debug("field matched " + ((write) ? "write" : "read") + " binding: " + field); adviceBindings.add(binding); binding.addAdvisor(this); pointcutResolved(newFieldInfos[i], binding, new FieldJoinpoint(field)); if (AspectManager.maintainAdvisorMethodInterceptors && this.initialized) { interceptors[i] = newFieldInfos[i].getInterceptors(); } } } } protected void initializeMethodChain() { long[] keys = advisedMethods.keys(); for (int i = 0; i < keys.length; i++) { MethodInfo info = new MethodInfo(); Method amethod = (Method) advisedMethods.get(keys[i]); info.setAdvisedMethod(amethod); Method umethod = (Method) unadvisedMethods.get(keys[i]); if (umethod == null) umethod = amethod; info.setUnadvisedMethod(umethod); info.setHash(keys[i]); info.setAdvisor(this); methodInfos.put(keys[i], info); try { Field infoField = clazz.getDeclaredField(MethodExecutionTransformer.getMethodInfoFieldName(amethod.getName(), keys[i])); infoField.setAccessible(true); infoField.set(null, new WeakReference(info)); } catch (NoSuchFieldException e) { // ignore, method may not be advised. } catch (IllegalAccessException e) { throw new RuntimeException(e); //To change body of catch statement use Options | File Templates. } } } protected void initializeFieldReadChain() { this.fieldReadInfos = new FieldInfo[advisedFields.length]; for (int i = 0; i < advisedFields.length; i++) { FieldInfo info = new FieldInfo(); info.setAdvisedField(advisedFields[i]); info.setAdvisor(this); info.setIndex(i); try { info.setWrapper(clazz.getDeclaredMethod( FieldAccessTransformer.fieldRead(advisedFields[i].getName()), new Class[] {Object.class})); } catch (NoSuchMethodException e) { //Just means not advised } fieldReadInfos[i] = info; try { Field infoField = clazz.getDeclaredField(FieldAccessTransformer.getFieldReadInfoFieldName(advisedFields[i].getName())); infoField.setAccessible(true); infoField.set(null, new WeakReference(info)); } catch (NoSuchFieldException e) { // ignore, method may not be advised. } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } protected void initializeFieldWriteChain() { this.fieldWriteInfos = new FieldInfo[advisedFields.length]; for (int i = 0; i < advisedFields.length; i++) { FieldInfo info = new FieldInfo(); info.setAdvisedField(advisedFields[i]); info.setAdvisor(this); info.setIndex(i); try { info.setWrapper(clazz.getDeclaredMethod( FieldAccessTransformer.fieldWrite(advisedFields[i].getName()), new Class[] {Object.class, advisedFields[i].getType()})); } catch (NoSuchMethodException e) { //Just means not advised } fieldWriteInfos[i] = info; try { Field infoField = clazz.getDeclaredField(FieldAccessTransformer.getFieldWriteInfoFieldName(advisedFields[i].getName())); infoField.setAccessible(true); infoField.set(null, new WeakReference(info)); } catch (NoSuchFieldException e) { // ignore, method may not be advised. } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } // protected void finalizeChain(JoinPointInfo[] infos) // { // for (int i = 0; i < infos.length; i++) // { // JoinPointInfo info = infos[i]; // ArrayList list = info.getInterceptorChain(); // Interceptor[] interceptors = null; // if (list.size() > 0) // { // interceptors = applyPrecedence(list.toArray(new Interceptor[list.size()])); // } // info.setInterceptors(interceptors); // } // } @SuppressWarnings("deprecation") protected void createInterceptorChains() throws Exception { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("Creating chains for " + clazz + " " + getClassLoader()); } // TODO flavia remove this // this if is here because the subclass GeneratedClassAdvisor shouldn't be calling // this method anymore: the infos are already created during this class initalization (initalise method) // we call this method because we have the method chains if (fieldReadInfos == null) { initializeFieldReadChain(); initializeFieldWriteChain(); initializeMethodChain(); } initializeConstructorChain(); initializeConstructionChain(); resolveBindings(manager); finalizeChains(); populateInterceptorsFromInfos(); doesHaveAspects = adviceBindings.size() > 0; // Notify observer about this change if (this.interceptorChainObserver != null) { this.interceptorChainObserver.interceptorChainsUpdated(fieldReadInfos, fieldWriteInfos, constructorInfos, methodInfos); } } @SuppressWarnings("deprecation") private void resolveBindings(AspectManager manager) { ClassifiedBindingAndPointcutCollection bindingCol = manager.getBindingCollection(); for (AdviceBinding binding: bindingCol.getFieldReadBindings()) { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("iterate binding " + binding.getName() + " " + binding.getPointcut().getExpr()); } resolveFieldPointcut(fieldReadInfos, fieldReadInterceptors, binding, false); } for (AdviceBinding binding: bindingCol.getFieldWriteBindings()) { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("iterate binding " + binding.getName() + " " + binding.getPointcut().getExpr()); } resolveFieldPointcut(fieldWriteInfos, fieldWriteInterceptors, binding, true); } for (AdviceBinding binding: bindingCol.getConstructionBindings()) { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("iterate binding " + binding.getName() + " " + binding.getPointcut().getExpr()); } resolveConstructionPointcut(binding); } for (AdviceBinding binding: bindingCol.getConstructorExecutionBindings()) { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("iterate binding " + binding.getName() + " " + binding.getPointcut().getExpr()); } resolveConstructorPointcut(binding); } for (AdviceBinding binding: bindingCol.getMethodExecutionBindings()) { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("iterate binding " + binding.getName() + " " + binding.getPointcut().getExpr()); } resolveMethodPointcut(binding); } } protected void updateInterceptorChains() throws Exception { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("Updating chains for " + clazz + " " + ((clazz != null) ? getClassLoader() : null )); } lockWriteChains(); try { resetChains(); resolveBindings(manager); finalizeChains(); populateInterceptorsFromInfos(); } finally { unlockWriteChains(); } doesHaveAspects = adviceBindings.size() > 0; // Notify observer about this change if (this.interceptorChainObserver != null) { this.interceptorChainObserver.interceptorChainsUpdated(fieldReadInfos, fieldWriteInfos, constructorInfos, methodInfos); } } private void lockWriteChains() { lockWriteChain(methodInfos); lockWriteChain(fieldReadInfos); lockWriteChain(fieldWriteInfos); lockWriteChain(constructorInfos); lockWriteChain(constructionInfos); } private void unlockWriteChains() { unlockWriteChain(methodInfos); unlockWriteChain(fieldReadInfos); unlockWriteChain(fieldWriteInfos); unlockWriteChain(constructorInfos); unlockWriteChain(constructionInfos); } private void resetChains() { resetChain(methodInfos); resetChain(fieldReadInfos); resetChain(fieldWriteInfos); resetChain(constructorInfos); resetChain(constructionInfos); } private void resetChainsKeepInterceptors() { resetChainKeepInterceptors(methodInfos); resetChainKeepInterceptors(fieldReadInfos); resetChainKeepInterceptors(fieldWriteInfos); resetChainKeepInterceptors(constructorInfos); resetChainKeepInterceptors(constructionInfos); } protected void finalizeChains() { finalizeMethodChain(); finalizeChain(fieldReadInfos); finalizeChain(fieldWriteInfos); finalizeChain(constructorInfos); finalizeChain(constructionInfos); } protected void resolvePointcuts(AdviceBinding binding) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("iterate binding " + binding.getName() + " " + binding.getPointcut().getExpr()); if (BindingClassifier.isExecution(binding)) { resolveMethodPointcut(binding); } if (BindingClassifier.isGet(binding)) { resolveFieldPointcut(fieldReadInfos, fieldReadInterceptors, binding, false); } if (BindingClassifier.isSet(binding)) { resolveFieldPointcut(fieldWriteInfos, fieldWriteInterceptors, binding, true); } if (BindingClassifier.isConstructorExecution(binding)) { resolveConstructorPointcut(binding); } if (BindingClassifier.isConstruction(binding)) { resolveConstructionPointcut(binding); } } @Override protected void rebuildInterceptorsForRemovedBinding(AdviceBinding binding) { if (initialized) { if (System.getSecurityManager() == null) { RebuildInterceptorsAction.NON_PRIVILEGED.rebuildInterceptorsForRemovedBinding(this, binding); } else { RebuildInterceptorsAction.PRIVILEGED.rebuildInterceptorsForRemovedBinding(this, binding); } } } protected void doRebuildInterceptorsForRemovedBinding(AdviceBinding removedBinding) { lockWriteChains(); if (BindingClassifier.isExecution(removedBinding)) { updateMethodPointcutAfterRemove(removedBinding); } if (BindingClassifier.isGet(removedBinding) || BindingClassifier.isSet(removedBinding)) { updateFieldPointcutAfterRemove(fieldReadInfos, removedBinding, false); updateFieldPointcutAfterRemove(fieldWriteInfos, removedBinding, true); } if (BindingClassifier.isConstructorExecution(removedBinding)) { updateConstructorPointcutAfterRemove(removedBinding); } if (BindingClassifier.isConstruction(removedBinding)) { updateConstructionPointcutAfterRemove(removedBinding); } finalizeChains(); unlockWriteChains(); // Notify observer about this change if (this.interceptorChainObserver != null) { this.interceptorChainObserver.interceptorChainsUpdated(fieldReadInfos, fieldWriteInfos, constructorInfos, methodInfos); } //TODO: optimize this try { rebuildCallerInterceptors(); } catch(Exception e) { } } @Override protected void updateFieldPointcutAfterRemove(FieldInfo fieldInfo, int i, boolean write) { if (AspectManager.maintainAdvisorMethodInterceptors) { if (write) { this.fieldWriteInterceptors[i] = fieldInfo.getInterceptors(); } else { this.fieldReadInterceptors[i] = fieldInfo.getInterceptors(); } } } private MethodByConInfo initializeConstructorCallerInterceptorsMap(Class callingClass, int callingIndex, String calledClass, long calledMethodHash, Method calledMethod) throws Exception { HashMap calledClassesMap = methodCalledByConInterceptors[callingIndex]; if (calledClassesMap == null) { calledClassesMap = new HashMap(); methodCalledByConInterceptors[callingIndex] = calledClassesMap; } TLongObjectHashMap calledMethodsMap = calledClassesMap.get(calledClass); if (calledMethodsMap == null) { calledMethodsMap = new TLongObjectHashMap(); calledClassesMap.put(calledClass, calledMethodsMap); } //The standard MethodCalledByXXXXInvocation class calls by reflection and needs access SecurityActions.setAccessible(calledMethod); Class calledClazz = getClassLoader().loadClass(calledClass); MethodByConInfo info = new MethodByConInfo(this, calledClazz, callingClass, callingIndex, calledMethod, calledMethodHash, null); calledMethodsMap.put(calledMethodHash, info); return info; } private ConByConInfo initializeConCalledByConInterceptorsMap(Class callingClass, int callingIndex, String calledClass, long calledConHash, Constructor calledCon) throws Exception { HashMap calledClassesMap = conCalledByConInterceptors[callingIndex]; if (calledClassesMap == null) { calledClassesMap = new HashMap(); conCalledByConInterceptors[callingIndex] = calledClassesMap; } TLongObjectHashMap calledMethodsMap = calledClassesMap.get(calledClass); if (calledMethodsMap == null) { calledMethodsMap = new TLongObjectHashMap(); calledClassesMap.put(calledClass, calledMethodsMap); } ConByConInfo info = createConByConInfo(callingClass, callingIndex, calledClass, calledCon, calledConHash); calledMethodsMap.put(calledConHash, info); return info; } private ConByConInfo createConByConInfo(Class callingClass, int callingIndex, String calledClass, Constructor calledCon, long calledConHash) throws Exception { //The standard ConstructorCalledByXXXXInvocation class calls by reflection and needs access calledCon.setAccessible(true); Class calledClazz = getClassLoader().loadClass(calledClass); try { int index = calledClass.lastIndexOf('.'); String baseClassName = calledClass.substring(index + 1); Method wrapper = calledCon.getDeclaringClass().getDeclaredMethod(ConstructorExecutionTransformer.constructorFactory(baseClassName), calledCon.getParameterTypes()); return new ConByConInfo(this, calledClazz, callingClass, callingIndex, calledCon, calledConHash, wrapper, null); } catch (NoSuchMethodException e) { return new ConByConInfo(this, calledClazz, callingClass, callingIndex, calledCon, calledConHash, null, null); } } protected void rebuildCallerInterceptors() throws Exception { if (methodByMethodData != null) { getMethodByMethodData().rebuildCallerInterceptors(); } for (int i = 0; i < methodCalledByConInterceptors.length; i++) { HashMap calledClasses = methodCalledByConInterceptors[i]; if (calledClasses == null) continue; for (Map.Entry entry : calledClasses.entrySet()) { String cname = entry.getKey(); TLongObjectHashMap calledMethods = entry.getValue(); long[] calledKeys = calledMethods.keys(); for (int j = 0; j < calledKeys.length; j++) { long calledHash = calledKeys[j]; ArrayList bindings = getConstructorCallerBindings(i, cname, calledHash); bindConstructorCallerInterceptorChain(bindings, i, cname, calledHash); } } } if (conByMethodData != null) { getConByMethodData().rebuildCallerInterceptors(); } for (int i = 0; i < conCalledByConInterceptors.length; i++) { HashMap calledClasses = conCalledByConInterceptors[i]; if (calledClasses == null) continue; for (Map.Entry entry : calledClasses.entrySet()) { String cname = entry.getKey(); TLongObjectHashMap calledMethods = entry.getValue(); long[] calledKeys = calledMethods.keys(); for (int j = 0; j < calledKeys.length; j++) { long calledHash = calledKeys[j]; ArrayList bindings = getConCalledByConBindings(i, cname, calledHash); bindConCalledByConInterceptorChain(bindings, i, cname, calledHash); } } } } private ArrayList getConstructorCallerBindings(int callingIndex, String cname, long calledHash) { try { Constructor callingConstructor = constructors[callingIndex]; if (callingConstructor == null) throw new RuntimeException("Unable to figure out calling method of a caller pointcut"); Class called = getClassLoader().loadClass(cname); Method calledMethod = MethodHashing.findMethodByHash(called, calledHash); if (calledMethod == null) throw new RuntimeException("Unable to figure out calledmethod of a caller pointcut"); Collection bindings = manager.getBindingCollection(). getMethodCallBindings(); ArrayList result = new ArrayList(bindings.size()); for(AdviceBinding ab : bindings) { if (ab.getPointcut().matchesCall(this, callingConstructor, called, calledMethod)) { result.add(ab); } } return result; } catch(Exception e) { logger.error("Error happened with methodCallConBinding",e); return new ArrayList(); } } private ArrayList getConCalledByConBindings(int callingIndex, String cname, long calledHash) { try { Constructor callingConstructor = constructors[callingIndex]; if (callingConstructor == null) throw new RuntimeException("Unable to figure out calling method of a caller pointcut"); Class called = getClassLoader().loadClass(cname); Constructor calledCon = MethodHashing.findConstructorByHash(called, calledHash); if (calledCon == null) throw new RuntimeException("Unable to figure out calledcon of a caller pointcut"); Collection bindings = manager.getBindingCollection(). getConstructorCallBindings(); ArrayList result= new ArrayList(bindings.size()); for(AdviceBinding ab : bindings) { if (ab.getPointcut().matchesCall(this, callingConstructor, called, calledCon)) { result.add(ab); } } return result; } catch(Exception e) { logger.error("Error happened for conCalledConBindings", e); return new ArrayList(); } } protected void finalizeMethodCalledByMethodInterceptorChain(MethodByMethodInfo info) { adjustInfoForAddedBinding(info); ArrayList list = info.getInterceptorChain(); Interceptor[] interceptors = null; if (list.size() > 0) { interceptors = list.toArray(new Interceptor[list.size()]); } info.setInterceptors(interceptors); } protected void finalizeConCalledByMethodInterceptorChain(ConByMethodInfo info) { adjustInfoForAddedBinding(info); ArrayList list = info.getInterceptorChain(); Interceptor[] interceptors = null; if (list.size() > 0) { interceptors = list.toArray(new Interceptor[list.size()]); } info.setInterceptors(interceptors); } private void bindConCalledByConInterceptorChain(ArrayList bindings, int callingIndex, String cname, long calledHash) { ConByConInfo info = getConCalledByCon(callingIndex, cname, calledHash); info.clear(); for (AdviceBinding binding : bindings) { if (BindingClassifier.isConstructorCall(binding)) { pointcutResolved(info, binding, new ConstructorCalledByConstructorJoinpoint(info.getCallingConstructor(), info.getConstructor())); } } finalizeConCalledByConInterceptorChain(info); } protected void finalizeConCalledByConInterceptorChain(ConByConInfo info) { adjustInfoForAddedBinding(info); ArrayList list = info.getInterceptorChain(); Interceptor[] interceptors = null; if (list.size() > 0) { interceptors = list.toArray(new Interceptor[list.size()]); } info.setInterceptors(interceptors); } private void bindConstructorCallerInterceptorChain(ArrayList bindings, int callingIndex, String cname, long calledHash) { MethodByConInfo info = getConstructorCallerMethodInfo(callingIndex, cname, calledHash); info.clear(); for (AdviceBinding binding : bindings) { if (BindingClassifier.isCall(binding)) { pointcutResolved(info, binding, new MethodCalledByConstructorJoinpoint(info.getCallingConstructor(), info.getMethod())); } } finalizeMethodCalledByConInterceptorChain(info); } protected void finalizeMethodCalledByConInterceptorChain(MethodByConInfo info) { adjustInfoForAddedBinding(info); ArrayList list = info.getInterceptorChain(); Interceptor[] interceptors = null; if (list.size() > 0) { interceptors = list.toArray(new Interceptor[list.size()]); } info.setInterceptors(interceptors); } @Override protected void rebuildInterceptors() { if (initialized) { if (System.getSecurityManager() == null) { RebuildInterceptorsAction.NON_PRIVILEGED.rebuildInterceptors(this); } else { RebuildInterceptorsAction.PRIVILEGED.rebuildInterceptors(this); } } } protected void doRebuildInterceptors() { try { adviceBindings.clear(); if (!this.initialized) { createInterceptorChains(); } else { updateInterceptorChains(); } rebuildCallerInterceptors(); } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } protected void rebuildInterceptorsForAddedBinding(AdviceBinding binding) { if (initialized) { if (System.getSecurityManager() == null) { RebuildInterceptorsAction.NON_PRIVILEGED.rebuildInterceptorsForAddedBinding(this, binding); } else { RebuildInterceptorsAction.PRIVILEGED.rebuildInterceptorsForAddedBinding(this, binding); } } } protected void doRebuildInterceptorsForAddedBinding(AdviceBinding binding) { try { if (!this.initialized) { throw new IllegalStateException("This should only be called when adding bindings to an exisiting advisor"); } lockWriteChains(); try { resetChainsKeepInterceptors(); resolvePointcuts(binding); finalizeChains(); } finally { unlockWriteChains(); } //TODO: Optimize this rebuildCallerInterceptors(); if (interceptorChainObserver != null) { this.interceptorChainObserver.interceptorChainsUpdated(fieldReadInfos, fieldWriteInfos, constructorInfos, methodInfos); } } catch (Exception ex) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } protected void bindClassMetaData(ClassMetaDataBinding data) { try { ClassMetaDataLoader loader = data.getLoader(); Object[] objs = advisedMethods.getValues(); Method[] methods = new Method[objs.length]; Field[] fields = advisedFields; // set to empty array because advisedFields may not have been initialized yet if (fields == null) fields = new Field[0]; Constructor[] cons = constructors; // set to empty array because constructors may not have been initialized yet if (cons == null) cons = new Constructor[0]; for (int i = 0; i < objs.length; i++) methods[i] = (Method) objs[i]; loader.bind(this, data, methods, fields, cons); } catch (Exception ex) { // REVISIT: Need to know how errors affects deployment ex.printStackTrace(); } } protected void rebindClassMetaData() { defaultMetaData.clear(); methodMetaData.clear(); fieldMetaData.clear(); constructorMetaData.clear(); classMetaData.clear(); for (int i = 0; i < classMetaDataBindings.size(); i++) { ClassMetaDataBinding data = classMetaDataBindings.get(i); bindClassMetaData(data); } deployAnnotationOverrides(); } public synchronized void addClassMetaData(ClassMetaDataBinding data) { initClassMetaDataBindingsList(); classMetaDataBindings.add(data); if (this.clazz == null) return; // don't bind till later. bindClassMetaData(data); // Recalculate interceptorPointcuts because of MetaDataInterceptorPointcuts adviceBindings.clear(); doesHaveAspects = false; rebuildInterceptors(); } public synchronized void removeClassMetaData(ClassMetaDataBinding data) { if (classMetaDataBindings.remove(data)) { if (this.clazz == null) return; // not bound yet rebindClassMetaData(); // Recalculate interceptorPointcuts because of MetaDataInterceptorPointcuts adviceBindings.clear(); doesHaveAspects = false; rebuildInterceptors(); } } private void initializeEmptyConstructorCallerChain(int callingIndex, String calledClass, long calledMethodHash) throws Exception { HashMap callingCon = methodCalledByConBindings[callingIndex]; if (callingCon == null) { callingCon = new HashMap(); methodCalledByConBindings[callingIndex] = callingCon; } TLongObjectHashMap classMap = callingCon.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingCon.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledMethodHash); if (bindings == null) { bindings = new ArrayList(); classMap.put(calledMethodHash, bindings); } } private void initializeConCalledByConEmptyChain(int callingIndex, String calledClass, long calledConHash) throws Exception { HashMap callingCon = conCalledByConBindings[callingIndex]; if (callingCon == null) { callingCon = new HashMap(); conCalledByConBindings[callingIndex] = callingCon; } TLongObjectHashMap classMap = callingCon.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingCon.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledConHash); if (bindings == null) { bindings = new ArrayList(); classMap.put(calledConHash, bindings); } } public void addConstructorCallerPointcut(int callingIndex, String calledClass, long calledMethodHash, AdviceBinding binding) throws Exception { if (AspectManager.verbose) logger.debug("constructor call matched binding " + binding.getPointcut().getExpr()); adviceBindings.add(binding); binding.addAdvisor(this); HashMap callingCon = methodCalledByConBindings[callingIndex]; if (callingCon == null) { callingCon = new HashMap(); methodCalledByConBindings[callingIndex] = callingCon; } TLongObjectHashMap classMap = callingCon.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingCon.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledMethodHash); boolean createdBindings = false; if (bindings == null) { bindings = new ArrayList(); classMap.put(calledMethodHash, bindings); createdBindings = true; } if (!bindings.contains(binding)) bindings.add(binding); // this is so that we can undeploy a caller ArrayList> backrefs = backrefMethodCalledByConstructorBindings.get(binding.getName()); if (backrefs == null) { backrefs = new ArrayList>(); backrefMethodCalledByConstructorBindings.put(binding.getName(), backrefs); backrefs.add(bindings); } else if (createdBindings) backrefs.add(bindings); } private void addConstructorCalledByConPointcut(int callingIndex, String calledClass, long calledConHash, AdviceBinding binding) throws Exception { if (AspectManager.verbose) logger.debug("constructor call matched binding " + binding.getPointcut().getExpr()); adviceBindings.add(binding); binding.addAdvisor(this); HashMap callingCon = conCalledByConBindings[callingIndex]; if (callingCon == null) { callingCon = new HashMap(); conCalledByConBindings[callingIndex] = callingCon; } TLongObjectHashMap classMap = callingCon.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingCon.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledConHash); boolean createdBindings = false; if (bindings == null) { bindings = new ArrayList(); classMap.put(calledConHash, bindings); createdBindings = true; } if (!bindings.contains(binding)) bindings.add(binding); // this is so that we can undeploy a caller ArrayList> backrefs = backrefConCalledByConstructorBindings.get(binding.getName()); if (backrefs == null) { backrefs = new ArrayList>(); backrefConCalledByConstructorBindings.put(binding.getName(), backrefs); backrefs.add(bindings); } else if (createdBindings) backrefs.add(bindings); } private void removeCallerPointcut(AdviceBinding binding) { getMethodByMethodData().removeCallerPointcut(binding); } /** * Generates internal, unadvised version of a method name. */ public static String notAdvisedMethodName(String className, String methodName) { return className.replace('.', '$') + "$" + methodName + NOT_TRANSFORMABLE_SUFFIX; } /** * Is this the name of a private, unadvised thing? */ public static boolean isWithoutAdvisement(String name) { return name.endsWith(NOT_TRANSFORMABLE_SUFFIX); } /** * Is the method advisable? */ public static boolean isAdvisable(Method method) { // note: this should match the implementation in the instrumentor. int modifiers = method.getModifiers(); return ( !isWithoutAdvisement(method.getName()) && !Modifier.isAbstract(modifiers) && !Modifier.isNative(modifiers) && !(method.getName().equals("_getAdvisor") && method.getParameterTypes().length == 0 && method.getReturnType().equals(Advisor.class)) && !(method.getName().equals("_getClassAdvisor") && method.getParameterTypes().length == 0 && method.getReturnType().equals(Advisor.class)) && !(method.getName().equals("_getInstanceAdvisor") && method.getParameterTypes().length == 0 && method.getReturnType().equals(InstanceAdvisor.class)) && !(method.getName().equals("_setInstanceAdvisor") && method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(InstanceAdvisor.class)) && ReflectUtils.isNotAccessMethod(method)); } private void populateFieldTable(ArrayList fields, Class superclass) throws Exception { if (superclass == null) return; if (superclass.equals(Object.class)) return; populateFieldTable(fields, superclass.getSuperclass()); // if (!isAdvised(superclass)) return; ArrayList temp = new ArrayList(); Field[] declaredFields = superclass.getDeclaredFields(); for (int i = 0; i < declaredFields.length; i++) { if (Advisable.isAdvisable(declaredFields[i])) { // Need to do this because notadvisable fields maybe private or protected declaredFields[i].setAccessible(true); temp.add(declaredFields[i]); } } Collections.sort(temp, FieldComparator.INSTANCE); fields.addAll(temp); } /** * Gets advised methods. */ protected void createFieldTable() throws Exception { ArrayList fields = new ArrayList(); populateFieldTable(fields, clazz); advisedFields = fields.toArray(new Field[fields.size()]); } protected void addDeclaredMethods(Class superclass) throws Exception { Method[] declaredMethods = superclass.getDeclaredMethods(); for (int i = 0; i < declaredMethods.length; i++) { if (ClassAdvisor.isAdvisable(declaredMethods[i])) { long hash = MethodHashing.methodHash(declaredMethods[i]); advisedMethods.put(hash, declaredMethods[i]); try { Method m = declaredMethods[i]; Method un = superclass.getDeclaredMethod(ClassAdvisor.notAdvisedMethodName(superclass.getName(), m.getName()), m.getParameterTypes()); un.setAccessible(true); unadvisedMethods.put(hash, un); } catch (NoSuchMethodException ignored) { } } } } /** * Create a HashMap of method hash and Method * Superclasses get added first so subclasses will override with * correct overriden method */ private void populateMethodTables(Class superclass) throws Exception { if (superclass == null) return; if (superclass.equals(Object.class)) return; populateMethodTables(superclass.getSuperclass()); //The advisor for the superclass may be a container Advisor superAdvisor = manager.getAnyAdvisorIfAdvised(superclass); if (superAdvisor != null && superAdvisor instanceof ClassAdvisor) { TLongObjectHashMap superHash = ((ClassAdvisor)superAdvisor).getUnadvisedMethods(); long[] keys = superHash.keys(); for (int i = 0; i < keys.length; i++) { unadvisedMethods.put(keys[i], superHash.get(keys[i])); } } addDeclaredMethods(superclass); } protected void createMethodTables() throws Exception { initAdvisedMethodsMap(); populateMethodTables(clazz.getSuperclass()); addDeclaredMethods(clazz); } protected void createConstructorTables() throws Exception { constructors = clazz.getDeclaredConstructors(); methodCalledByConBindings = new HashMap[constructors.length]; methodCalledByConInterceptors = new HashMap[constructors.length]; conCalledByConBindings = new HashMap[constructors.length]; conCalledByConInterceptors = new HashMap[constructors.length]; for (int i = 0; i < constructors.length; i++) { constructors[i].setAccessible(true); } Arrays.sort(constructors, ConstructorComparator.INSTANCE); } public MethodByMethodInfo resolveCallerMethodInfo(long callingMethodHash, String calledClass, long calledMethodHash) { return getMethodByMethodData().resolveCallerMethodInfo(callingMethodHash, calledClass, calledMethodHash); } public WeakReference resolveCallerMethodInfoAsWeakReference(long callingMethodHash, String calledClass, long calledMethodHash) { //Javassist doesn't like this in a field initialiser hence this method return new WeakReference(resolveCallerMethodInfo(callingMethodHash, calledClass, calledMethodHash)); } public ConByMethodInfo resolveCallerConstructorInfo(long callingMethodHash, String calledClass, long calledConHash) { return getConByMethodData().resolveCallerConstructorInfo(callingMethodHash, calledClass, calledConHash); } public WeakReference resolveCallerConstructorInfoAsWeakReference(long callingMethodHash, String calledClass, long calledConHash) { //Javassist doesn't like this in a field initialiser hence this method return new WeakReference(resolveCallerConstructorInfo(callingMethodHash, calledClass, calledConHash)); } @Deprecated public MethodByConInfo resolveConstructorCallerMethodInfo(int callingIndex, String calledClass, long calledMethodHash) { return resolveConstructorCallerMethodInfo(this.getClazz(), callingIndex, calledClass, calledMethodHash); } public MethodByConInfo resolveConstructorCallerMethodInfo(Class callingClass, int callingIndex, String calledClass, long calledMethodHash) { if (System.getSecurityManager() == null) { return ResolveConstructorCallerMethodInfoAction.NON_PRIVILEGED.resolveInfo(this, callingClass, callingIndex, calledClass, calledMethodHash); } else { return ResolveConstructorCallerMethodInfoAction.PRIVILEGED.resolveInfo(this, callingClass, callingIndex, calledClass, calledMethodHash); } } private MethodByConInfo doResolveConstructorCallerMethodInfo(Class callingClass, int callingIndex, String calledClass, long calledMethodHash) { try { Constructor callingConstructor = constructors[callingIndex]; if (callingConstructor == null) throw new RuntimeException("Unable to figure out calling method of a caller pointcut"); Class called = SecurityActions.getClassLoader(callingClass).loadClass(calledClass); Method calledMethod = MethodHashing.findMethodByHash(called, calledMethodHash); if (calledMethod == null) throw new RuntimeException("Unable to figure out calledmethod of a caller pointcut"); boolean matched = false; ClassifiedBindingAndPointcutCollection bindingCol = manager.getBindingCollection(); for (AdviceBinding binding : bindingCol.getConstructorCallBindings()) { if (binding.getPointcut().matchesCall(this, callingConstructor, called, calledMethod)) { addConstructorCallerPointcut(callingIndex, calledClass, calledMethodHash, binding); matched = true; } } if (!matched) initializeEmptyConstructorCallerChain(callingIndex, calledClass, calledMethodHash); MethodByConInfo info = initializeConstructorCallerInterceptorsMap(callingClass, callingIndex, calledClass, calledMethodHash, calledMethod); ArrayList bindings = getConstructorCallerBindings(callingIndex, calledClass, calledMethodHash); bindConstructorCallerInterceptorChain(bindings, callingIndex, calledClass, calledMethodHash); return info; } catch (Exception x) { throw new RuntimeException(x); } } @Deprecated public WeakReference resolveConstructorCallerMethodInfoAsWeakReference(int callingIndex, String calledClass, long calledMethodHash) { //Javassist doesn't like this in a field initialiser hence this method return new WeakReference(resolveConstructorCallerMethodInfo(callingIndex, calledClass, calledMethodHash)); } public WeakReference resolveConstructorCallerMethodInfoAsWeakReference(Class callingClass, int callingIndex, String calledClass, long calledMethodHash) { //Javassist doesn't like this in a field initialiser hence this method return new WeakReference(resolveConstructorCallerMethodInfo(callingClass, callingIndex, calledClass, calledMethodHash)); } public ConByConInfo resolveConstructorCallerConstructorInfo(int callingIndex, String calledClass, long calledConHash) { return resolveConstructorCallerConstructorInfo(this.getClazz(), callingIndex, calledClass, calledConHash); } public ConByConInfo resolveConstructorCallerConstructorInfo(Class callingClass, int callingIndex, String calledClass, long calledConHash) { if (System.getSecurityManager() == null) { return ResolveConstructorCallerConstructorInfoAction.NON_PRIVILEGED.resolveInfo(this, callingClass, callingIndex, calledClass, calledConHash); } else { return ResolveConstructorCallerConstructorInfoAction.PRIVILEGED.resolveInfo(this, callingClass, callingIndex, calledClass, calledConHash); } } private ConByConInfo doResolveConstructorCallerConstructorInfo(Class callingClass, int callingIndex, String calledClass, long calledConHash) { try { Constructor callingConstructor = constructors[callingIndex]; if (callingConstructor == null) throw new RuntimeException("Unable to figure out calling method of a caller pointcut"); Class called = SecurityActions.getClassLoader(callingClass).loadClass(calledClass); Constructor calledCon = MethodHashing.findConstructorByHash(called, calledConHash); if (calledCon == null) throw new RuntimeException("Unable to figure out calledcon of a caller pointcut"); boolean matched = false; ClassifiedBindingAndPointcutCollection bindingCol = manager.getBindingCollection(); for (AdviceBinding binding : bindingCol.getConstructorCallBindings()) { if (binding.getPointcut().matchesCall(this, callingConstructor, called, calledCon)) { addConstructorCalledByConPointcut(callingIndex, calledClass, calledConHash, binding); matched = true; } } if (!matched) initializeConCalledByConEmptyChain(callingIndex, calledClass, calledConHash); ConByConInfo info = initializeConCalledByConInterceptorsMap(callingClass, callingIndex, calledClass, calledConHash, calledCon); ArrayList bindings = getConCalledByConBindings(callingIndex, calledClass, calledConHash); bindConCalledByConInterceptorChain(bindings, callingIndex, calledClass, calledConHash); return info; } catch (Exception x) { throw new RuntimeException(x); } } @Deprecated public WeakReference resolveConstructorCallerConstructorInfoAsWeakReference(int callingIndex, String calledClass, long calledConHash) { //Javassist doesn't like this in a field initialiser hence this method return new WeakReference(resolveConstructorCallerConstructorInfo(callingIndex, calledClass, calledConHash)); } public WeakReference resolveConstructorCallerConstructorInfoAsWeakReference(Class callingClass, int callingIndex, String calledClass, long calledConHash) { //Javassist doesn't like this in a field initialiser hence this method return new WeakReference(resolveConstructorCallerConstructorInfo(callingClass, callingIndex, calledClass, calledConHash)); } ///////////////////////// // Invoking /** * Invokes target object without applying interceptors. */ public Object invokeWithoutAdvisement(Object target, long methodHash, Object[] arguments) throws Throwable { try { Method method = (Method) unadvisedMethods.get(methodHash); return method.invoke(target, arguments); } catch (InvocationTargetException e) { throw e.getTargetException(); } } public Object invokeNewWithoutAdvisement(Object[] arguments, Constructor constructor) throws Throwable { try { return constructor.newInstance(arguments); } catch (InstantiationException in) { throw new RuntimeException("failed to call constructor", in); } catch (IllegalAccessException ill) { throw new RuntimeException("illegal access", ill); } catch (InvocationTargetException ite) { throw ite.getCause(); } } public Object invokeMethod(long methodHash, Object[] arguments) throws Throwable { return invokeMethod(null, methodHash, arguments); } public Object invokeMethod(Object target, long methodHash, Object[] arguments) throws Throwable { InstanceAdvisor advisor = null; if (target != null) { InstanceAdvised advised = (InstanceAdvised) target; advisor = advised._getInstanceAdvisor(); } MethodInfo info = methodInfos.getMethodInfo(methodHash); return invokeMethod(advisor, target, methodHash, arguments, info); } public Object invokeMethod(InstanceAdvisor instanceAdvisor, Object target, long methodHash, Object[] arguments) throws Throwable { MethodInfo info = methodInfos.getMethodInfo(methodHash); if (info == null && logger.isDebugEnabled()) { logger.debug("info is null for hash: " + methodHash + " of " + clazz.getName()); } return invokeMethod(instanceAdvisor, target, methodHash, arguments, info); } public Object invokeMethod(InstanceAdvisor instanceAdvisor, Object target, long methodHash, Object[] arguments, MethodInfo info) throws Throwable { Interceptor[] aspects = info.getInterceptors(); if (instanceAdvisor != null && (instanceAdvisor.hasInterceptors())) { aspects = instanceAdvisor.getInterceptors(aspects); } MethodInvocation invocation = new MethodInvocation(info, aspects); invocation.setArguments(arguments); invocation.setTargetObject(target); return invocation.invokeNext(); } /** *@deprecated */ public Object invokeCaller(long callingMethodHash, Object target, Object[] args, CallerMethodInfo info, Object callingObject) throws Throwable { return invokeCaller((MethodByMethodInfo)info, callingObject, target, args); } public Object invokeCaller(MethodByMethodInfo info, Object callingObject, Object target, Object[] args) throws Throwable { MethodCalledByMethodInvocation invocation = new MethodCalledByMethodInvocation(info, callingObject, target, args, info.getInterceptors()); invocation.setTargetObject(target); return invocation.invokeNext(); } /** *@deprecated */ public Object invokeConCalledByMethod(long callingMethodHash, Object[] args, CallerConstructorInfo info, Object callingObject) throws Throwable { return invokeConCalledByMethod((ConByMethodInfo)info, callingObject, args); } public Object invokeConCalledByMethod(ConByMethodInfo info, Object callingObject, Object[] args) throws Throwable { ConstructorCalledByMethodInvocation invocation = new ConstructorCalledByMethodInvocation(info, callingObject, args, info.getInterceptors()); return invocation.invokeNext(); } /** *@deprecated */ public Object invokeConstructorCaller(int callingIndex, Object target, Object[] args, CallerMethodInfo info) throws Throwable { return invokeConstructorCaller((MethodByConInfo)info, null, target, args); } /** *@deprecated */ public Object invokeConstructorCaller(int callingIndex, Object callingObject, Object target, Object[] args, CallerMethodInfo info) throws Throwable { return invokeConstructorCaller((MethodByConInfo)info, callingObject, target, args); } /** * @deprecated * * Prefer using the version with callingObject instead of this one, * since this object is available for call invocations made inside constructors. * * @see #invokeConstructorCaller(MethodByConInfo, Object, Object, Object[]) */ public Object invokeConstructorCaller(MethodByConInfo info, Object target, Object[] args) throws Throwable { return this.invokeConstructorCaller(info, null, target, args); } public Object invokeConstructorCaller(MethodByConInfo info, Object callingObject, Object target, Object[] args) throws Throwable { MethodCalledByConstructorInvocation invocation = new MethodCalledByConstructorInvocation(info, callingObject, target, args, info.getInterceptors()); invocation.setTargetObject(target); return invocation.invokeNext(); } /** *@deprecated */ public Object invokeConCalledByCon(int callingIndex, Object[] args, CallerConstructorInfo info) throws Throwable { return invokeConCalledByCon((ConByConInfo)info, null, args); } /** *@deprecated */ public Object invokeConCalledByCon(int callingIndex, Object callingObject, Object[] args, CallerConstructorInfo info) throws Throwable { return invokeConCalledByCon((ConByConInfo)info, callingObject, args); } /** * @deprecated * * Prefer using the version with callingObject instead of this one, * since this object is available for call invocations made inside constructors. * * @see #invokeConCalledByCon(ConByConInfo, Object, Object[]) */ public Object invokeConCalledByCon(ConByConInfo info, Object[] args) throws Throwable { return invokeConCalledByCon(info, null, args); } public Object invokeConCalledByCon(ConByConInfo info, Object callingObject, Object[] args) throws Throwable { ConstructorCalledByConstructorInvocation invocation = new ConstructorCalledByConstructorInvocation(info, callingObject, args, info.getInterceptors()); return invocation.invokeNext(); } private MethodByConInfo getConstructorCallerMethodInfo(int callingIndex, String calledClass, long calledMethodHash) { HashMap calledClasses = methodCalledByConInterceptors[callingIndex]; TLongObjectHashMap calledMethods = calledClasses.get(calledClass); MethodByConInfo info = (MethodByConInfo) calledMethods.get(calledMethodHash); return info; } private ConByConInfo getConCalledByCon(int callingIndex, String calledClass, long calledConHash) { HashMap calledClasses = conCalledByConInterceptors[callingIndex]; TLongObjectHashMap calledMethods = calledClasses.get(calledClass); ConByConInfo info = (ConByConInfo) calledMethods.get(calledConHash); return info; } public Object invokeNew(Object[] args, int idx) throws Throwable { Interceptor[] cInterceptors = constructorInfos[idx].getInterceptors(); if (cInterceptors == null) cInterceptors = new Interceptor[0]; ConstructorInvocation invocation = new ConstructorInvocation(cInterceptors); invocation.setAdvisor(this); invocation.setArguments(args); invocation.setConstructor(constructors[idx]); return invocation.invokeNext(); } /** * Invokes interceptor chain. * This is the beginning */ public Object invokeRead(Object target, int index) throws Throwable { Interceptor[] aspects = fieldReadInfos[index].getInterceptors(); if (aspects == null) aspects = new Interceptor[0]; FieldReadInvocation invocation; if (target != null) { InstanceAdvised advised = (InstanceAdvised) target; InstanceAdvisor advisor = advised._getInstanceAdvisor(); if (advisor != null && advisor.hasInterceptors()) { aspects = advisor.getInterceptors(aspects); } } invocation = new FieldReadInvocation(advisedFields[index], index, aspects); invocation.setAdvisor(this); invocation.setTargetObject(target); return invocation.invokeNext(); } /** * Invokes interceptor chain. * This is the beginning */ public Object invokeWrite(Object target, int index, Object value) throws Throwable { Interceptor[] aspects = fieldWriteInfos[index].getInterceptors(); if (aspects == null) aspects = new Interceptor[0]; FieldWriteInvocation invocation; if (target != null) { InstanceAdvised advised = (InstanceAdvised) target; InstanceAdvisor advisor = advised._getInstanceAdvisor(); if (advisor != null && advisor.hasInterceptors()) { aspects = advised._getInstanceAdvisor().getInterceptors(aspects); } } invocation = new FieldWriteInvocation(advisedFields[index], index, value, aspects); invocation.setAdvisor(this); invocation.setTargetObject(target); return invocation.invokeNext(); } /** * Invokes interceptor chain. * This is the beginning */ public Object invoke(Invocation invocation) throws Throwable { if (invocation instanceof FieldWriteInvocation) { FieldWriteInvocation fieldInvocation = (FieldWriteInvocation) invocation; Object target = fieldInvocation.getTargetObject(); Object val = fieldInvocation.getValue(); Field field = fieldInvocation.getField(); field.set(target, val); return null; } else if (invocation instanceof FieldReadInvocation) { FieldReadInvocation fieldInvocation = (FieldReadInvocation) invocation; Object target = fieldInvocation.getTargetObject(); Field field = fieldInvocation.getField(); return field.get(target); } else if (invocation instanceof MethodInvocation) { MethodInvocation methodInvocation = (MethodInvocation) invocation; return invokeWithoutAdvisement(methodInvocation.getTargetObject(), methodInvocation.getMethodHash(), methodInvocation.getArguments()); } else if (invocation instanceof ConstructorInvocation) { ConstructorInvocation cInvocation = (ConstructorInvocation) invocation; Object[] arguments = cInvocation.getArguments(); Constructor constructor = cInvocation.getConstructor(); return invokeNewWithoutAdvisement(arguments, constructor); } throw new IllegalStateException("Unknown Invocation type: " + invocation.getClass().getName()); } @Override public void cleanup() { super.cleanup(); if (methodByMethodData != null) { methodByMethodData.cleanup(); methodByMethodData = null; } if (conByMethodData != null) { conByMethodData.cleanup(); conByMethodData = null; } } // interceptor chain observer private InterceptorChainObserver interceptorChainObserver; /** * Returns the interceptor chain observer associated with this advisor. */ protected InterceptorChainObserver getInterceptorChainObserver() { return this.interceptorChainObserver; } /** * Defines the interceptor chain observer associated with this advisor. * @param observer the interceptor chain observer. */ protected void setInterceptorChainObserver(InterceptorChainObserver observer) { if (observer != null) { observer.initialInterceptorChains(this.clazz, fieldReadInfos, fieldWriteInfos, constructorInfos, methodInfos); } this.interceptorChainObserver = observer; } /** @deprecated We should just be using xxxxInfos */ @Override protected void populateInterceptorsFromInfos() { if (!AspectManager.maintainAdvisorMethodInterceptors) { return; } super.populateInterceptorsFromInfos(); fieldReadInterceptors = new Interceptor[fieldReadInfos.length][]; for (int i = 0 ; i < fieldReadInfos.length ; i++) { fieldReadInterceptors[i] = fieldReadInfos[i].getInterceptors(); } fieldWriteInterceptors = new Interceptor[fieldWriteInfos.length][]; for (int i = 0 ; i < fieldWriteInfos.length ; i++) { fieldWriteInterceptors[i] = fieldWriteInfos[i].getInterceptors(); } if (constructionInfos == null) { constructionInterceptors = new Interceptor[0][]; } else { constructionInterceptors = new Interceptor[constructionInfos.length][]; for (int i = 0 ; i < constructionInfos.length ; i++) { constructionInterceptors[i] = constructionInfos[i].getInterceptors(); } } } protected MethodByMethodData getMethodByMethodData() { if (methodByMethodData == null) { synchronized(lazyCollectionLock) { if (methodByMethodData == null) { methodByMethodData = new MethodByMethodData(); } } } return methodByMethodData; } protected ConByMethodData getConByMethodData() { if (conByMethodData == null) { synchronized(lazyCollectionLock) { if (conByMethodData == null) { conByMethodData = new ConByMethodData(); } } } return conByMethodData; } interface ResolveCallerConstuctorInfoAction { ConByMethodInfo resolveInfo(ConByMethodData data, long callingMethodHash, String calledClass, long calledConHash); ResolveCallerConstuctorInfoAction PRIVILEGED = new ResolveCallerConstuctorInfoAction() { public ConByMethodInfo resolveInfo(final ConByMethodData data, final long callingMethodHash, final String calledClass, final long calledConHash) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public ConByMethodInfo run() throws Exception { return data.doResolveCallerConstructorInfo(callingMethodHash, calledClass, calledConHash); } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException)ex; } throw new RuntimeException(ex); } } }; ResolveCallerConstuctorInfoAction NON_PRIVILEGED = new ResolveCallerConstuctorInfoAction() { public ConByMethodInfo resolveInfo(ConByMethodData data, long callingMethodHash, String calledClass, long calledConHash) { return data.doResolveCallerConstructorInfo(callingMethodHash, calledClass, calledConHash); } }; } interface ResolveCallerMethodInfoAction { MethodByMethodInfo resolveInfo(MethodByMethodData data, long callingMethodHash, String calledClass, long calledMethodHash); ResolveCallerMethodInfoAction PRIVILEGED = new ResolveCallerMethodInfoAction() { public MethodByMethodInfo resolveInfo(final MethodByMethodData data, final long callingMethodHash, final String calledClass, final long calledMethodHash) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public MethodByMethodInfo run() throws Exception { return data.doResolveCallerMethodInfo(callingMethodHash, calledClass, calledMethodHash); } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException)ex; } throw new RuntimeException(ex); } } }; ResolveCallerMethodInfoAction NON_PRIVILEGED = new ResolveCallerMethodInfoAction() { public MethodByMethodInfo resolveInfo(MethodByMethodData data, long callingMethodHash, String calledClass, long calledMethodHash) { return data.doResolveCallerMethodInfo(callingMethodHash, calledClass, calledMethodHash); } }; } interface ResolveConstructorCallerMethodInfoAction { MethodByConInfo resolveInfo(ClassAdvisor advisor, Class callingClass, int callingIndex, String calledClass, long calledMethodHash); ResolveConstructorCallerMethodInfoAction PRIVILEGED = new ResolveConstructorCallerMethodInfoAction() { public MethodByConInfo resolveInfo(final ClassAdvisor advisor, final Class callingClass, final int callingIndex, final String calledClass, final long calledMethodHash) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public MethodByConInfo run() throws Exception { return advisor.doResolveConstructorCallerMethodInfo(callingClass, callingIndex, calledClass, calledMethodHash); } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException)ex; } throw new RuntimeException(ex); } } }; ResolveConstructorCallerMethodInfoAction NON_PRIVILEGED = new ResolveConstructorCallerMethodInfoAction() { public MethodByConInfo resolveInfo(ClassAdvisor advisor, Class callingClass, int callingIndex, String calledClass, long calledMethodHash) { return advisor.doResolveConstructorCallerMethodInfo(callingClass, callingIndex, calledClass, calledMethodHash); } }; } interface ResolveConstructorCallerConstructorInfoAction { ConByConInfo resolveInfo(ClassAdvisor advisor, Class callingClass, int callingIndex, String calledClass, long calledConHash); ResolveConstructorCallerConstructorInfoAction PRIVILEGED = new ResolveConstructorCallerConstructorInfoAction() { public ConByConInfo resolveInfo(final ClassAdvisor advisor, final Class callingClass, final int callingIndex, final String calledClass, final long calledConHash) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public ConByConInfo run() throws Exception { return advisor.doResolveConstructorCallerConstructorInfo(callingClass, callingIndex, calledClass, calledConHash); } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException)ex; } throw new RuntimeException(ex); } } }; ResolveConstructorCallerConstructorInfoAction NON_PRIVILEGED = new ResolveConstructorCallerConstructorInfoAction() { public ConByConInfo resolveInfo(ClassAdvisor advisor, Class callingClass, int callingIndex, String calledClass, long calledConHash) { return advisor.doResolveConstructorCallerConstructorInfo(callingClass, callingIndex, calledClass, calledConHash); } }; } interface RebuildInterceptorsAction { void rebuildInterceptors(ClassAdvisor advisor); void rebuildInterceptorsForAddedBinding(ClassAdvisor advisor, AdviceBinding binding); void rebuildInterceptorsForRemovedBinding(ClassAdvisor advisor, AdviceBinding binding); RebuildInterceptorsAction PRIVILEGED = new RebuildInterceptorsAction() { public void rebuildInterceptors(final ClassAdvisor advisor) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() { advisor.doRebuildInterceptors(); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } public void rebuildInterceptorsForAddedBinding(final ClassAdvisor advisor, final AdviceBinding binding) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() { advisor.doRebuildInterceptorsForAddedBinding(binding); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } public void rebuildInterceptorsForRemovedBinding(final ClassAdvisor advisor, final AdviceBinding binding) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() { advisor.doRebuildInterceptorsForRemovedBinding(binding); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } }; RebuildInterceptorsAction NON_PRIVILEGED = new RebuildInterceptorsAction() { public void rebuildInterceptors(ClassAdvisor advisor) { advisor.doRebuildInterceptors(); } public void rebuildInterceptorsForAddedBinding(ClassAdvisor advisor, AdviceBinding binding) { advisor.doRebuildInterceptorsForAddedBinding(binding); } public void rebuildInterceptorsForRemovedBinding(ClassAdvisor advisor, AdviceBinding binding) { advisor.doRebuildInterceptorsForRemovedBinding(binding); } }; } private class MethodByMethodData { private volatile TLongObjectHashMap methodCalledByMethodBindings = UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP; private volatile HashMap>> backrefMethodCalledByMethodBindings = UnmodifiableEmptyCollections.EMPTY_HASHMAP; private volatile TLongObjectHashMap methodCalledByMethodInterceptors = UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP; public TLongObjectHashMap getMethodCalledByMethodInterceptors() { //No need to initialise map here if it is empty return methodCalledByMethodInterceptors; } public TLongObjectHashMap getMethodCalledByMethodBindings() { //No need to initialise map here if it is empty return methodCalledByMethodBindings; } public void rebuildCallerInterceptors() throws Exception { //No need to initialise map here if it is empty long[] callingKeys = methodCalledByMethodInterceptors.keys(); for (int i = 0; i < callingKeys.length; i++) { long callingHash = callingKeys[i]; HashMap calledClasses = (HashMap) methodCalledByMethodInterceptors.get(callingHash); for (Map.Entry entry : calledClasses.entrySet()) { String cname = entry.getKey(); TLongObjectHashMap calledMethods = entry.getValue(); long[] calledKeys = calledMethods.keys(); for (int j = 0; j < calledKeys.length; j++) { long calledHash = calledKeys[j]; ArrayList bindings = getCallerBindings(callingHash, cname, calledHash); Method calling = MethodHashing.findMethodByHash(clazz, callingHash); bindCallerInterceptorChain(bindings, callingHash, cname, calledHash, calling); } } } } public void removeCallerPointcut(AdviceBinding binding) { //No need to initialise map here if it is empty ArrayList> backrefs = backrefMethodCalledByMethodBindings.get(binding.getName()); if (backrefs == null) return; for (int i = 0; i < backrefs.size(); i++) { ArrayList ref = backrefs.get(i); ref.remove(binding); } } public MethodByMethodInfo resolveCallerMethodInfo(long callingMethodHash, String calledClass, long calledMethodHash) { //The main entry point for adding data to the maps, let us initialise them here. if (methodCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP || backrefMethodCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_HASHMAP || methodCalledByMethodInterceptors == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP) { synchronized(lazyCollectionLock) { if (methodCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP) { methodCalledByMethodBindings = new TLongObjectHashMap(); } if (backrefMethodCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { backrefMethodCalledByMethodBindings = new HashMap>>(); } if (methodCalledByMethodInterceptors == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP) { methodCalledByMethodInterceptors = new TLongObjectHashMap(); } } } if (System.getSecurityManager() == null) { return ResolveCallerMethodInfoAction.NON_PRIVILEGED.resolveInfo(this, callingMethodHash, calledClass, calledMethodHash); } else { return ResolveCallerMethodInfoAction.PRIVILEGED.resolveInfo(this, callingMethodHash, calledClass, calledMethodHash); } } private MethodByMethodInfo doResolveCallerMethodInfo(long callingMethodHash, String calledClass, long calledMethodHash) { //Called via resolveCallerMethodInfo, maps are initialised try { Method callingMethod = MethodHashing.findMethodByHash(clazz, callingMethodHash); if (callingMethod == null) throw new RuntimeException("Unable to figure out calling method of a caller pointcut"); Class called = getClassLoader().loadClass(calledClass); Method calledMethod = MethodHashing.findMethodByHash(called, calledMethodHash); if (calledMethod == null) throw new RuntimeException("Unable to figure out calledmethod of a caller pointcut"); boolean matched = false; for (AdviceBinding binding : manager.getBindingCollection().getMethodCallBindings()) { if (binding.getPointcut().matchesCall(ClassAdvisor.this, callingMethod, called, calledMethod)) { addMethodCalledByMethodPointcut(callingMethodHash, calledClass, calledMethodHash, binding); matched = true; } } if (!matched) initializeEmptyCallerChain(callingMethodHash, calledClass, calledMethodHash); MethodByMethodInfo info = initializeCallerInterceptorsMap(callingMethodHash, calledClass, calledMethodHash, callingMethod, calledMethod); ArrayList bindings = getCallerBindings(callingMethodHash, calledClass, calledMethodHash); bindCallerInterceptorChain(bindings, callingMethodHash, calledClass, calledMethodHash, callingMethod); return info; } catch (Exception x) { throw new RuntimeException(x); } } private void addMethodCalledByMethodPointcut(long callingMethodHash, String calledClass, long calledMethodHash, AdviceBinding binding) throws Exception { //Called via resolveCallerMethodInfo, maps are initialised if (AspectManager.verbose) logger.debug("method call matched binding " + binding.getPointcut().getExpr()); adviceBindings.add(binding); binding.addAdvisor(ClassAdvisor.this); HashMap callingMethod = (HashMap)methodCalledByMethodBindings.get(callingMethodHash); if (callingMethod == null) { callingMethod = new HashMap(); methodCalledByMethodBindings.put(callingMethodHash, callingMethod); } TLongObjectHashMap classMap = callingMethod.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingMethod.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledMethodHash); boolean createdBindings = false; if (bindings == null) { bindings = new ArrayList(); classMap.put(calledMethodHash, bindings); createdBindings = true; } if (!bindings.contains(binding)) bindings.add(binding); // this is so that we can undeploy a caller ArrayList> backrefs = backrefMethodCalledByMethodBindings.get(binding.getName()); if (backrefs == null) { backrefs = new ArrayList>(); backrefMethodCalledByMethodBindings.put(binding.getName(), backrefs); backrefs.add(bindings); } else if (createdBindings) backrefs.add(bindings); } private void initializeEmptyCallerChain(long callingMethodHash, String calledClass, long calledMethodHash) throws Exception { //Called via resolveCallerMethodInfo, maps are initialised HashMap callingMethod = (HashMap) methodCalledByMethodBindings.get(callingMethodHash); if (callingMethod == null) { callingMethod = new HashMap(); methodCalledByMethodBindings.put(callingMethodHash, callingMethod); } TLongObjectHashMap classMap = callingMethod.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingMethod.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledMethodHash); if (bindings == null) { bindings = new ArrayList(); classMap.put(calledMethodHash, bindings); } } private MethodByMethodInfo initializeCallerInterceptorsMap(long callingMethodHash, String calledClass, long calledMethodHash, Method callingMethod, Method calledMethod) throws Exception { //Called via resolveCallerMethodInfo, maps are initialised HashMap calledClassesMap = (HashMap) methodCalledByMethodInterceptors.get(callingMethodHash); if (calledClassesMap == null) { calledClassesMap = new HashMap(); methodCalledByMethodInterceptors.put(callingMethodHash, calledClassesMap); } TLongObjectHashMap calledMethodsMap = calledClassesMap.get(calledClass); if (calledMethodsMap == null) { calledMethodsMap = new TLongObjectHashMap(); calledClassesMap.put(calledClass, calledMethodsMap); } //The standard MethodCalledByXXXXInvocation class calls by reflection and needs access calledMethod.setAccessible(true); Class calledClazz = getClassLoader().loadClass(calledClass); MethodByMethodInfo info = new MethodByMethodInfo(ClassAdvisor.this, calledClazz, calledMethod, callingMethod, callingMethodHash, calledMethodHash, null); calledMethodsMap.put(calledMethodHash, info); return info; } private ArrayList getCallerBindings(long callingHash, String cname, long calledHash) { try { Method callingMethod = MethodHashing.findMethodByHash(clazz, callingHash); if (callingMethod == null) throw new RuntimeException("Unable to figure out calling method of a caller pointcut"); Class called = getClassLoader().loadClass(cname); Method calledMethod = MethodHashing.findMethodByHash(called, calledHash); if (calledMethod == null) throw new RuntimeException("Unable to figure out calledmethod of a caller pointcut"); Collection bindings = manager.getBindingCollection(). getMethodCallBindings(); ArrayList result = new ArrayList(bindings.size()); for(AdviceBinding ab : bindings) { if (ab.getPointcut().matchesCall(ClassAdvisor.this, callingMethod, called, calledMethod)) { result.add(ab); } } return result; } catch(Exception e) { logger.error("Error happened when getting callerBindings",e); return new ArrayList(); } } private void bindCallerInterceptorChain(ArrayList bindings, long callingHash, String cname, long calledHash, Method calling) { //Called via resolveCallerMethodInfo, maps are initialised MethodByMethodInfo info = getCallerMethodInfo(callingHash, cname, calledHash); info.clear(); for (AdviceBinding binding : bindings) { if (BindingClassifier.isCall(binding)) { pointcutResolved(info, binding, new MethodCalledByMethodJoinpoint(info.getCallingMethod(), info.getMethod())); } } finalizeMethodCalledByMethodInterceptorChain(info); } private MethodByMethodInfo getCallerMethodInfo(long callingMethodHash, String calledClass, long calledMethodHash) { //Called via resolveCallerMethodInfo, maps are initialised HashMap calledClasses = (HashMap) methodCalledByMethodInterceptors.get(callingMethodHash); TLongObjectHashMap calledMethods = calledClasses.get(calledClass); MethodByMethodInfo info = (MethodByMethodInfo) calledMethods.get(calledMethodHash); return info; } public void cleanup() { methodCalledByMethodBindings.clear(); backrefMethodCalledByMethodBindings.clear(); methodCalledByMethodInterceptors.clear(); } } private class ConByMethodData { // constructor caller pointcut support for methods calling constructors only private volatile TLongObjectHashMap conCalledByMethodBindings = UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP; private volatile HashMap>> backrefConCalledByMethodBindings = UnmodifiableEmptyCollections.EMPTY_HASHMAP; private volatile TLongObjectHashMap conCalledByMethodInterceptors = UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP; public TLongObjectHashMap getConCalledByMethodInterceptors() { return conCalledByMethodInterceptors; } public ArrayList getConCalledByMethodBindings(long callingHash, String cname, long calledHash) { try { Method callingMethod = MethodHashing.findMethodByHash(clazz, callingHash); if (callingMethod == null) throw new RuntimeException("Unable to figure out calling method of a constructor caller pointcut"); Class called = getClassLoader().loadClass(cname); Constructor calledCon = MethodHashing.findConstructorByHash(called, calledHash); if (calledCon == null) throw new RuntimeException("Unable to figure out calledcon of a constructor caller pointcut"); Collection bindings = manager.getBindingCollection(). getConstructorCallBindings(); ArrayList result = new ArrayList(bindings.size()); for(AdviceBinding ab : bindings) { if (ab.getPointcut().matchesCall(ClassAdvisor.this, callingMethod, called, calledCon)) { result.add(ab); } } return result; } catch(Exception e) { logger.error("Error happened conCalledMethod bindings", e); return new ArrayList(); } } public void rebuildCallerInterceptors() throws Exception { long[] callingKeys = conCalledByMethodInterceptors.keys(); for (int i = 0; i < callingKeys.length; i++) { long callingHash = callingKeys[i]; HashMap calledClasses = (HashMap) conCalledByMethodInterceptors.get(callingHash); for (Map.Entry entry : calledClasses.entrySet()) { String cname = entry.getKey(); TLongObjectHashMap calledMethods = entry.getValue(); long[] calledKeys = calledMethods.keys(); for (int j = 0; j < calledKeys.length; j++) { long calledHash = calledKeys[j]; ArrayList bindings = getConCalledByMethodBindings(callingHash, cname, calledHash); bindConCalledByMethodInterceptorChain(bindings, callingHash, cname, calledHash); } } } } public ConByMethodInfo resolveCallerConstructorInfo(long callingMethodHash, String calledClass, long calledConHash) { //The main entry point for adding data to the maps, let us initialise them here. if (conCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP || backrefConCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_HASHMAP || conCalledByMethodInterceptors == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP) { synchronized(lazyCollectionLock) { if (conCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP) { conCalledByMethodBindings = new TLongObjectHashMap(); } if (backrefConCalledByMethodBindings == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { backrefConCalledByMethodBindings = new HashMap>>(); } if (conCalledByMethodInterceptors == UnmodifiableEmptyCollections.EMPTY_TLONG_OBJECT_HASHMAP) { conCalledByMethodInterceptors = new TLongObjectHashMap(); } } } if (System.getSecurityManager() == null) { return ResolveCallerConstuctorInfoAction.NON_PRIVILEGED.resolveInfo(this, callingMethodHash, calledClass, calledConHash); } else { return ResolveCallerConstuctorInfoAction.PRIVILEGED.resolveInfo(this, callingMethodHash, calledClass, calledConHash); } } private ConByMethodInfo doResolveCallerConstructorInfo(long callingMethodHash, String calledClass, long calledConHash) { try { Method callingMethod = MethodHashing.findMethodByHash(clazz, callingMethodHash); if (callingMethod == null) throw new RuntimeException("Unable to figure out calling method of a constructor caller pointcut"); Class called = getClassLoader().loadClass(calledClass); Constructor calledCon = MethodHashing.findConstructorByHash(called, calledConHash); if (calledCon == null) throw new RuntimeException("Unable to figure out calledcon of a constructor caller pointcut"); boolean matched = false; ClassifiedBindingAndPointcutCollection bindingCol = manager.getBindingCollection(); for (AdviceBinding binding : bindingCol.getConstructorCallBindings()) { if (binding.getPointcut().matchesCall(ClassAdvisor.this, callingMethod, called, calledCon)) { addConstructorCalledByMethodPointcut(callingMethodHash, calledClass, calledConHash, binding); matched = true; } } if (!matched) initializeConCalledByMethodEmptyChain(callingMethodHash, calledClass, calledConHash); ConByMethodInfo info = initializeConCalledByMethodInterceptorsMap(callingMethod, callingMethodHash, calledClass, calledConHash, calledCon); ArrayList bindings = getConCalledByMethodBindings(callingMethodHash, calledClass, calledConHash); bindConCalledByMethodInterceptorChain(bindings, callingMethodHash, calledClass, calledConHash); return info; } catch (Exception x) { throw new RuntimeException(x); } } private void addConstructorCalledByMethodPointcut(long callingMethodHash, String calledClass, long calledMethodHash, AdviceBinding binding) throws Exception { if (AspectManager.verbose) logger.debug("method call matched binding " + binding.getPointcut().getExpr()); adviceBindings.add(binding); binding.addAdvisor(ClassAdvisor.this); HashMap callingMethod = (HashMap) conCalledByMethodBindings.get(callingMethodHash); if (callingMethod == null) { callingMethod = new HashMap(); conCalledByMethodBindings.put(callingMethodHash, callingMethod); } TLongObjectHashMap classMap = callingMethod.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingMethod.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledMethodHash); boolean createdBindings = false; if (bindings == null) { bindings = new ArrayList(); classMap.put(calledMethodHash, bindings); createdBindings = true; } if (!bindings.contains(binding)) bindings.add(binding); // this is so that we can undeploy a caller ArrayList> backrefs = backrefConCalledByMethodBindings.get(binding.getName()); if (backrefs == null) { backrefs = new ArrayList>(); backrefConCalledByMethodBindings.put(binding.getName(), backrefs); backrefs.add(bindings); } else if (createdBindings) backrefs.add(bindings); } private ConByMethodInfo initializeConCalledByMethodInterceptorsMap(Method callingMethod, long callingMethodHash, String calledClass, long calledConHash, Constructor calledCon) throws Exception { HashMap calledClassesMap = (HashMap) conCalledByMethodInterceptors.get(callingMethodHash); if (calledClassesMap == null) { calledClassesMap = new HashMap(); conCalledByMethodInterceptors.put(callingMethodHash, calledClassesMap); } TLongObjectHashMap calledMethodsMap = calledClassesMap.get(calledClass); if (calledMethodsMap == null) { calledMethodsMap = new TLongObjectHashMap(); calledClassesMap.put(calledClass, calledMethodsMap); } ConByMethodInfo info = createConByMethodInfo(calledClass, callingMethod, callingMethodHash, calledCon, calledConHash); calledMethodsMap.put(calledConHash, info); return info; } private void initializeConCalledByMethodEmptyChain(long callingMethodHash, String calledClass, long calledConHash) throws Exception { HashMap callingMethod = (HashMap) conCalledByMethodBindings.get(callingMethodHash); if (callingMethod == null) { callingMethod = new HashMap(); conCalledByMethodBindings.put(callingMethodHash, callingMethod); } TLongObjectHashMap classMap = callingMethod.get(calledClass); if (classMap == null) { classMap = new TLongObjectHashMap(); callingMethod.put(calledClass, classMap); } ArrayList bindings = (ArrayList) classMap.get(calledConHash); if (bindings == null) { bindings = new ArrayList(); classMap.put(calledConHash, bindings); } } private ConByMethodInfo getConCalledByMethod(long callingMethodHash, String calledClass, long calledConHash) { HashMap calledClasses = (HashMap) conCalledByMethodInterceptors.get(callingMethodHash); TLongObjectHashMap calledMethods = calledClasses.get(calledClass); ConByMethodInfo info = (ConByMethodInfo) calledMethods.get(calledConHash); return info; } private ConByMethodInfo createConByMethodInfo(String calledClass, Method callingMethod, long callingMethodHash, Constructor calledCon, long calledConHash) throws Exception { //The standard ConstructorCalledByXXXXInvocation class calls by reflection and needs access calledCon.setAccessible(true); Class calledClazz = getClassLoader().loadClass(calledClass); try { int index = calledClass.lastIndexOf('.'); String baseClassName = calledClass.substring(index + 1); Method wrapper = calledCon.getDeclaringClass().getDeclaredMethod(ConstructorExecutionTransformer.constructorFactory(baseClassName), calledCon.getParameterTypes()); return new ConByMethodInfo(ClassAdvisor.this, calledClazz, callingMethod, callingMethodHash, calledCon, calledConHash, wrapper, null); } catch (NoSuchMethodException e) { return new ConByMethodInfo(ClassAdvisor.this, calledClazz, callingMethod, callingMethodHash, calledCon, calledConHash, null, null); } } private void bindConCalledByMethodInterceptorChain(ArrayList bindings, long callingHash, String cname, long calledHash) throws Exception { ConByMethodInfo info = getConCalledByMethod(callingHash, cname, calledHash); info.clear(); for (AdviceBinding binding : bindings) { if (BindingClassifier.isConstructorCall(binding)) { pointcutResolved(info, binding, new ConstructorCalledByMethodJoinpoint(info.getCallingMethod(), info.getConstructor())); } } finalizeConCalledByMethodInterceptorChain(info); } public void cleanup() { conCalledByMethodBindings.clear(); conCalledByMethodInterceptors.clear(); } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/ant/0000755000175000017500000000000011145122062026427 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/ant/AnnotationC.java0000644000175000017500000002063411145122054031515 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.ant; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import java.io.File; import java.util.ArrayList; /** * Ant task. Copied a bunch of shit from javac task * * @author Bill Burke * @version $Revision: 70842 $ * **/ public class AnnotationC extends MatchingTask { private static String lSep = System.getProperty("line.separator"); private Path classpath; private Path output; private Path compilerClasspath; private Path compileSourcepath; boolean xml = false; boolean bytecode = false; /** * flag to control action on execution trouble */ protected boolean failOnError = true; public void setXml(boolean i) { xml = i; } public boolean getXml() { return xml; } public void setBytecode(boolean i) { bytecode = i; } public boolean getBytecode() { return xml; } /** * Whether or not the build should halt if compilation fails. * Defaults to true. */ public void setFailonerror(boolean fail) { failOnError = fail; } /** * Gets the failonerror flag. */ public boolean getFailonerror() { return failOnError; } /** * Set the classpath to be used for this compilation. */ public void setClasspath(Path cp) { if (classpath == null) { classpath = cp; } else { classpath.append(cp); } } /** * Adds a path to the classpath. */ public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } /** * Adds a reference to a classpath defined elsewhere */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } public Path getClasspath() { return classpath; } /** * Adds a reference to a classpath defined elsewhere */ public void setCompilerClasspathRef(Reference r) { if (compilerClasspath == null) compilerClasspath = new Path(getProject()); compilerClasspath.setRefid(r); } /** * Set the classpath to be used to find this compiler adapter */ public void setCompilerclasspath(Path cp) { if (compilerClasspath == null) { compilerClasspath = cp; } else { compilerClasspath.append(cp); } } /** * get the classpath used to find the compiler adapter */ public Path getCompilerclasspath() { return compilerClasspath; } /** * Support nested compiler classpath, used to locate compiler adapter */ public Path createCompilerclasspath() { if (compilerClasspath == null) { compilerClasspath = new Path(getProject()); } return compilerClasspath.createPath(); } /** * Adds a path for source compilation. * * @return a nested src element. */ public Path createSrc() { if (compileSourcepath == null) { compileSourcepath = new Path(getProject()); } return compileSourcepath.createPath(); } public Path createOutput() { if (output == null) { output = new Path(getProject()); } return output.createPath(); } /** * Set the classpath to be used to find this compiler adapter */ public void setOutput(Path cp) { if (output == null) { output = cp; } else { output.append(cp); } } /** * get the classpath used to find the compiler adapter */ public Path getOutput() { return output; } public void execute() throws BuildException { CommandlineJava cmd = new CommandlineJava(); if (output != null) { cmd.createArgument().setValue("-o"); cmd.createArgument().setValue(output.toString()); } if (xml) { cmd.createArgument().setValue("-xml"); } if (bytecode) { cmd.createArgument().setValue("-bytecode"); } logAndAddFilesToCompile(cmd); try { // Create an instance of the compiler, redirecting output to // the project log classpath.append(compilerClasspath); Java java = (Java) (getProject().createTask("java")); if (getClasspath() != null) { getProject().log("using user supplied classpath: " + getClasspath(), Project.MSG_DEBUG); java.setClasspath(getClasspath() .concatSystemClasspath("ignore")); } else { Path classpath = new Path(getProject()); classpath = classpath.concatSystemClasspath("only"); getProject().log("using system classpath: " + classpath, Project.MSG_DEBUG); java.setClasspath(classpath); } java.setDir(getProject().getBaseDir()); java.setClassname("org.jboss.aop.annotation.compiler.AnnotationCompiler"); //this is really irritating; we need a way to set stuff String args[] = cmd.getJavaCommand().getArguments(); for (int i = 0; i < args.length; i++) { java.createArg().setValue(args[i]); } java.setFailonerror(getFailonerror()); //we are forking here to be sure that if JspC calls //System.exit() it doesn't halt the build java.setFork(false); java.setTaskName("annotationc"); java.execute(); } catch (Exception ex) { if (ex instanceof BuildException) { throw (BuildException) ex; } else { throw new BuildException("Error running aopc compiler: ", ex, getLocation()); } } } protected void logAndAddFilesToCompile(CommandlineJava cmd) { // scan source directories and dest directory to build up // compile lists String[] list = compileSourcepath.list(); ArrayList compilingFiles = new ArrayList(); for (int i = 0; i < list.length; i++) { File srcDir = getProject().resolveFile(list[i]); if (!srcDir.exists()) { throw new BuildException("srcdir \"" + srcDir.getPath() + "\" does not exist!", getLocation()); } DirectoryScanner ds = this.getDirectoryScanner(srcDir); String[] files = ds.getIncludedFiles(); for (int j = 0; j < files.length; j++) { if (files[j].endsWith(".java")) { File f = new File(srcDir, files[j]); compilingFiles.add(f.getAbsolutePath()); } } } StringBuffer niceSourceList = new StringBuffer("File"); for (int i = 0; i < compilingFiles.size(); i++) { String file = compilingFiles.get(i); cmd.createArgument().setValue(file); niceSourceList.append(" " + file + lSep); } //getProject().log(niceSourceList.toString()); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/ant/AopC.java0000644000175000017500000003217211145122062030121 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.ant; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; /** * Ant task. Copied a bunch of shit from javac task * * @author Bill Burke * @version $Revision: 74708 $ */ public class AopC extends MatchingTask { final static String SYS_OPTIMIZED = "jboss.aop.optimized"; final static String SYS_INSTRUMENTOR = "jboss.aop.instrumentor"; private final static String MSG_PREFIX = "\n[aopc] "; private static String lSep = System.getProperty("line.separator"); private int maxSrc = 1000; private String instrumentor; private String jvm; private Path classpath; private Path aoppath; private Path aopclasspath; private Path compilerClasspath; private Path compileSourcepath; private boolean verbose = false; private boolean suppress = true; private boolean report = false; private boolean optimized = true; private String maxmemory = null; ArrayList sysproperties = new ArrayList(); File sourceFiles; /** * flag to control action on execution trouble */ protected boolean failOnError = true; /** * Set the verbose level of the compiler */ public void setVerbose(boolean i) { verbose = i; } public boolean getVerbose() { return verbose; } public String getInstrumentor() { return instrumentor; } public void setInstrumentor(String instrumentor) { this.instrumentor = instrumentor; } /** * Set the verbose level of the compiler */ public void setSuppress(boolean i) { suppress = i; } public boolean getSupress() { return suppress; } public void setReport(boolean i) { report = i; } public boolean getReport() { return report; } public String getJvm() { return jvm; } public void setJvm(String jvm) { this.jvm = jvm; } public void setOptimized(boolean optimized) { this.optimized = optimized; } public boolean getOptimized() { return optimized; } /** * Set the maxmemory of the Java task forked to apply the AOP */ public void setMaxmemory(String maxmemory) { this.maxmemory = maxmemory; } public String getMaxmemory() { return maxmemory; } /** * Whether or not the build should halt if compilation fails. * Defaults to true. */ public void setFailonerror(boolean fail) { failOnError = fail; } /** * Gets the failonerror flag. */ public boolean getFailonerror() { return failOnError; } /** * Set the classpath to be used for this compilation. */ public void setClasspath(Path cp) { if (classpath == null) { classpath = cp; } else { classpath.append(cp); } } public void setMaxSrc(int maxSrc) { this.maxSrc = maxSrc; } public int getMaxSrc() { return maxSrc; } /** * Adds a path to the classpath. */ public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } /** * Adds a reference to a classpath defined elsewhere */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } public Path getClasspath() { return classpath; } /** * Adds a reference to a classpath defined elsewhere */ public void setCompilerClasspathRef(Reference r) { if (compilerClasspath == null) compilerClasspath = new Path(getProject()); compilerClasspath.setRefid(r); } /** * Set the classpath to be used to find this compiler adapter */ public void setCompilerclasspath(Path cp) { if (compilerClasspath == null) { compilerClasspath = cp; } else { compilerClasspath.append(cp); } } /** * get the classpath used to find the compiler adapter */ public Path getCompilerclasspath() { return compilerClasspath; } /** * Support nested compiler classpath, used to locate compiler adapter */ public Path createCompilerclasspath() { if (compilerClasspath == null) { compilerClasspath = new Path(getProject()); } return compilerClasspath.createPath(); } /** * Adds a path for source compilation. * * @return a nested src element. */ public Path createSrc() { if (compileSourcepath == null) { compileSourcepath = new Path(getProject()); } return compileSourcepath.createPath(); } public Path createAoppath() { if (aoppath == null) { aoppath = new Path(getProject()); } //return aoppath.createPath(); Path path = aoppath.createPath(); return path; } public Path createAopclasspath() { if (aopclasspath == null) { aopclasspath = new Path(getProject()); } return aopclasspath.createPath(); } public void addSysproperty(Environment.Variable property) { sysproperties.add(property); } public void execute() throws BuildException { CommandlineJava cmd = new CommandlineJava(); if (compileSourcepath == null) { throw new BuildException(MSG_PREFIX + "'src' path element not found"); } if (classpath == null) { throw new BuildException(MSG_PREFIX + "classpath undefined (use 'classpath' path elements and/or the 'classpathref' attribute)"); } if (verbose) cmd.createArgument().setValue("-verbose"); if (suppress) cmd.createArgument().setValue("-suppress"); if (!optimized) cmd.createArgument().setValue("-noopt"); if (report) cmd.createArgument().setValue("-report"); if (aoppath != null && aoppath.size() > 0) { cmd.createArgument().setValue("-aoppath"); cmd.createArgument().setValue(aoppath.toString()); } if (aopclasspath != null && aopclasspath.size() > 0) { cmd.createArgument().setValue("-aopclasspath"); cmd.createArgument().setValue(aopclasspath.toString()); } logAndAddFilesToCompile(cmd); try { // Create an instance of the compiler, redirecting output to // the project log classpath.append(compilerClasspath); Java java = (Java) (getProject().createTask("java")); if (jvm != null && jvm.length() > 0) { java.setJvm(jvm); } if (getClasspath() != null) { getProject().log("using user supplied classpath: " + getClasspath(), Project.MSG_DEBUG); java.setClasspath(getClasspath() .concatSystemClasspath("ignore")); } else { Path classpath = new Path(getProject()); classpath = classpath.concatSystemClasspath("only"); getProject().log("using system classpath: " + classpath, Project.MSG_DEBUG); java.setClasspath(classpath); } java.setDir(getProject().getBaseDir()); java.setClassname("org.jboss.aop.standalone.Compiler"); //this is really irritating; we need a way to set stuff String args[] = cmd.getJavaCommand().getArguments(); for (int i = 0; i < args.length; i++) { java.createArg().setValue(args[i]); } java.setFailonerror(getFailonerror()); //we are forking here to be sure that if JspC calls //System.exit() it doesn't halt the build java.setFork(true); java.setTaskName("aopc"); Environment.Variable optimize = new Environment.Variable(); optimize.setKey(SYS_OPTIMIZED); optimize.setValue(String.valueOf(optimized)); java.addSysproperty(optimize); for (Environment.Variable var : sysproperties) { java.addSysproperty(var); } if (maxmemory != null) { java.setMaxmemory(maxmemory); } java.execute(); } catch (Exception ex) { if (ex instanceof BuildException) { throw (BuildException) ex; } else { throw new BuildException(MSG_PREFIX + "error running aopc compiler", ex, getLocation()); } } finally { if (sourceFiles != null) { //deleteOnExit does not seem to work so do it explicitly here sourceFiles.delete(); } } } protected void logAndAddFilesToCompile(CommandlineJava cmd) { // scan source directories and dest directory to build up // compile lists String[] list = compileSourcepath.list(); ArrayList compilingFiles = new ArrayList(); for (int i = 0; i < list.length; i++) { File srcDir = getProject().resolveFile(list[i]); if (!srcDir.exists()) { throw new BuildException(MSG_PREFIX + "srcdir \"" + srcDir.getPath() + "\" does not exist!", getLocation()); } DirectoryScanner ds = this.getDirectoryScanner(srcDir); String[] files = ds.getIncludedFiles(); for (int j = 0; j < files.length; j++) { if (files[j].endsWith(".class")) { File f = new File(srcDir, files[j]); compilingFiles.add(f.getAbsolutePath()); } } } int length = 0; for (int i = 0; i < compilingFiles.size(); i++) { //Add 1 to allow for the spaces between args length += compilingFiles.get(i).length() + 1; if (length > maxSrc) { break; } } if (length < maxSrc) { StringBuffer niceSourceList = new StringBuffer("Files\n"); for (int i = 0; i < compilingFiles.size(); i++) { String file = compilingFiles.get(i); cmd.createArgument().setValue(file); niceSourceList.append(" " + file + lSep); } } else { for (Environment.Variable var : sysproperties) { if (var.getKey().equals("java.io.tmpdir")) { System.setProperty("java.io.tmpdir", var.getValue()); } } BufferedWriter writer = null; try { sourceFiles = File.createTempFile("src", ".tmp"); if (verbose) { System.out.println("[info] Total length of filenames to be compiled is greater than " + maxSrc + ", listing files in --SOURCEPATH: " + sourceFiles.getAbsolutePath()); } sourceFiles.deleteOnExit(); writer = new BufferedWriter(new FileWriter(sourceFiles)); for (int i = 0; i < compilingFiles.size(); i++) { writer.write(compilingFiles.get(i)); writer.newLine(); } writer.flush(); cmd.createArgument().setValue("--SOURCEPATH"); cmd.createArgument().setValue(sourceFiles.getAbsolutePath()); } catch (IOException e) { if (writer != null) { try { writer.close(); } catch (IOException e1) { } } throw new RuntimeException(e); } } } }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/DomainDefinition.java0000644000175000017500000000331611145122054031734 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; /** * Comment * * @author Bill Burke * @version $Revision: 57778 $ */ public class DomainDefinition { private String name; private AspectManager manager; public DomainDefinition(String name, AspectManager parent, boolean parentFirst, boolean inheritDefs, boolean inheritBindings) { this.name = name; Domain domain = new Domain(parent, name, parentFirst); domain.setInheritsBindings(inheritBindings); domain.setInheritsDeclarations(inheritDefs); manager = domain; } public String getName() { return name; } public AspectManager getManager() { return manager; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/introduction/0000755000175000017500000000000011145122064030370 5ustar twernertwerner././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/introduction/InterfaceIntroduction.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/introduction/InterfaceIntrod0000644000175000017500000001657311145122064033407 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.introduction; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.io.StringReader; import org.jboss.aop.Advisor; import org.jboss.aop.pointcut.TypeMatcher; import org.jboss.aop.pointcut.Util; import org.jboss.aop.pointcut.ast.ASTStart; import org.jboss.aop.pointcut.ast.ClassExpression; import org.jboss.aop.pointcut.ast.TypeExpressionParser; import org.jboss.aop.pointcut.ast.ParseException; import javassist.CtClass; /** * @author Bill Burke * @version $Revision: 70842 $ */ public class InterfaceIntroduction { public static class Mixin { protected String classname; protected String[] interfaces; protected String construction; protected boolean trans; public Mixin() {} public Mixin(String classname, String[] interfaces, String construction, boolean trans) { this.classname = classname; this.interfaces = interfaces; this.construction = construction; this.trans = trans; } public String getClassName() { return classname; } public String[] getInterfaces() { return interfaces; } public String getConstruction() { return construction; } public boolean isTransient() { return trans; } public void setClassname(String classname) { this.classname = classname; } public void setInterfaces(String[] interfaces) { this.interfaces = interfaces; } public void setConstruction(String construction) { this.construction = construction; } public void setTrans(boolean trans) { this.trans = trans; } } protected String name; protected ArrayList> advisors = new ArrayList>(); protected String[] interfaces; protected ArrayList mixins = new ArrayList(); protected ClassExpression classExpr; protected ASTStart ast; protected String constructorClass; // name of the class containing the mixin constructor method protected String constructorMethod; // name of the mixin constructor method public InterfaceIntroduction() { } public InterfaceIntroduction(String name, String exp, String[] interfaces) { this.name = name; this.interfaces = interfaces; this.classExpr = new ClassExpression(exp); } // call this constructor only when constructor method receives the mixin target // as parameter, for posterior validation of constructor method signature public InterfaceIntroduction(String name, String exp, String[] interfaces, String constructorClass, String constructorMethod) { this(name, exp, interfaces); this.constructorClass = constructorClass; this.constructorMethod = constructorMethod; } public InterfaceIntroduction(String name, ASTStart ast, String[] interfaces) { this.name = name; this.ast = ast; this.interfaces = interfaces; } // call this constructor only when constructor method receives the mixin target // as parameter, for posterior validation of constructor method signature public InterfaceIntroduction(String name, ASTStart ast, String[] interfaces, String constructorClass, String constructorMethod) { this(name, ast, interfaces); this.constructorClass = constructorClass; this.constructorMethod = constructorMethod; } public void setClassExpression(String exp) { this.classExpr = new ClassExpression(exp); } public void setTypeExpression(String exp) { try { ast = new TypeExpressionParser(new StringReader(exp)).Start(); } catch (ParseException e) { throw new RuntimeException(e); } } public void setMixins(ArrayList mixins) { this.mixins = mixins; } public void addMixin(Mixin mixin) { mixins.add(mixin); } public void setInterfaces(String[] interfaces) { this.interfaces = interfaces; } public void setName(String name) { this.name = name; } public String getName() { return name; } public String[] getInterfaces() { return interfaces; } public ArrayList getMixins() { return mixins; } // this value is set only when there is a mixin constructor method and this // method receives the target as parameter public String getConstructorClass() { return this.constructorClass; } // this value is set only when there is a mixin constructor method and this // method receives the target as parameter public String getConstructorMethod() { return this.constructorMethod; } public void addAdvisor(Advisor advisor) { advisors.add(new WeakReference(advisor)); advisor.addInterfaceIntroduction(this); } public void clearAdvisors() { for (int i = 0; i < advisors.size(); i++) { Advisor advisor = advisors.get(i).get(); if (advisor != null) advisor.removeInterfaceIntroduction(this); } } public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof InterfaceIntroduction)) return false; return ((InterfaceIntroduction) obj).getName().equals(name); } public int hashCode() { return name.hashCode(); } public String getClassExpr() { if (classExpr == null) return null; return classExpr.getOriginal(); } public ASTStart getAst() { return ast; } public boolean matches(Advisor advisor, CtClass clazz) throws Exception { if (classExpr != null) return Util.matchesClassExpr(classExpr, clazz, advisor); else { TypeMatcher matcher = new TypeMatcher(advisor, clazz); return ((Boolean) ast.jjtAccept(matcher, null)).booleanValue(); } } public boolean matches(Advisor advisor, Class clazz) { if (classExpr != null) return Util.matchesClassExpr(classExpr, clazz, advisor); else { TypeMatcher matcher = new TypeMatcher(advisor, clazz); return ((Boolean) ast.jjtAccept(matcher, null)).booleanValue(); } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/introduction/AnnotationIntroduction.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/introduction/AnnotationIntro0000644000175000017500000001522511145122064033446 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.introduction; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.annotation.factory.ast.ASTAnnotation; import org.jboss.annotation.factory.ast.AnnotationParser; import org.jboss.annotation.factory.ast.ParseException; import org.jboss.aop.pointcut.AnnotationMatcher; import org.jboss.aop.pointcut.ast.ASTStart; import org.jboss.aop.pointcut.ast.TypeExpressionParser; import org.jboss.aop.util.logging.AOPLogger; import org.jboss.util.StringPropertyReplacer; import java.io.StringReader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Comment * * @author Bill Burke * @version $Revision: 79516 $ */ public class AnnotationIntroduction { final static AOPLogger logger = AOPLogger.getLogger(AnnotationIntroduction.class); public static AnnotationIntroduction createMethodAnnotationIntroduction(String methodExpr, String annotationExpr, boolean invisible) { String expr = "method(" + methodExpr + ")"; return new AnnotationIntroduction(expr, annotationExpr, invisible); } public static AnnotationIntroduction createConstructorAnnotationIntroduction(String conExpr, String annotationExpr, boolean invisible) { String expr = "constructor(" + conExpr + ")"; return new AnnotationIntroduction(expr, annotationExpr, invisible); } public static AnnotationIntroduction createFieldAnnotationIntroduction(String fieldExpr, String annotationExpr, boolean invisible) { String expr = "field(" + fieldExpr + ")"; return new AnnotationIntroduction(expr, annotationExpr, invisible); } public static AnnotationIntroduction createClassAnnotationIntroduction(String classExpr, String annotationExpr, boolean invisible) { String expr = "class(" + classExpr + ")"; return new AnnotationIntroduction(expr, annotationExpr, invisible); } public static AnnotationIntroduction createComplexAnnotationIntroduction(String expr, String annotationExpr, boolean invisible) { return new AnnotationIntroduction(expr, annotationExpr, invisible); } private String originalExpression; private String originalAnnotationExpr; private ASTStart target; private ASTAnnotation annotation; private boolean invisible; private AnnotationIntroduction(String expr, String annotationExpr, boolean invisible) { this.invisible = invisible; originalAnnotationExpr = StringPropertyReplacer.replaceProperties(annotationExpr); originalExpression = expr; try { if (AspectManager.verbose && logger.isTraceEnabled()) { logger.trace("Creating annotation from " + originalAnnotationExpr); } AnnotationParser parser = new AnnotationParser(new StringReader(originalAnnotationExpr)); org.jboss.annotation.factory.ast.ASTStart start = parser.Start(); annotation = (ASTAnnotation) start.jjtGetChild(0); } catch (ParseException e) { throw new RuntimeException(annotationExpr, e); //To change body of catch statement use Options | File Templates. } try { TypeExpressionParser parser = new TypeExpressionParser(new StringReader(expr)); target = parser.Start(); } catch (org.jboss.aop.pointcut.ast.ParseException e) { throw new RuntimeException(expr, e); //To change body of catch statement use Options | File Templates. } } public boolean matches(Advisor advisor, CtClass clazz) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, clazz); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public boolean matches(Advisor advisor, CtMethod method) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, method); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public boolean matches(Advisor advisor, CtConstructor con) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, con); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public boolean matches(Advisor advisor, CtField field) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, field); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public boolean matches(Advisor advisor, Class clazz) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, clazz); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public boolean matches(Advisor advisor, Method method) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, method); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public boolean matches(Advisor advisor, Constructor con) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, con); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public boolean matches(Advisor advisor, Field field) { AnnotationMatcher matcher = new AnnotationMatcher(advisor, field); return ((Boolean) target.jjtAccept(matcher, null)).booleanValue(); } public String getOriginalExpression() { return originalExpression; } public String getOriginalAnnotationExpr() { return originalAnnotationExpr; } public ASTAnnotation getAnnotation() { return annotation; } public boolean isInvisible() { return invisible; } public ASTStart getTarget() { return target; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/Domain.java0000644000175000017500000012473611145122056027737 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.AdviceStack; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.ClassifiedBindingAndPointcutCollection; import org.jboss.aop.advice.DynamicCFlowDefinition; import org.jboss.aop.advice.InterceptorFactory; import org.jboss.aop.advice.PrecedenceDef; import org.jboss.aop.array.ArrayReplacement; import org.jboss.aop.introduction.AnnotationIntroduction; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.metadata.ClassMetaDataBinding; import org.jboss.aop.metadata.ClassMetaDataLoader; import org.jboss.aop.microcontainer.lifecycle.LifecycleCallbackBinding; import org.jboss.aop.pointcut.CFlowStack; import org.jboss.aop.pointcut.DynamicCFlow; import org.jboss.aop.pointcut.Pointcut; import org.jboss.aop.pointcut.PointcutInfo; import org.jboss.aop.pointcut.Typedef; import org.jboss.aop.pointcut.ast.ClassExpression; import org.jboss.aop.util.UnmodifiableEmptyCollections; /** * Comment * * @author Bill Burke * @author adrian@jboss.org * @version $Revision: 81449 $ */ public class Domain extends AspectManager { String name; protected AspectManager parent; protected boolean parentFirst; protected boolean inheritsDeclarations = true; protected boolean inheritsBindings = false; //Calculating the size of the collections containing this information is timeconsuming, we //only want to do this when adding/removing stuff protected boolean hasOwnPointcuts; protected boolean hasOwnBindings; protected boolean hasOwnAnnotationIntroductions; protected boolean hasOwnAnnotationOverrides; protected boolean hasOwnInterfaceIntroductions; protected boolean hasOwnTypedefs; protected boolean hasOwnPrecedenceDefs; protected boolean hasOwnClassMetaData; private static int sequenceNumber; public Domain(AspectManager manager, String name, boolean parentFirst) { this.parent = manager; this.parentFirst = parentFirst; this.name = name; manager.addSubDomainByName(this); } /** * Creates the binding collection to be used as the collection by this domain * @return a {@link DomainClassifiedBindingAndPointcutCollection} */ @Override protected ClassifiedBindingAndPointcutCollection createBindingCollection() { return new DomainClassifiedBindingAndPointcutCollection(); } // FIXME: JBAOP-107 REMOVE THIS HACK public boolean isValid() { return true; } public String getDomainName() { return name; } public String getManagerFQN() { return parent.getManagerFQN() + name + "/"; } public static String getDomainName(final Class clazz, final boolean forInstance) { String name = AccessController.doPrivileged(new PrivilegedAction() { public String run() { StringBuffer sb = new StringBuffer(); sb.append(clazz.getName()); sb.append("_"); sb.append(System.identityHashCode(SecurityActions.getClassLoader(clazz))); if (forInstance) { sb.append("_"); sb.append(getNextSequenceNumber()); } return sb.toString(); } }); return name; } private synchronized static int getNextSequenceNumber() { return sequenceNumber++; } /** * Inherits interceptor, aspect, advice stack definitions * * @param inheritsDeclarations */ public void setInheritsDeclarations(boolean inheritsDeclarations) { this.inheritsDeclarations = inheritsDeclarations; } public void setInheritsBindings(boolean inheritBindings) { this.inheritsBindings = inheritBindings; if (inheritsBindings) { parent.subscribeSubDomain(this); } else { parent.unsubscribeSubDomain(this); } } @Override public LinkedHashMap getBindings() { if (inheritsBindings) { if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. LinkedHashMap map = new LinkedHashMap(parent.getBindings()); map.putAll(this.bindingCollection.getBindings()); return map; } else { LinkedHashMap map = new LinkedHashMap(this.bindingCollection.getBindings()); map.putAll(parent.getBindings()); return map; } } return super.getBindings(); } public boolean hasOwnBindings() { return hasOwnBindings; } @Override public synchronized void addBinding(AdviceBinding binding) { lock.lockWrite(); try { hasOwnPointcuts = true; hasOwnBindings = true; super.addBinding(binding); } finally { lock.unlockWrite(); } } @Override public synchronized void removeBinding(String name) { lock.lockWrite(); try { super.removeBinding(name); hasOwnBindings = !bindingCollection.isEmpty(); hasOwnPointcuts = !bindingCollection.hasPointcuts(); } finally { lock.unlockWrite(); } } @Override public synchronized void removeBindings(ArrayList binds) { lock.lockWrite(); try { super.removeBindings(binds); hasOwnBindings = !bindingCollection.isEmpty(); hasOwnPointcuts = !bindingCollection.hasPointcuts(); } finally { lock.unlockWrite(); } } @Override public LinkedHashMap getPointcuts() { return bindingCollection.getPointcuts(); } public boolean hasOwnPointcuts() { return hasOwnPointcuts; } @Override public synchronized void addPointcut(Pointcut pointcut) { hasOwnPointcuts = true; super.addPointcut(pointcut); } @Override public void removePointcut(String name) { super.removePointcut(name); hasOwnPointcuts = bindingCollection.hasPointcuts(); } @Override public LinkedHashMap getPointcutInfos() { return bindingCollection.getPointcutInfos(); } @Override public List getAnnotationIntroductions() { if (inheritsBindings) { List result = new ArrayList(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. result.addAll(parent.getAnnotationIntroductions()); synchronized (annotationIntroductions) { result = new ArrayList(annotationIntroductions.values()); } return result; } else { synchronized (annotationIntroductions) { result = new ArrayList(annotationIntroductions.values()); } result.addAll(parent.getAnnotationIntroductions()); return result; } } return super.getAnnotationIntroductions(); } @Override public Map getArrayReplacements() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getArrayReplacements()); synchronized (arrayReplacements) { map.putAll(arrayReplacements); } return map; } else { synchronized (arrayReplacements) { map.putAll(arrayReplacements); } map.putAll(parent.getArrayReplacements()); return map; } } return super.getArrayReplacements(); } public boolean hasOwnAnnotationIntroductions() { return hasOwnAnnotationIntroductions; } @Override public synchronized void addAnnotationIntroduction(AnnotationIntroduction pointcut) { hasOwnAnnotationIntroductions = true; super.addAnnotationIntroduction(pointcut); } @Override public void removeAnnotationIntroduction(AnnotationIntroduction pointcut) { super.removeAnnotationIntroduction(pointcut); hasOwnAnnotationIntroductions = annotationIntroductions.size() > 0; } @Override public List getAnnotationOverrides() { if (inheritsBindings) { ArrayList list = new ArrayList(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. list.addAll(parent.getAnnotationOverrides()); synchronized (annotationOverrides) { list.addAll(annotationOverrides.values()); } return list; } else { synchronized (annotationOverrides) { list.addAll(annotationOverrides.values()); } list.addAll(parent.getAnnotationOverrides()); return list; } } return super.getAnnotationOverrides(); } public boolean hasOwnAnnotationOverrides() { return hasOwnAnnotationOverrides; } @Override public synchronized void addAnnotationOverride(AnnotationIntroduction pointcut) { hasOwnAnnotationOverrides = true; super.addAnnotationOverride(pointcut); } @Override public void removeAnnotationOverride(AnnotationIntroduction pointcut) { super.removeAnnotationOverride(pointcut); hasOwnAnnotationOverrides = annotationOverrides.size() > 0; } @Override public Map getInterfaceIntroductions() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getInterfaceIntroductions()); synchronized (interfaceIntroductions) { map.putAll(interfaceIntroductions); } return map; } else { synchronized (interfaceIntroductions) { map.putAll(interfaceIntroductions); } map.putAll(parent.getInterfaceIntroductions()); return map; } } return super.getInterfaceIntroductions(); } public boolean hasOwnInterfaceIntroductions() { return hasOwnInterfaceIntroductions; } @Override public synchronized void addInterfaceIntroduction(InterfaceIntroduction pointcut) { hasOwnInterfaceIntroductions = true; super.addInterfaceIntroduction(pointcut); } @Override public void removeInterfaceIntroduction(String name) { super.removeInterfaceIntroduction(name); hasOwnInterfaceIntroductions = interfaceIntroductions.size() > 0; } @Override public Map getTypedefs() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getTypedefs()); synchronized (typedefs) { map.putAll(typedefs); } return map; } else { synchronized (typedefs) { map.putAll(typedefs); } map.putAll(parent.getTypedefs()); return map; } } return super.getTypedefs(); } public boolean hasOwnTypedefs() { return hasOwnTypedefs; } @Override public synchronized void addTypedef(Typedef def) throws Exception { hasOwnTypedefs = true; super.addTypedef(def); } @Override public void removeTypedef(String name) { super.removeTypedef(name); hasOwnTypedefs = typedefs.size() > 0; } public Map getInterceptorStacks() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getInterceptorStacks()); synchronized (interceptorStacks) { map.putAll(interceptorStacks); } return map; } else { synchronized (interceptorStacks) { map.putAll(interceptorStacks); } map.putAll(parent.getInterceptorStacks()); return map; } } return super.getInterceptorStacks(); } @Override public Map getClassMetaDataLoaders() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getClassMetaDataLoaders()); synchronized (classMetaDataLoaders) { map.putAll(classMetaDataLoaders); } return map; } else { synchronized (classMetaDataLoaders) { map.putAll(classMetaDataLoaders); } map.putAll(parent.getClassMetaDataLoaders()); return map; } } return super.getClassMetaDataLoaders(); } @Override public Map getCflowStacks() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getCflowStacks()); synchronized (cflowStacks) { map.putAll(cflowStacks); } return map; } else { synchronized (cflowStacks) { map.putAll(cflowStacks); } map.putAll(parent.getCflowStacks()); return map; } } return super.getCflowStacks(); } @Override public Map getDynamicCFlows() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getDynamicCFlows()); synchronized (dynamicCFlows) { map.putAll(dynamicCFlows); } return map; } else { synchronized (dynamicCFlows) { map.putAll(dynamicCFlows); } map.putAll(parent.getDynamicCFlows()); return map; } } return super.getDynamicCFlows(); } @Override public Map getPerVMAspects() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getPerVMAspects()); synchronized (perVMAspects) { map.putAll(perVMAspects); } return map; } else { synchronized (perVMAspects) { map.putAll(perVMAspects); } map.putAll(parent.getPerVMAspects()); return map; } } return super.getPerVMAspects(); } @Override public LinkedHashMap getPrecedenceDefs() { if (inheritsDeclarations) { if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. LinkedHashMap map = new LinkedHashMap(parent.getPrecedenceDefs()); map.putAll(this.precedenceDefs); return map; } else { LinkedHashMap map = new LinkedHashMap(this.precedenceDefs); map.putAll(parent.getPrecedenceDefs()); return map; } } return super.getPrecedenceDefs(); } public boolean hasOwnPrecedenceDefs() { return hasOwnPrecedenceDefs; } @Override public void addPrecedence(PrecedenceDef precedenceDef) { hasOwnPrecedenceDefs = true; super.addPrecedence(precedenceDef); } @Override public void removePrecedence(String name) { super.removePrecedence(name); hasOwnPrecedenceDefs = precedenceDefs.size() > 0; } @Override public Map getClassMetaData() { if (inheritsBindings) { HashMap map = new HashMap(); if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. map.putAll(parent.getClassMetaData()); synchronized (classMetaData) { map.putAll(classMetaData); } return map; } else { synchronized (classMetaData) { map.putAll(classMetaData); } map.putAll(parent.getClassMetaData()); return map; } } return super.getClassMetaData(); } public boolean hasOwnClassMetaData() { return hasOwnClassMetaData; } @Override public void removeClassMetaData(String name) { super.removeClassMetaData(name); hasOwnClassMetaData = classMetaData.size() > 0; } @Override public void addClassMetaData(ClassMetaDataBinding meta) { hasOwnClassMetaData = true; super.addClassMetaData(meta); } public boolean hasOwnDataWithEffectOnAdvices() { return hasOwnBindings || hasOwnPointcuts || hasOwnAnnotationIntroductions || hasOwnAnnotationOverrides || hasOwnInterfaceIntroductions || hasOwnTypedefs || hasOwnPrecedenceDefs || hasOwnClassMetaData; } @Override public InterceptorFactory getInterceptorFactory(String name) { InterceptorFactory factory = null; if (parentFirst) { factory = parent.getInterceptorFactory(name); if (factory != null) return factory; } factory = super.getInterceptorFactory(name); if (factory != null) return factory; return parent.getInterceptorFactory(name); } @Override public AdviceStack getAdviceStack(String name) { AdviceStack factory = null; if (parentFirst) { factory = parent.getAdviceStack(name); if (factory != null) return factory; } factory = super.getAdviceStack(name); if (factory != null) return factory; return parent.getAdviceStack(name); } @Override public Object getPerVMAspect(AspectDefinition def) { return getPerVMAspect(def.getName()); } @Override public Object getPerVMAspect(String def) { Object factory = null; if (parentFirst) { factory = parent.getPerVMAspect(def); if (factory != null) return factory; } factory = super.getPerVMAspect(def); if (factory != null) return factory; return parent.getPerVMAspect(def); } @Override public AspectDefinition getAspectDefinition(String name) { AspectDefinition factory = null; if (parentFirst) { factory = parent.getAspectDefinition(name); if (factory != null) return factory; } factory = super.getAspectDefinition(name); if (factory != null) return factory; return parent.getAspectDefinition(name); } @Override public Typedef getTypedef(String name) { Typedef factory = null; if (parentFirst) { factory = parent.getTypedef(name); if (factory != null) return factory; } factory = super.getTypedef(name); if (factory != null) return factory; return parent.getTypedef(name); } @Override public DomainDefinition getContainer(String name) { DomainDefinition container = null; if (parentFirst) { container = parent.getContainer(name); if (container != null) return container; } container = super.getContainer(name); if (container != null) return container; return parent.getContainer(name); } /** * Find a pointcut of with a given name */ @Override public Pointcut getPointcut(String name) { Pointcut pointcut = null; if (parentFirst) { pointcut = parent.getPointcut(name); if (pointcut != null) return pointcut; } pointcut = super.getPointcut(name); if (pointcut != null) return pointcut; return parent.getPointcut(name); } @Override public void attachMetaData(Advisor advisor, Class clazz) { if (inheritsBindings) { if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. parent.attachMetaData(advisor, clazz); super.attachMetaData(advisor, clazz); } else { super.attachMetaData(advisor, clazz); parent.attachMetaData(advisor, clazz); } } else { super.attachMetaData(advisor, clazz); } } @Override public CFlowStack getCFlowStack(String name) { if (inheritsDeclarations) { if (!parentFirst) { CFlowStack cflow = super.getCFlowStack(name); if (cflow == null) { cflow = parent.getCFlowStack(name); } return cflow; } else { CFlowStack cflow = parent.getCFlowStack(name); if (cflow == null) { cflow = super.getCFlowStack(name); } return cflow; } } else { return super.getCFlowStack(name); } } @Override public DynamicCFlow getDynamicCFlow(String name, ClassLoader cl) { if (inheritsBindings) { if (!parentFirst) { DynamicCFlow cflow = super.getDynamicCFlow(name, cl); if (cflow == null) { cflow = parent.getDynamicCFlow(name, cl); } return cflow; } else { DynamicCFlow cflow = parent.getDynamicCFlow(name, cl); if (cflow == null) { cflow = super.getDynamicCFlow(name, cl); } return cflow; } } else { return super.getDynamicCFlow(name, cl); } } @Override public ClassMetaDataLoader findClassMetaDataLoader(String group) { if (inheritsDeclarations) { if (!parentFirst) { ClassMetaDataLoader loader = super.findClassMetaDataLoader(group); if (loader == null) { loader = parent.findClassMetaDataLoader(group); } return loader; } else { ClassMetaDataLoader loader = parent.findClassMetaDataLoader(group); if (loader == null) { loader = super.findClassMetaDataLoader(group); } return loader; } } return super.findClassMetaDataLoader(group); } @Override public Map getLifecycleBindings() { if (inheritsBindings) { if (!parentFirst) { // when child first, parent bindings go in first so that they can be overridden by child. LinkedHashMap map = new LinkedHashMap(parent.getLifecycleBindings()); map.putAll(super.getLifecycleBindings()); return map; } else { LinkedHashMap map = new LinkedHashMap(super.getLifecycleBindings()); map.putAll(parent.getLifecycleBindings()); return map; } } return super.getLifecycleBindings(); } ////////////////////////////////////////////////////////////////////////// //Methods that should delegate to the top AspectManager @Override public InterceptionMarkers getInterceptionMarkers(ClassLoader loader) { return parent.getInterceptionMarkers(loader); } /** Managed by the top-level aspect manager */ @Override protected Map, WeakReference> getSubDomainsPerClass() { return parent.getSubDomainsPerClass(); } /** Only set on a per vm basis */ @Override public ArrayList getExclude() { return parent.getExclude(); } /** Only set on a per vm basis */ @Override public ArrayList getInclude() { return parent.getInclude(); } /** Only set on a per vm basis */ @Override public ArrayList getIgnore() { return parent.getIgnore(); } /** Only set on a per vm basis */ @Override public ClassExpression[] getIgnoreExpressions() { return parent.getIgnoreExpressions(); } /** Only set on a per vm basis */ @Override public List getIncludedInvisibleAnnotations() { return parent.getIncludedInvisibleAnnotations(); } @Override public DynamicAOPStrategy getDynamicAOPStrategy() { return parent.getDynamicAOPStrategy(); } @Override public void setDynamicAOPStrategy(DynamicAOPStrategy strategy) { parent.setDynamicAOPStrategy(strategy); } private class DomainClassifiedBindingAndPointcutCollection extends ClassifiedBindingAndPointcutCollection { @Override public LinkedHashMap getBindings() { LinkedHashMap result = super.getBindingsInternal(); LinkedHashMap parentResult = inheritsBindings ? parent.getBindingCollection().getBindingsInternal() : UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; LinkedHashMap overall = unifyMaps(result, parentResult, parentFirst); if (overall == result || overall == parentResult) { return new LinkedHashMap(overall); } return overall; } @Override public LinkedHashMap getPointcuts() { LinkedHashMap result = super.getPointcutsInternal(); LinkedHashMap parentResult = inheritsBindings ? parent.getBindingCollection().getPointcutsInternal() : UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; LinkedHashMap overall = unifyMaps(result, parentResult, parentFirst); if (overall == result || overall == parentResult) { return new LinkedHashMap(overall); } return overall; } @Override public LinkedHashMap getPointcutInfos() { LinkedHashMap result = super.getPointcutInfosInternal(); LinkedHashMap parentResult = inheritsBindings ? parent.getBindingCollection().getPointcutInfosInternal() : UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; LinkedHashMap overall = unifyMaps(result, parentResult, parentFirst); if (overall == result || overall == parentResult) { return new LinkedHashMap(overall); } return overall; } @Override public Collection getFieldReadBindings() { Collection result = super.getFieldReadBindings(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getFieldReadBindings() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } @Override public Collection getFieldWriteBindings() { Collection result = super.getFieldWriteBindings(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getFieldWriteBindings(): UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } @Override public Collection getConstructionBindings() { Collection result = super.getConstructionBindings(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructionBindings() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } @Override public Collection getConstructorExecutionBindings() { Collection result = super.getConstructorExecutionBindings(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructorExecutionBindings() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } @Override public Collection getMethodExecutionBindings() { Collection result = super.getMethodExecutionBindings(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getMethodExecutionBindings() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } @Override public Collection getConstructorCallBindings() { Collection result = super.getConstructorCallBindings(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructorCallBindings() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } @Override public Collection getMethodCallBindings() { Collection result = super.getMethodCallBindings(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getMethodCallBindings() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getFieldReadPointcuts() { Collection result = super.getFieldReadPointcuts(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getFieldReadPointcuts() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getFieldWritePointcuts() { Collection result = super.getFieldWritePointcuts(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getFieldWritePointcuts() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getConstructionPointcuts() { Collection result = super.getConstructionPointcuts(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructionPointcuts() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getConstructorExecutionPointcuts() { Collection result = super.getConstructorExecutionPointcuts(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructorExecutionPointcuts() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getMethodExecutionPointcuts() { Collection result = super.getMethodExecutionPointcuts(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getMethodExecutionPointcuts() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getConstructorCallPointcuts() { Collection result = super.getConstructorCallPointcuts(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructorCallPointcuts() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getMethodCallPointcuts() { Collection result = super.getMethodCallPointcuts(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getMethodCallPointcuts() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getFieldReadPointcutInfos() { Collection result = super.getFieldReadPointcutInfos(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getFieldReadPointcutInfos() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getFieldWritePointcutInfos() { Collection result = super.getFieldWritePointcutInfos(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getFieldWritePointcutInfos() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getConstructionPointcutInfos() { Collection result = super.getConstructionPointcutInfos(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructionPointcutInfos() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getConstructorExecutionPointcutInfos() { Collection result = super.getConstructorExecutionPointcutInfos(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructorExecutionPointcutInfos() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getMethodExecutionPointcutInfos() { Collection result = super.getMethodExecutionPointcutInfos(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getMethodExecutionPointcutInfos() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getConstructorCallPointcutInfos() { Collection result = super.getConstructorCallPointcutInfos(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getConstructorCallPointcutInfos() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } public Collection getMethodCallPointcutInfos() { Collection result = super.getMethodCallPointcutInfos(); Collection parentResult = inheritsBindings ? parent.getBindingCollection().getMethodCallPointcutInfos() : UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; return unifyCollections(result, parentResult, parentFirst); } @Override public boolean isExecution() { if (super.isExecution()) { return true; } if (inheritsBindings) { return parent.isExecution(); } return false; } @Override public boolean isConstruction() { if (super.isConstruction()) { return true; } if (inheritsBindings) { return parent.isConstruction(); } return false; } @Override public boolean isCall() { if (super.isCall()) { return true; } if (inheritsBindings) { return parent.isCall(); } return false; } @Override public boolean isWithin() { if (super.isWithin()) { return true; } if (inheritsBindings) { return parent.isWithin(); } return false; } @Override public boolean isWithincode() { if (super.isWithincode()) { return true; } if (inheritsBindings) { return parent.isWithincode(); } return false; } @Override public boolean isGet() { if (super.isGet()) { return true; } if (inheritsBindings) { return parent.isGet(); } return false; } @Override public boolean isSet() { if (super.isSet()) { return true; } if (inheritsBindings) { return parent.isSet(); } return false; } private Collection unifyCollections(Collection collection1, Collection collection2, boolean prioritizeFirst) { if (collection1.isEmpty()) { return collection2; } if (collection2.isEmpty()) { return collection1; } if (prioritizeFirst) { collection1 = new LinkedHashSet(collection1); collection1.addAll(collection2); } else { Collection temp = collection1; collection1 = new LinkedHashSet(collection2); collection1.addAll(temp); } return collection1; } private LinkedHashMap unifyMaps(LinkedHashMap map1, LinkedHashMap map2, boolean prioritizeFirst) { if (map1.isEmpty()) { return map2; } if (map2.isEmpty()) { return map1; } if (prioritizeFirst) { map1 = new LinkedHashMap(map1); map1.putAll(map2); } else { LinkedHashMap temp = map1; map1 = new LinkedHashMap(map2); map1.putAll(temp); } return map1; } } }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/0000755000175000017500000000000011145122064027030 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/MethodMapped.java0000644000175000017500000000251711145122054032246 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import java.util.Map; import org.jboss.aop.util.reference.MethodPersistentReference; /** * Comment * * @author Bill Burke * @version $Revision: 71276 $ */ public interface MethodMapped { public Map getMethodMap(); } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/MarshalledClassProxy.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/MarshalledClassProxy.j0000644000175000017500000000370311145122054033311 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import org.jboss.aop.InstanceAdvisor; import java.io.ObjectStreamException; import java.io.Serializable; /** * Comment * * @author Bill Burke * @version $Revision: 71276 $ */ public class MarshalledClassProxy implements Serializable { static final long serialVersionUID = 4049171769644464715L; private Class clazz; private ProxyMixin[] mixins; private InstanceAdvisor advisor; protected MarshalledClassProxy() { } public MarshalledClassProxy(Class clazz, ProxyMixin[] mixins, InstanceAdvisor advisor) { this.clazz = clazz; this.advisor = advisor; this.mixins = mixins; } public Object readResolve() throws ObjectStreamException { try { return ClassProxyFactory.newInstance(clazz, mixins, advisor); } catch (Exception e) { throw new RuntimeException(e); } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/0000755000175000017500000000000011145122066031014 5ustar twernertwerner././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ProxyTemplate.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ProxyTemplat0000644000175000017500000001237111145122060033405 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.io.ObjectStreamException; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.InstanceAdvisor; import org.jboss.aop.metadata.SimpleMetaData; /** * @author Bill Burke * @version $Revision: 71276 $ */ public class ProxyTemplate implements Delegate, AspectManaged { public ProxyTemplate() { } private transient Advisor classAdvisor; private transient InstanceAdvisor instanceAdvisor; protected volatile transient Advisor currentAdvisor; private Object delegate; private Object[] mixins; // Do not remove this private SimpleMetaData metadata; private ContainerProxyCacheKey key; public Object getDelegate() { return delegate; } public void setDelegate(Object delegate) { this.delegate = delegate; } public void setContainerProxyCacheKey(ContainerProxyCacheKey key) { this.key = key; } public Advisor getAdvisor() { return currentAdvisor; } public void setAdvisor(Advisor advisor) { this.classAdvisor = advisor; this.currentAdvisor = classAdvisor; } public void setMetadata(SimpleMetaData metadata) { this.metadata = metadata; } public void setInstanceAdvisor(InstanceAdvisor ia) { synchronized (this) { if (this.instanceAdvisor != null) { throw new RuntimeException("InstanceAdvisor already set"); } if (!(ia instanceof org.jboss.aop.proxy.container.InstanceProxyContainer)) { throw new RuntimeException("Wrong type for instance advisor: " + instanceAdvisor); } this.instanceAdvisor = ia; currentAdvisor = (org.jboss.aop.proxy.container.InstanceProxyContainer)ia; } } public InstanceAdvisor getInstanceAdvisor() { synchronized(this) { if (instanceAdvisor == null) { org.jboss.aop.proxy.container.InstanceProxyContainer ipc = ((org.jboss.aop.proxy.container.ClassProxyContainer)currentAdvisor).createInstanceProxyContainer(); setInstanceAdvisor(ipc); } } return instanceAdvisor; } public boolean equals(Object obj) { if (delegate != null) { if (obj != null && obj instanceof Delegate) obj = ((Delegate) obj).getDelegate(); return delegate.equals(obj); } else return super.equals(obj); } public int hashCode() { if (delegate != null) return delegate.hashCode(); else return super.hashCode(); } public String toString() { if (delegate != null) return delegate.toString() + " (proxied by " + this.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(this)) + ")"; else return super.toString() + "(empty proxy of " + this.getClass().getSuperclass().getName() + ")"; } private Object writeReplace() throws ObjectStreamException { return new MarshalledContainerProxy( this, this.key, this.mixins, this.delegate, this.currentAdvisor, this.metadata); } public void localUnmarshal(MarshalledContainerProxy proxy) { this.delegate = proxy.getDelegate(); this.mixins = proxy.getMixins(); this.metadata = proxy.getMetadata(); this.key = proxy.getKey(); this.classAdvisor = ContainerCache.getCachedContainer(this.key); this.currentAdvisor = classAdvisor; if (proxy.getInstanceAdvisorDomainName() != null) { ProxyAdvisorDomain domain = (ProxyAdvisorDomain)AspectManager.getTopLevelAspectManager().findManagerByName(proxy.getInstanceAdvisorDomainName()); this.currentAdvisor = domain.getAdvisor(); } } public void remoteUnmarshal(MarshalledContainerProxy proxy, MarshalledProxyAdvisor advisor) { this.delegate = proxy.getDelegate(); this.mixins = proxy.getMixins(); this.metadata = proxy.getMetadata(); this.key = proxy.getKey(); this.classAdvisor = advisor; this.currentAdvisor = advisor; this.instanceAdvisor = advisor; } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerProxyFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerPro0000644000175000017500000012672611145122064033356 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.io.Externalizable; import java.io.Serializable; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.Modifier; import javassist.NotFoundException; import javassist.SerialVersionUID; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.ParameterAnnotationsAttribute; import javassist.bytecode.SignatureAttribute; import javassist.bytecode.annotation.Annotation; import org.jboss.aop.Advised; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.ClassContainer; import org.jboss.aop.InstanceAdvised; import org.jboss.aop.MethodInfo; import org.jboss.aop.instrument.Instrumentor; import org.jboss.aop.instrument.TransformerCommon; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.util.JavassistMethodHashing; /** * @author Bill Burke * @version $Revision: 81449 $ */ public class ContainerProxyFactory { final static String DELEGATE = Delegate.class.getName(); final static String ASPECT_MANAGED = AspectManaged.class.getName(); @SuppressWarnings("unchecked") private static final HashMap EMPTY_HASHMAP = new HashMap(); private static final String ADVISED = Advised.class.getName(); private static final String INSTANCE_ADVISED = InstanceAdvised.class.getName(); private static final CtClass[] EMPTY_CTCLASS_ARRAY = new CtClass[0]; // private static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final String PROXY_NAME_PREFIX = "AOPContainerProxy$"; private static Object maplock = new Object(); private static WeakHashMap, Map>>>> proxyCache = new WeakHashMap, Map>>>>(); private static volatile int counter = 0; private static CtMethod setDelegateMethod; /** True if java.lang.Object should be used as the super class for this proxy */ private boolean objectAsSuper; /** The Advisor for this proxy */ private Advisor advisor; /** The class we are generating this proxy for */ private Class clazz; /** The generated proxy */ private CtClass proxy; /** The class pool for the proxy (i.e for the class we are proxying */ private ClassPool pool; /** True if we are proxying a class already woven by jboss aop, false otherwise */ private boolean isAdvised; ProxyStrategy proxyStrategy; private CtConstructor defaultCtor; /** Methods hardcoded in createBasics */ private HashSet hardcodedMethods = new HashSet(); public static Class getProxyClass(Class clazz, AspectManager manager) throws Exception { ContainerProxyCacheKey key = new ContainerProxyCacheKey(clazz); ClassContainer container = getTempClassContainer(clazz, manager); return getProxyClass(false, key, container); } public static Class getProxyClass(boolean objectAsSuper, ContainerProxyCacheKey key, Advisor advisor) throws Exception { return getProxyClass(objectAsSuper, key, advisor, null); } public static Class getProxyClass(boolean objectAsSuper, ContainerProxyCacheKey key, Advisor advisor, MarshalledContainerProxy outOfVmProxy) throws Exception { Class clazz = key.getClazz(); // Don't make a proxy of a proxy ! if (Delegate.class.isAssignableFrom(clazz)) clazz = clazz.getSuperclass(); ClassPool pool = AspectManager.instance().findClassPool(SecurityActions.getClassLoader(clazz)); if (pool == null) throw new NullPointerException("Could not find ClassPool"); Class proxyClass = null; synchronized (maplock) { WeakHashMap, Map>>> proxiesForLoader = proxyCache.get(pool.getClassLoader()); if (proxiesForLoader == null) { proxiesForLoader = new WeakHashMap, Map>>>(); proxyCache.put(pool.getClassLoader(), proxiesForLoader); } Map>> map = proxiesForLoader.get(clazz); if (map == null) { map = new HashMap>>(); proxiesForLoader.put(clazz, map); } else { WeakReference> proxyClassRef = map.get(key); if (proxyClassRef != null) { proxyClass = proxyClassRef.get(); } } if (proxyClass == null) { proxyClass = generateProxy(objectAsSuper, clazz, advisor, outOfVmProxy); map.put(key, new WeakReference>(proxyClass)); } } return proxyClass; } private static Class generateProxy(boolean objectAsSuper, Class clazz, Advisor advisor, MarshalledContainerProxy outOfVmProxy) throws Exception { ArrayList introductions = advisor.getInterfaceIntroductions(); CtClass proxy = createProxyCtClass(objectAsSuper, introductions, clazz, advisor, outOfVmProxy); // ClassLoader loader = determineClassLoaderToUse(clazz, proxy); ProtectionDomain pd = clazz.getProtectionDomain(); Class proxyClass = TransformerCommon.toClass(proxy, /*loader,*/ pd); return proxyClass; } private static ClassProxyContainer getTempClassContainer(Class clazz, AspectManager manager) { ClassProxyContainer container = new ClassProxyContainer("temp", manager); container.setClass(clazz); for (InterfaceIntroduction intro : container.getManager().getInterfaceIntroductions().values()) { if (intro.matches(container, container.getClazz())) { container.addInterfaceIntroduction(intro); } } return container; } @SuppressWarnings("unused") private static CtClass createProxyCtClass(boolean objectAsSuper, ArrayList mixins, Class clazz, Advisor advisor) throws Exception { return createProxyCtClass(objectAsSuper, mixins, clazz, advisor, null); } private static CtClass createProxyCtClass(boolean objectAsSuper, ArrayList mixins, Class clazz, Advisor advisor, MarshalledContainerProxy outOfVmProxy) throws Exception { ContainerProxyFactory factory = new ContainerProxyFactory(objectAsSuper, mixins, clazz, advisor, outOfVmProxy); return factory.createProxyCtClass(); } private ContainerProxyFactory(boolean objectAsSuper, ArrayList mixins, Class clazz, Advisor advisor, MarshalledContainerProxy outOfVmProxy) { this.objectAsSuper = objectAsSuper; this.clazz = clazz; this.advisor = advisor; isAdvised = Advised.class.isAssignableFrom(clazz); if (outOfVmProxy == null) { proxyStrategy = new OriginalProxyStrategy(mixins); } else { proxyStrategy = new UnmarshalledInRemoteJVMProxyStrategy(outOfVmProxy); } } private CtClass createProxyCtClass() throws Exception { this.pool = AspectManager.instance().findClassPool(clazz); if (pool == null) throw new NullPointerException("Could not find ClassPool"); createBasics(); addMethodsAndMixins(); overrideSpecialMethods(clazz, proxy); SerialVersionUID.setSerialVersionUID(proxy); return proxy; } private CtClass createBasics() throws Exception { Class proxySuper = (objectAsSuper) ? Object.class : this.clazz; String classname = getClassName(); CtClass template = pool.get("org.jboss.aop.proxy.container.ProxyTemplate"); CtClass superclass = pool.get(proxySuper.getName()); this.proxy = TransformerCommon.makeClass(pool, classname, superclass); proxy.addInterface(pool.get("org.jboss.aop.instrument.Untransformable")); //Add all the interfaces of the class Class[] interfaces = proxySuper.getInterfaces(); for (int i = 0 ; i < interfaces.length ; i++) { CtClass interfaze = pool.get(interfaces[i].getName()); proxy.addInterface(interfaze); } copyConstructors(superclass, proxy); addFieldFromTemplate(template, "mixins"); //Add methods/fields needed for Delegate interface proxy.addInterface(pool.get("org.jboss.aop.proxy.container.Delegate")); addFieldFromTemplate(template, "delegate", superclass); addMethodFromTemplate(template, "getDelegate", "{ return delegate; }"); setDelegateMethod = addMethodFromTemplate(template, "setDelegate", "{ this.delegate = (" + proxySuper.getName() + ")$1; }"); addFieldFromTemplate(template, "key"); addMethodFromTemplate(template, "setContainerProxyCacheKey", "{this.key=$1;}"); //Add methods/fields needed for AspectManaged interface proxy.addInterface(pool.get("org.jboss.aop.proxy.container.AspectManaged")); addFieldFromTemplate(template, "currentAdvisor"); addFieldFromTemplate(template, "classAdvisor"); addMethodFromTemplate(template, "getAdvisor", "{return classAdvisor;}"); addMethodFromTemplate(template, "setAdvisor", "{this.classAdvisor = $1;currentAdvisor = classAdvisor;}"); addFieldFromTemplate(template, "metadata"); addMethodFromTemplate(template, "setMetadata", "{this.metadata = $1;}"); addFieldFromTemplate(template, "instanceAdvisor"); addMethodFromTemplate(template, "setInstanceAdvisor", instanceAdvisorSetterBody()); addMethodFromTemplate(template, "getInstanceAdvisor", instanceAdvisorGetterBody()); addMethodFromTemplate(template, "writeReplace", writeReplaceObjectBody()); addMethodFromTemplate(template, "localUnmarshal", localUnmarshalObjectBody(superclass)); addMethodFromTemplate(template, "remoteUnmarshal", remoteUnmarshalObjectBody(superclass)); if (objectAsSuper) { addMethodFromTemplate(template, "equals", equalsBody()); addMethodFromTemplate(template, "hashCode", hashCodeBody()); } addMethodFromTemplate(template, "toString", toStringBody()); copyAnnotations(superclass, proxy); copySignature(superclass, proxy); return proxy; } private String instanceAdvisorSetterBody() { return "{" + " synchronized (this)" + " {" + " if (this.instanceAdvisor != null)" + " {" + " throw new RuntimeException(\"InstanceAdvisor already set\");" + " }" + " if (!($1 instanceof org.jboss.aop.proxy.container.InstanceProxyContainer))" + " {" + " throw new RuntimeException(\"Wrong type for instance advisor: \" + $1);" + " }" + " this.instanceAdvisor = $1;" + " currentAdvisor = (org.jboss.aop.proxy.container.InstanceProxyContainer)$1;" + " }" + "}"; } private String instanceAdvisorGetterBody() { return "{" + " synchronized(this)" + " {" + " if (instanceAdvisor == null)" + " {" + " org.jboss.aop.proxy.container.InstanceProxyContainer ipc = ((org.jboss.aop.proxy.container.ClassProxyContainer)currentAdvisor).createInstanceProxyContainer();" + " setInstanceAdvisor(ipc);" + " }" + " }" + " return instanceAdvisor;" + "}"; } private String writeReplaceObjectBody() { return "{" + " return new " + MarshalledContainerProxy.class.getName() + "(" + " this," + " this.key," + " this.mixins," + " this.delegate," + " this.currentAdvisor," + " this.metadata);" + "}"; } private String localUnmarshalObjectBody(CtClass superclass) { return "{" + // " try{" + " this.delegate = (" + superclass.getName() + ")$1.getDelegate();" + " this.mixins = $1.getMixins();" + " this.metadata = $1.getMetadata();" + " this.key = $1.getKey();" + " java.lang.Class clazz = $1.getClazz();" + " this.classAdvisor = org.jboss.aop.proxy.container.ContainerCache.getCachedContainer(this.key);" + " this.currentAdvisor = classAdvisor;" + " if ($1.getInstanceAdvisorDomainName() != null)" + " {" + " org.jboss.aop.proxy.container.ProxyAdvisorDomain domain = (org.jboss.aop.proxy.container.ProxyAdvisorDomain)org.jboss.aop.AspectManager.getTopLevelAspectManager().findManagerByName($1.getInstanceAdvisorDomainName());" + " this.currentAdvisor = domain.getAdvisor();" + " this.instanceAdvisor = this.currentAdvisor;" + " }" + // " }catch(java.lang.Exception e){throw e;}" + "}"; } private String remoteUnmarshalObjectBody(CtClass superclass) { return "{" + " this.delegate = (" + superclass.getName() + ")$1.getDelegate();" + " this.mixins = $1.getMixins();" + " this.metadata = $1.getMetadata();" + " this.key = $1.getKey();" + " java.lang.Class clazz = $1.getClazz();" + " this.classAdvisor = $2;" + " this.currentAdvisor = $2;" + " this.instanceAdvisor = $2;" + "}"; } private String equalsBody() { return "{" + " if (delegate != null)" + " {" + " if ($1 != null && $1 instanceof org.jboss.aop.proxy.container.Delegate)" + " $1 = ((org.jboss.aop.proxy.container.Delegate) $1).getDelegate();" + " return delegate.equals($1);" + " }" + " else" + " return super.equals($1);" + "}"; } private String hashCodeBody() { return "{" + " if (delegate != null)" + " return delegate.hashCode();" + " else" + " return super.hashCode();" + "}"; } private String toStringBody() { return "{" + " if (delegate != null)" + " return delegate.toString() + \" (proxied by \" + this.getClass().getName() + \"@\" + java.lang.Integer.toHexString(java.lang.System.identityHashCode(this)) + \")\";" + " else" + " return super.toString() + \" (empty proxy of \" + this.getClass().getSuperclass().getName() + \")\";" + "}"; } private CtField addFieldFromTemplate(CtClass template, String name) throws Exception { return addFieldFromTemplate(template, name, null); } private CtField addFieldFromTemplate(CtClass template, String name, CtClass type) throws Exception { CtField templateField = template.getField(name); CtClass fieldType = (type == null) ? templateField.getType() : type; CtField field = new CtField(fieldType, name, proxy); field.setModifiers(templateField.getModifiers()); Instrumentor.addSyntheticAttribute(field); proxy.addField(field); return field; } private CtMethod addMethodFromTemplate(CtClass template, String name, String body) throws Exception { CtMethod templateMethod = template.getDeclaredMethod(name); CtMethod method = CtNewMethod.make(templateMethod.getReturnType(), name, templateMethod.getParameterTypes(), templateMethod.getExceptionTypes(), body, proxy); method.setModifiers(templateMethod.getModifiers()); Instrumentor.addSyntheticAttribute(method); proxy.addMethod(method); hardcodedMethods.add(JavassistMethodHashing.methodHash(method)); return method; } private void copyConstructors(CtClass superclass, CtClass proxy) throws Exception { CtConstructor[] ctors = superclass.getConstructors(); int minParameters = Integer.MAX_VALUE; CtConstructor bestCtor = null; for (int i = 0 ; i < ctors.length ; i++) { CtClass[] params = ctors[i].getParameterTypes(); CtConstructor ctor = CtNewConstructor.make( ctors[i].getParameterTypes(), ctors[i].getExceptionTypes(), CtNewConstructor.PASS_PARAMS, null, null, proxy); ctor.setModifiers(ctors[i].getModifiers()); proxy.addConstructor(ctor); if (params.length < minParameters) { bestCtor = ctor; minParameters = params.length; } if (params.length == 0) { defaultCtor = ctor; } } if (minParameters > 0) { //We don't have a default constructor, we need to create one passing in null to the super ctor createDefaultConstructor(bestCtor); } } private void createDefaultConstructor(CtConstructor bestCtor) throws NotFoundException, CannotCompileException { CtClass params[] = bestCtor.getParameterTypes(); StringBuffer superCall = new StringBuffer("super("); for (int i = 0 ; i < params.length ; i++) { if (i > 0) { superCall.append(", "); } superCall.append(getNullType(params[i])); } superCall.append(");"); defaultCtor = CtNewConstructor.make(EMPTY_CTCLASS_ARRAY, EMPTY_CTCLASS_ARRAY, "{" + superCall.toString() + "}", proxy); Instrumentor.addSyntheticAttribute(defaultCtor); proxy.addConstructor(defaultCtor); } private String getNullType(CtClass clazz) { if (!clazz.isPrimitive()) { return "null"; } else { if (clazz.equals(CtClass.booleanType)) return "false"; else if (clazz.equals(CtClass.charType)) return "'0'"; else if (clazz.equals(CtClass.byteType)) return "0"; else if (clazz.equals(CtClass.shortType)) return "0"; else if (clazz.equals(CtClass.intType)) return "0"; else if (clazz.equals(CtClass.longType)) return "0L"; else if (clazz.equals(CtClass.floatType)) return "0f"; else if (clazz.equals(CtClass.doubleType)) return "0d"; else return "";//void } } private void addMethodsAndMixins()throws Exception { HashSet addedMethods = new HashSet(); createMixinsAndIntroductions(addedMethods); createProxyMethods(addedMethods); } private void createMixinsAndIntroductions(HashSet addedMethods) throws Exception { HashSet addedInterfaces = new HashSet(); Set implementedInterfaces = interfacesAsSet(); if (proxyStrategy.hasIntroductions()) { HashMap intfs = new HashMap(); HashMap mixinIntfs = new HashMap(); ArrayList mixes = new ArrayList(); proxyStrategy.getMixins(intfs, mixinIntfs, mixes); //Now that we have added the mixins, add all the proxies methods to the added methods set HashMap allMethods = JavassistMethodHashing.getDeclaredMethodMap(proxy); addedMethods.addAll(allMethods.keySet()); createMixins(addedMethods, mixes, addedInterfaces, implementedInterfaces); createIntroductions(addedMethods, intfs, addedInterfaces, implementedInterfaces); } } private void createMixins(HashSet addedMethods, ArrayList mixes, HashSet addedInterfaces, Set implementedInterfaces) throws Exception { for (int mixinId = 0 ; mixinId < mixes.size() ; mixinId++) { MixinInfo mixin = mixes.get(mixinId); String[] intfs = mixin.getInterfaces(); for (int ifId = 0 ; ifId < intfs.length ; ifId++) { String intf = intfs[ifId]; if (addedInterfaces.contains(intf)) throw new Exception("2 mixins are implementing the same interfaces " + intf); if (implementedInterfaces.contains(intf)) throw new Exception("Attempting to mixin interface already used by class " + intf); CtClass intfClass = pool.get(intf); CtMethod[] methods = intfClass.getMethods(); HashSet mixinMethods = new HashSet(); for (int m = 0; m < methods.length; m++) { if (methods[m].getDeclaringClass().getName().equals("java.lang.Object")) continue; Long hash = new Long(JavassistMethodHashing.methodHash(methods[m])); if (mixinMethods.contains(hash)) continue; if (addedMethods.contains(hash)) throw new Exception("More than one mixin has same method"); mixinMethods.add(hash); addedMethods.add(hash); String aopReturnStr = (methods[m].getReturnType().equals(CtClass.voidType)) ? "" : "return ($r)"; String returnStr = (methods[m].getReturnType().equals(CtClass.voidType)) ? "" : "return "; String args = "null"; if (methods[m].getParameterTypes().length > 0) args = "$args"; String code = "{ " + " try{" + " " + intf + " mixin = (" + intf + ")mixins[" + mixinId + "];" + " org.jboss.aop.MethodInfo mi = currentAdvisor.getMethodInfo(" + hash.longValue() + "L); " + " org.jboss.aop.advice.Interceptor[] interceptors = mi.getInterceptors();" + " if (mi != null && interceptors != (Object[])null && interceptors.length > 0) { " + " org.jboss.aop.proxy.container.ContainerProxyMethodInvocation invocation = new org.jboss.aop.proxy.container.ContainerProxyMethodInvocation(mi, interceptors, this); " + " invocation.setArguments(" + args + "); " + " invocation.setTargetObject(mixin); " + " invocation.setMetaData(metadata);" + " " + aopReturnStr + " invocation.invokeNext(); " + " } else { " + " " + returnStr + " mixin." + methods[m].getName() + "($$);" + " } " + " }finally{" + " }" + "}"; CtMethod newMethod = CtNewMethod.make(methods[m].getReturnType(), methods[m].getName(), methods[m].getParameterTypes(), methods[m].getExceptionTypes(), code, proxy); newMethod.setModifiers(Modifier.PUBLIC); proxy.addMethod(newMethod); copySignature(methods[m], newMethod); } proxy.addInterface(intfClass); addedInterfaces.add(intfClass.getName()); } } } private void createProxyMethods(HashSet addedMethods) throws Exception { HashMap allMethods = JavassistMethodHashing.getMethodMap(proxy.getSuperclass()); for (Map.Entry entry : allMethods.entrySet()) { CtMethod m = entry.getValue(); if (!Modifier.isPublic(m.getModifiers()) || Modifier.isStatic(m.getModifiers()) || Modifier.isFinal(m.getModifiers())) continue; Long hash = entry.getKey(); if (addedMethods.contains(hash)) continue; if (hardcodedMethods.contains(hash)) continue; addedMethods.add(hash); String aopReturnStr = (m.getReturnType().equals(CtClass.voidType)) ? "" : "return ($r)"; String returnStr = (m.getReturnType().equals(CtClass.voidType)) ? "" : "return "; String args = "null"; String name = null; if (isAdvised) { MethodInfo info = advisor.getMethodInfo(hash.longValue()); Method originalMethod = info.getUnadvisedMethod(); name = originalMethod.getName(); } else { name = m.getName(); } if (m.getParameterTypes().length > 0) args = "$args"; String code = "{ " + " boolean handled = false;" + " try{" + " if (currentAdvisor != null) {" + " org.jboss.aop.MethodInfo mi = currentAdvisor.getMethodInfo(" + hash.longValue() + "L); " + " if (mi == null) " + " throw new java.lang.NoSuchMethodError(\"" + m.getName() + m.getSignature() + "\");" + " org.jboss.aop.advice.Interceptor[] interceptors = mi.getInterceptors(); " + " if (interceptors != (Object[])null && interceptors.length > 0) { " + " handled = true;" + " org.jboss.aop.proxy.container.ContainerProxyMethodInvocation invocation = new org.jboss.aop.proxy.container.ContainerProxyMethodInvocation(mi, interceptors, this); " + " invocation.setArguments(" + args + "); " + " invocation.setTargetObject(delegate); " + " invocation.setMetaData(metadata);" + " " + aopReturnStr + " invocation.invokeNext(); " + " }" + " }" + " if (!handled && delegate != null){ " + " " + returnStr + " delegate." + name + "($$); " + " }" + " return " + getNullType(m.getReturnType()) + ";" + " }finally{" + " }" + "}"; CtMethod newMethod = CtNewMethod.make(m.getReturnType(), m.getName(), m.getParameterTypes(), m.getExceptionTypes(), code, proxy); newMethod.setModifiers(Modifier.PUBLIC); proxy.addMethod(newMethod); copyAnnotations(m, newMethod); copySignature(m, newMethod); } } private void createIntroductions(HashSet addedMethods, HashMap intfs, HashSet addedInterfaces, Set implementedInterfaces) throws Exception { for (String intf : intfs.keySet()) { if (addedInterfaces.contains(intf)) throw new Exception("2 mixins are implementing the same interfaces"); if (implementedInterfaces.contains(intf)) { continue; } CtClass intfClass = pool.get(intf); CtMethod[] methods = intfClass.getMethods(); HashSet mixinMethods = new HashSet(); for (int m = 0; m < methods.length; m++) { if (methods[m].getDeclaringClass().getName().equals("java.lang.Object")) continue; Long hash = new Long(JavassistMethodHashing.methodHash(methods[m])); if (mixinMethods.contains(hash)) continue; if (addedMethods.contains(hash)) continue; mixinMethods.add(hash); addedMethods.add(hash); String aopReturnStr = (methods[m].getReturnType().equals(CtClass.voidType)) ? "" : "return ($r)"; String args = "null"; if (methods[m].getParameterTypes().length > 0) args = "$args"; String code = "{ " + " try{" + " org.jboss.aop.MethodInfo mi = currentAdvisor.getMethodInfo(" + hash.longValue() + "L); " + " if (mi == null) " + " throw new java.lang.NoSuchMethodError(\"" + methods[m].getName() + methods[m].getSignature() + "\");" + " org.jboss.aop.advice.Interceptor[] interceptors = mi.getInterceptors();" + " org.jboss.aop.proxy.container.ContainerProxyMethodInvocation invocation = new org.jboss.aop.proxy.container.ContainerProxyMethodInvocation(mi, interceptors, this); " + " invocation.setArguments(" + args + "); " + " invocation.setTargetObject(delegate); " + " invocation.setMetaData(metadata);" + " " + aopReturnStr + " invocation.invokeNext(); " + " }finally{" + " }" + "}"; CtMethod newMethod = CtNewMethod.make(methods[m].getReturnType(), methods[m].getName(), methods[m].getParameterTypes(), methods[m].getExceptionTypes(), code, proxy); newMethod.setModifiers(Modifier.PUBLIC); proxy.addMethod(newMethod); copySignature(methods[m], newMethod); } proxy.addInterface(intfClass); addedInterfaces.add(intfClass.getName()); } } private Set interfacesAsSet() throws NotFoundException { HashSet set = new HashSet(); CtClass[] interfaces = proxy.getInterfaces(); for (int i = 0 ; i < interfaces.length ; i++) { set.add(interfaces[i].getName()); } return set; } private String getClassName() { String packageName = clazz.getPackage().getName(); if (!packageName.startsWith("java.") && !packageName.startsWith("sun.")) { packageName += "."; } else { packageName = ""; } return packageName + PROXY_NAME_PREFIX + counter++; } private void overrideSpecialMethods(Class clazz, CtClass proxy) throws Exception { addInstanceAdvisedMethods(clazz, proxy); } /** * If the class is Advised, the _getInstanceAdvisor() and _setInstanceAdvisor() methods will * not have been overridden. Make sure that these methods work with the instance proxy container. */ private void addInstanceAdvisedMethods(Class clazz, CtClass proxy) throws Exception { CtClass advisedInterface = null; CtClass interfaces[] = proxy.getInterfaces(); for (int i = 0 ; i < interfaces.length ; i++) { if (interfaces[i].getName().equals(ADVISED)) { advisedInterface = interfaces[i]; break; } } if (advisedInterface != null) { CtMethod[] methods = advisedInterface.getMethods(); for (int i = 0 ; i < methods.length ; i++) { if (methods[i].getDeclaringClass().getName().equals(INSTANCE_ADVISED)) { String name = methods[i].getName(); String body = null; if (name.equals("_getInstanceAdvisor")) { body = "{ return getInstanceAdvisor(); }"; } else if (name.equals("_setInstanceAdvisor")) { body = "{ setInstanceAdvisor($1); }"; } if (body != null) { CtMethod m = CtNewMethod.make(methods[i].getReturnType(), methods[i].getName(), methods[i].getParameterTypes(), methods[i].getExceptionTypes(), body, proxy); m.setModifiers(Modifier.PUBLIC); Instrumentor.addSyntheticAttribute(m); proxy.addMethod(m); } } } } } private void copyAnnotations(CtMethod src, CtMethod dest) throws NotFoundException { javassist.bytecode.MethodInfo srcInfo = src.getMethodInfo2(); javassist.bytecode.MethodInfo destInfo = dest.getMethodInfo2(); copyAnnotations(srcInfo, destInfo, AnnotationsAttribute.invisibleTag); copyAnnotations(srcInfo, destInfo, AnnotationsAttribute.visibleTag); int numParams = src.getParameterTypes().length; copyParameterAnnotations(numParams, srcInfo, destInfo, ParameterAnnotationsAttribute.visibleTag); copyParameterAnnotations(numParams, srcInfo, destInfo, ParameterAnnotationsAttribute.invisibleTag); } private void copyAnnotations(javassist.bytecode.MethodInfo src, javassist.bytecode.MethodInfo dest, String annotationTag) { AnnotationsAttribute attribute = (AnnotationsAttribute) src.getAttribute(annotationTag); if (attribute != null) { dest.addAttribute(attribute.copy(dest.getConstPool(), EMPTY_HASHMAP)); } } private void copyParameterAnnotations(int numParams, javassist.bytecode.MethodInfo src, javassist.bytecode.MethodInfo dest, String paramsTag) { ParameterAnnotationsAttribute params = (ParameterAnnotationsAttribute)src.getAttribute(paramsTag); if (params != null) { dest.addAttribute(params.copy(dest.getConstPool(), EMPTY_HASHMAP)); ParameterAnnotationsAttribute srcParams = new ParameterAnnotationsAttribute(src.getConstPool(), paramsTag); Annotation[][] emptyParamAnnotations = new Annotation[numParams][]; for (int i = 0 ; i < numParams ; i++) { emptyParamAnnotations[i] = new Annotation[0]; } srcParams.setAnnotations(emptyParamAnnotations); src.addAttribute(srcParams); } } private void copyAnnotations(CtClass src, CtClass dest) throws NotFoundException { ClassFile srcFile = src.getClassFile2(); ClassFile destFile = dest.getClassFile2(); copyAnnotations(srcFile, destFile, AnnotationsAttribute.invisibleTag); copyAnnotations(srcFile, destFile, AnnotationsAttribute.visibleTag); } private void copyAnnotations(ClassFile src, ClassFile dest, String annotationTag) { AnnotationsAttribute attribute = (AnnotationsAttribute) src.getAttribute(annotationTag); if (attribute != null) { dest.addAttribute(attribute.copy(dest.getConstPool(), EMPTY_HASHMAP)); } } private void copySignature(CtMethod src, CtMethod dest) { javassist.bytecode.MethodInfo srcInfo = src.getMethodInfo2(); javassist.bytecode.MethodInfo destInfo = dest.getMethodInfo2(); SignatureAttribute sig = (SignatureAttribute)srcInfo.getAttribute(SignatureAttribute.tag); if (sig != null) { destInfo.addAttribute(sig.copy(destInfo.getConstPool(), EMPTY_HASHMAP)); } } private void copySignature(CtClass src, CtClass dest) { ClassFile srcFile = src.getClassFile2(); ClassFile destFile = dest.getClassFile2(); SignatureAttribute sig = (SignatureAttribute)srcFile.getAttribute(SignatureAttribute.tag); if (sig != null) { destFile.addAttribute(sig.copy(destFile.getConstPool(), EMPTY_HASHMAP)); } } private interface ProxyStrategy { /** * Whether the proxy has introductions and/or mixins * @return true if we have introductions and/or mixins */ boolean hasIntroductions(); /** * @param intfs receives the interfaces from plain interface introductions * @param mixinInterfaces receives the interfaces from mixins * @param mixes receives the actual InterfaceIntroduction.Mixin objects */ void getMixins(HashMap intfs, HashMap mixins, ArrayList mixes) throws Exception; } private class OriginalProxyStrategy implements ProxyStrategy { ArrayList mixins; OriginalProxyStrategy(ArrayList mixins) { this.mixins = mixins; } public boolean hasIntroductions() { if (mixins == null) { return false; } return mixins.size() > 0; } public void getMixins(HashMap intfs, HashMap mixinInterfaces, ArrayList mixes) throws Exception { if (mixins != null) { HashMap mixinIntfs = new HashMap(); for (int i = 0; i < mixins.size(); i++) { InterfaceIntroduction introduction = mixins.get(i); getIntroductionInterfaces(introduction, intfs, mixinIntfs, mixes, i); } if (mixes.size() > 0) { defaultCtor.insertAfter("mixins = new Object[" + mixes.size() + "];"); for (int i = 0; i < mixes.size(); i++) { //If using a constructor and passing "this" as the parameters, the proxy gets used. The delegate (instance wrapped by proxy) is not //set in the proxy until later, and if the mixin implements Delegate it will get set with the "real" instance at this point. MixinInfo mixin = mixes.get(i); String initializer = (mixin.getConstruction() == null) ? ("new " + mixin.getClassName() + "()") : mixin.getConstruction(); String code = "mixins[" + i + "] = " + initializer + ";"; defaultCtor.insertAfter(code); setDelegateMethod.insertAfter("{if (org.jboss.aop.proxy.container.Delegate.class.isAssignableFrom(mixins[" + i + "].getClass())) " + "((org.jboss.aop.proxy.container.Delegate)mixins[" + i + "]).setDelegate($1);}"); } } } } /** * Split the interface introduction into something we can work with * * @param intro The InterfaceIntroduction * @param intfs receives the interfaces from plain interface introductions * @param mixinInterfaces receives the interfaces from mixins * @param mixes receives the actual InterfaceIntroduction.Mixin objects * @@param the index interface introduction this data comes from */ private void getIntroductionInterfaces(InterfaceIntroduction intro, HashMap intfs, HashMap mixinInterfaces, ArrayList mixes, int idx) { for (InterfaceIntroduction.Mixin mixin : intro.getMixins()) { mixes.add(new MixinInfo(mixin)); for (int i = 0; i < mixin.getInterfaces().length; i++) { if (intfs.containsKey(mixin.getInterfaces()[i])) { intfs.remove(mixin.getInterfaces()[i]); } if (mixinInterfaces.containsKey(mixin.getInterfaces()[i])) { throw new RuntimeException("cannot have an IntroductionInterface that introduces several mixins with the same interfaces " + mixin.getInterfaces()[i]); } mixinInterfaces.put(mixin.getInterfaces()[i], new Integer(idx)); } } if (intro.getInterfaces() != null) { for (int i = 0; i < intro.getInterfaces().length; i++) { if (intfs.containsKey(intro.getInterfaces()[i]) || mixinInterfaces.containsKey(intro.getInterfaces()[i])) { //Do nothing } else { intfs.put(intro.getInterfaces()[i], new Integer(idx)); } } } } } private class UnmarshalledInRemoteJVMProxyStrategy implements ProxyStrategy { MarshalledContainerProxy outOfVmProxy; UnmarshalledInRemoteJVMProxyStrategy(MarshalledContainerProxy outOfVmProxy) { this.outOfVmProxy = outOfVmProxy; } public boolean hasIntroductions() { if (outOfVmProxy == null) { return false; } return outOfVmProxy.getIntroducedInterfaces().length > 0; } public void getMixins(HashMap intfs, HashMap mixinInterfaces, ArrayList mixes) throws Exception { HashSet allInterfaces = new HashSet(); String[] introducedInterfaces = outOfVmProxy.getIntroducedInterfaces(); allInterfaces.addAll(Arrays.asList(introducedInterfaces)); Set targetInterfaces = outOfVmProxy.getTargetInterfaces(); Object[] mixins = outOfVmProxy.getMixins(); int i = 0; for ( ; i < mixins.length ; i++) { Class clazz = mixins[i].getClass(); Class[] ifs = clazz.getInterfaces(); ArrayList interfaces = new ArrayList(ifs.length); for (Class iface : ifs) { String name = iface.getName(); if (name.equals(Serializable.class.getName()) || name.equals(Externalizable.class.getName()) || targetInterfaces.contains(name)) { continue; } interfaces.add(name); allInterfaces.remove(name); mixinInterfaces.put(name, i); } MixinInfo info = new MixinInfo(clazz.getName(), interfaces); mixes.add(info); } for (String iface : allInterfaces) { intfs.put(iface, ++i); } } } private static class MixinInfo { String[] interfaces; String className; String construction; MixinInfo(InterfaceIntroduction.Mixin mixin) { this.interfaces = mixin.getInterfaces(); this.className = mixin.getClassName(); this.construction = mixin.getConstruction(); } MixinInfo(String className, ArrayList interfaces) { this.className = className; this.interfaces = interfaces.toArray(new String[interfaces.size()]); } protected String[] getInterfaces() { return interfaces; } protected String getClassName() { return className; } protected String getConstruction() { return construction; } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerCacheUtil.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerCac0000644000175000017500000000646211145122066033300 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Comparator; /** * * @author Kabir Khan * @version $Revision: 70849 $ */ public class ContainerCacheUtil { /** * Takes a Class[] containing interface classes, and returns an array of weak references to thos class * objects, sorted alphabetically by name. */ public static WeakReference>[] getSortedWeakReferenceForInterfaces(Class[] ifaces) { if (ifaces == null) { return null; } WeakReference>[] interfaces = new WeakReference[ifaces.length]; for (int i = 0 ; i < ifaces.length ; i++) { interfaces[i] = new WeakReference>(ifaces[i]); } Arrays.sort(interfaces, Alphabetical.singleton); return interfaces; } public static boolean compareClassRefs(WeakReference> my, WeakReference> other) { Class myClass = my.get(); Class otherClass = other.get(); if (myClass == null || otherClass == null) { return false; } if (!myClass.equals(otherClass)) { return false; } return true; } public static boolean compareInterfaceRefs(WeakReference>[] my, WeakReference>[] other) { if ((my == null && other != null) || (my == null && other != null)) { return false; } if (my != null && my != null) { if (my.length != other.length) { return false; } for (int i = 0 ; i < my.length ; i++) { Class myIf = my[i].get(); Class otherIf = other[i].get(); if (!myIf.equals(otherIf)) { return false; } } } return true; } static class Alphabetical implements Comparator>> { static Alphabetical singleton = new Alphabetical(); public int compare(WeakReference> o1, WeakReference> o2) { String name1 = o1.get().getName(); String name2 = o2.get().getName(); return (name1).compareTo(name2); } } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerProxyMethodInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerPro0000644000175000017500000000353611145122054033346 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import org.jboss.aop.MethodInfo; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.joinpoint.MethodInvocation; /** * MethodInvocation allowing storage of the generated proxy * * @author Kabir Khan * @version $Revision: 44253 $ */ public class ContainerProxyMethodInvocation extends MethodInvocation { AspectManaged proxy; static final Object[] NO_ARGS = new Object[0]; public ContainerProxyMethodInvocation(MethodInfo info, Interceptor[] interceptors, AspectManaged proxy) { super(info, interceptors); this.proxy = proxy; } public AspectManaged getProxy() { return proxy; } public Object[] getArguments() { Object[] args = super.getArguments(); if (args != null) { return args; } return NO_ARGS; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/MarshalledProxyAdvisor.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/MarshalledPr0000644000175000017500000001270111145122064033314 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import gnu.trove.TLongObjectHashMap; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.Domain; import org.jboss.aop.InstanceAdvisor; import org.jboss.aop.MethodInfo; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.joinpoint.Joinpoint; import org.jboss.aop.metadata.ClassMetaDataBinding; import org.jboss.aop.metadata.SimpleMetaData; /** * The advisor used by a container proxy that is unmarshalled in a remote jvm * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class MarshalledProxyAdvisor extends Advisor implements InstanceAdvisor { TLongObjectHashMap methodInfos = new TLongObjectHashMap(); Object instance; public MarshalledProxyAdvisor(String name, AspectManager manager) { super(name, manager); } public void setClazz(Class clazz) { super.clazz = clazz; } public void addMethodInfo(MethodInfo info) { methodInfos.put(info.getHash(), info); } public void setInstance(Object instance) { this.instance = instance; } @Override public void addClassMetaData(ClassMetaDataBinding data) { throw new RuntimeException("Not yet implemented"); } @Override protected void rebuildInterceptors() { //Noop, all interceptors are added via addMethodInfo } @Override protected void rebuildInterceptorsForAddedBinding(AdviceBinding binding) { //Noop, all interceptors are added via addMethodInfo } @Override protected void rebuildInterceptorsForRemovedBinding(AdviceBinding removedBinding) { //Noop, all interceptors are added via addMethodInfo } @Override public void removeClassMetaData(ClassMetaDataBinding data) { throw new RuntimeException("Not yet implemented"); } @Override public MethodInfo getMethodInfo(long hash) { MethodInfo info = (MethodInfo)methodInfos.get(hash); return info; } public MethodInfo[] getMethodInfos() { Object[] vals = methodInfos.getValues(); MethodInfo[] infos = new MethodInfo[vals.length]; System.arraycopy(vals, 0, infos, 0, vals.length); return infos; } public void appendInterceptor(Interceptor interceptor) { throw new RuntimeException("Not yet implemented"); } public void appendInterceptor(int index, Interceptor interceptor) throws IndexOutOfBoundsException { throw new RuntimeException("Not yet implemented"); } public void appendInterceptorStack(String stackName) { throw new RuntimeException("Not yet implemented"); } public Domain getDomain() { return null; } public Object getInstance() { return instance; } public Interceptor[] getInterceptors() { throw new RuntimeException("Not yet implemented"); } public Interceptor[] getInterceptors(Interceptor[] baseChain) { throw new RuntimeException("Not yet implemented"); } public SimpleMetaData getMetaData() { return null; } public Object getPerInstanceAspect(String aspectName) { throw new RuntimeException("Not yet implemented"); } public Object getPerInstanceAspect(AspectDefinition def) { throw new RuntimeException("Not yet implemented"); } public Object getPerInstanceJoinpointAspect(Joinpoint joinpoint, AspectDefinition def) { throw new RuntimeException("Not yet implemented"); } public boolean hasInterceptors() { return false; } public void insertInterceptor(Interceptor interceptor) { throw new RuntimeException("Not yet implemented"); } public void insertInterceptor(int index, Interceptor interceptor) throws IndexOutOfBoundsException { throw new RuntimeException("Not yet implemented"); } public void insertInterceptorStack(String stackName) { throw new RuntimeException("Not yet implemented"); } public void removeInterceptor(String name) { throw new RuntimeException("Not yet implemented"); } public void removeInterceptorStack(String name) { throw new RuntimeException("Not yet implemented"); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/SecurityActions.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/SecurityActi0000644000175000017500000000556011145122054033352 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.security.AccessController; import java.security.PrivilegedAction; /** * SecurityActions. * * @author Adrian Brock * @version $Revision: 1.1 $ */ class SecurityActions { static class GetContextClassLoaderAction implements PrivilegedAction { public static GetContextClassLoaderAction INSTANCE = new GetContextClassLoaderAction(); public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } } static ClassLoader getContextClassLoader() { if (System.getSecurityManager() == null) return Thread.currentThread().getContextClassLoader(); else return AccessController.doPrivileged(GetContextClassLoaderAction.INSTANCE); } interface GetClassLoaderAction { ClassLoader getClassLoader(Class clazz); GetClassLoaderAction NON_PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(Class clazz) { return clazz.getClassLoader(); }}; GetClassLoaderAction PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction() { public ClassLoader run() { return clazz.getClassLoader(); }}); }}; } static ClassLoader getClassLoader(Class clazz) { if (System.getSecurityManager() == null) { return GetClassLoaderAction.NON_PRIVILEGED.getClassLoader(clazz); } else { return GetClassLoaderAction.PRIVILEGED.getClassLoader(clazz); } } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AOPProxyFactoryParameters.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AOPProxyFact0000644000175000017500000001227611145122066033226 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import org.jboss.aop.metadata.SimpleMetaData; import org.jboss.metadata.spi.MetaData; /** * * @author Kabir Khan * @version $Revision: 70849 $ */ public class AOPProxyFactoryParameters { private Class proxiedClass; private Object target; private MetaData metaData; private boolean metaDataHasInstanceLevelData; private Class[] interfaces; private AOPProxyFactoryMixin[] mixins; private boolean objectAsSuperClass; private SimpleMetaData simpleMetaData; private ContainerCache containerCache; private Ctor ctor; public AOPProxyFactoryParameters() { } public AOPProxyFactoryParameters( Class proxiedClass, Object target, Class[] interfaces, AOPProxyFactoryMixin[] mixins, MetaData metaData, boolean metaDataHasInstanceLevelData, boolean objectAsSuperClass, SimpleMetaData simpleMetaData, ContainerCache containerCache, Class[] ctorSignature, Object[] ctorArguments) { this.proxiedClass = proxiedClass; this.target = target; this.interfaces = interfaces; this.mixins = mixins; this.metaData = metaData; this.metaDataHasInstanceLevelData = metaDataHasInstanceLevelData; this.objectAsSuperClass = objectAsSuperClass; this.simpleMetaData = simpleMetaData; this.containerCache = containerCache; setCtor(ctorSignature, ctorArguments); } public Class[] getInterfaces() { return interfaces; } public void setInterfaces(Class[] interfaces) { this.interfaces = interfaces; } public MetaData getMetaData() { return metaData; } public void setMetaData(MetaData metaData) { this.metaData = metaData; } public boolean isObjectAsSuperClass() { return objectAsSuperClass; } public void setObjectAsSuperClass(boolean objectAsSuperClass) { this.objectAsSuperClass = objectAsSuperClass; } public Class getProxiedClass() { return proxiedClass; } public void setProxiedClass(Class proxiedClass) { this.proxiedClass = proxiedClass; } public SimpleMetaData getSimpleMetaData() { return simpleMetaData; } public void setSimpleMetaData(SimpleMetaData simpleMetaData) { this.simpleMetaData = simpleMetaData; } public Object getTarget() { return target; } public void setTarget(Object target) { this.target = target; } public AOPProxyFactoryMixin[] getMixins() { return mixins; } public void setMixins(AOPProxyFactoryMixin[] mixins) { this.mixins = mixins; } public ContainerCache getContainerCache() { return containerCache; } public void setContainerCache(ContainerCache containerCache) { this.containerCache = containerCache; } public Ctor getCtor() { return ctor; } public boolean getMetaDataHasInstanceLevelData() { return metaDataHasInstanceLevelData; } public void setMetaDataHasInstanceLevelData(boolean metaDataHasInstanceLevelData) { this.metaDataHasInstanceLevelData = metaDataHasInstanceLevelData; } public void setCtor(Class[] ctorSignature, Object[] ctorArguments) { boolean haveSig = (ctorSignature != null && ctorSignature.length > 0); boolean haveArgs = (ctorArguments != null && ctorArguments.length > 0); if (haveSig && haveArgs) { ctor = new Ctor(ctorSignature, ctorArguments); } else if (!haveSig && !haveArgs) { ctor = null; } else { throw new RuntimeException("If specifying either constructor arguments or signature, you must specify the other"); } } public static class Ctor { Class[] signature; Object[] arguments; public Ctor(Class[] signature, Object[] arguments) { this.signature = signature; this.arguments = arguments; } public Object[] getArguments() { return arguments; } public Class[] getSignature() { return signature; } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AOPProxyFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AOPProxyFact0000644000175000017500000000233311145122054033214 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; /** * * @author Kabir Khan * @version $Revision: 42108 $ */ public interface AOPProxyFactory { public Object createAdvisedProxy(AOPProxyFactoryParameters params); } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/InstanceProxyContainer.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/InstanceProx0000644000175000017500000001515011145122060033350 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import org.jboss.aop.Advisor; import org.jboss.aop.ClassAdvisor; import org.jboss.aop.Domain; import org.jboss.aop.InstanceAdvisor; import org.jboss.aop.InstanceAdvisorDelegate; import org.jboss.aop.MethodInfo; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.joinpoint.Joinpoint; import org.jboss.aop.metadata.SimpleMetaData; import org.jboss.metadata.spi.MetaData; /** * The InstanceAdvisor returned by ClassProxyContainer * * @author Kabir Khan * @version $Revision: 73394 $ */ public class InstanceProxyContainer extends ClassProxyContainer implements InstanceAdvisor { Advisor classAdvisor; InstanceAdvisorDelegate delegate; public InstanceProxyContainer(String name, ProxyAdvisorDomain instanceDomain, Advisor classAdvisor, MetaData metaData) { super(name, instanceDomain); this.classAdvisor = classAdvisor; instanceDomain.setAdvisor(this); setMetadata(metaData); delegate = new InstanceAdvisorDelegate(classAdvisor, this); delegate.initialize(); initialise(classAdvisor.getClazz()); } public static InstanceProxyContainer createInstanceProxyContainer(Advisor classAdvisor, InterfaceIntroduction introduction, MetaData metaData) { String name = Domain.getDomainName(classAdvisor.getClazz(), true); ProxyAdvisorDomain domain = new ProxyAdvisorDomain(classAdvisor.getManager(), name, classAdvisor.getClazz(), true); if (introduction != null) { domain.addInterfaceIntroduction(introduction); } InstanceProxyContainer ia = new InstanceProxyContainer(classAdvisor.getName(), domain, classAdvisor, metaData); return ia; } public Advisor getClassAdvisor() { return classAdvisor; } public Object getPerInstanceAspect(String aspectName) { return delegate.getPerInstanceAspect(aspectName); } public Object getPerInstanceAspect(AspectDefinition def) { return delegate.getPerInstanceAspect(def); } public Object getPerInstanceJoinpointAspect(Joinpoint joinpoint, AspectDefinition def) { return delegate.getPerInstanceJoinpointAspect(joinpoint, def); } public SimpleMetaData getMetaData() { return delegate.getMetaData(); } public Domain getDomain() { return (Domain)super.getManager(); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public boolean hasInterceptors() { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public Interceptor[] getInterceptors() { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public Interceptor[] getInterceptors(Interceptor[] baseChain) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void insertInterceptor(Interceptor interceptor) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void removeInterceptor(String name) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void appendInterceptor(Interceptor interceptor) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void insertInterceptorStack(String stackName) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void removeInterceptorStack(String name) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void appendInterceptorStack(String stackName) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void insertInterceptor(int index, Interceptor interceptor) { throw new RuntimeException("Not implemented"); } /** * Not implemented InstanceAdvisor method, we should be using the domain */ public void appendInterceptor(int index, Interceptor interceptor) { throw new RuntimeException("Not implemented"); } public void removeFromDomain() { ProxyAdvisorDomain domain = (ProxyAdvisorDomain)super.manager; domain.removeAdvisor(this); } public Object getInstance() { throw new RuntimeException("Not implemented"); } /** * If the target instance is advised, make sure that we set the unadvised method to the one stored by the class advisor * so that we don't get double invocations. */ @Override public MethodInfo getMethodInfo(long hash) { MethodInfo info = super.getMethodInfo(hash); if (classAdvisor instanceof ClassAdvisor && info.getMethod().equals(info.getUnadvisedMethod())) { MethodInfo superInfo = classAdvisor.getMethodInfo(hash); if (superInfo != null) { info.setUnadvisedMethod(superInfo.getUnadvisedMethod()); } } return info; } @Override protected Advisor getParentAdvisor() { return classAdvisor; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerCache.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerCac0000644000175000017500000002417011145122056033273 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.util.HashMap; import java.util.WeakHashMap; import org.jboss.aop.Advised; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.Domain; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.metadata.SimpleMetaData; import org.jboss.metadata.spi.MetaData; /** * * @author Kabir Khan * @version $Revision: 75539 $ */ public class ContainerCache { private static volatile int counter; public static final Object mapLock = new Object(); private static WeakHashMap, HashMap> containerCache = new WeakHashMap, HashMap>(); private AspectManager manager; private ContainerProxyCacheKey key; /** This will be ClassAdvisor if class has been woven i.e implements Advised, or ClassProxyContainer*/ private Advisor classAdvisor; private InstanceProxyContainer instanceContainer; boolean isClassProxyContainer; Class[] interfaces; AOPProxyFactoryMixin[] mixins; MetaData metaData; boolean metaDataHasInstanceLevelData; SimpleMetaData simpleMetaData; private ContainerCache(AspectManager manager, Class proxiedClass, Class[] interfaces, AOPProxyFactoryMixin[] mixins, MetaData metaData, boolean metaDataHasInstanceLevelData, SimpleMetaData simpleMetaData) { this.manager = manager; this.interfaces = interfaces; this.mixins = mixins; this.metaData = metaData; this.simpleMetaData = simpleMetaData; this.metaDataHasInstanceLevelData = metaDataHasInstanceLevelData; key = new ContainerProxyCacheKey(manager.getManagerFQN(), proxiedClass, interfaces, mixins, metaData); } public static ContainerCache initialise(AspectManager manager, Class proxiedClass, MetaData metaData, boolean metaDataHasInstanceLevelData) { return initialise(manager, proxiedClass, null, null, metaData, metaDataHasInstanceLevelData, null); } public static ContainerCache initialise(AspectManager manager, AOPProxyFactoryParameters params) { return initialise( manager, params.getProxiedClass(), params.getInterfaces(), params.getMixins(), params.getMetaData(), params.getMetaDataHasInstanceLevelData(), params.getSimpleMetaData()); } private static ContainerCache initialise(AspectManager manager, Class proxiedClass, Class[] interfaces, AOPProxyFactoryMixin[] mixins, MetaData metaData, boolean metaDataHasInstanceLevelData, SimpleMetaData simpleMetaData) { ContainerCache factory = new ContainerCache(manager, proxiedClass, interfaces, mixins, metaData, metaDataHasInstanceLevelData, simpleMetaData); synchronized (mapLock) { factory.initClassContainer(); factory.initInstanceContainer(); } return factory; } public ContainerProxyCacheKey getKey() { return key; } public Advisor getAdvisor() { return (instanceContainer != null) ? instanceContainer : classAdvisor; } public Advisor getClassAdvisor() { return classAdvisor; } public InstanceProxyContainer getInstanceContainer() { return instanceContainer; } public boolean hasAspects() { if (instanceContainer != null) { return instanceContainer.hasAspects(); } return classAdvisor.hasAspects(); } public boolean hasIntroductionsForClassAdvisor() { return classAdvisor.getInterfaceIntroductions().size() > 0; } public boolean requiresInstanceAdvisor() { return hasInterfaceIntroductions() || hasMixins() || (metaData!= null && metaDataHasInstanceLevelData) || simpleMetaData != null; } public boolean isAdvised() { return Advised.class.isAssignableFrom(key.getClazz()); } private boolean hasInterfaceIntroductions() { return interfaces != null && interfaces.length > 0; } private boolean hasMixins() { return mixins != null && mixins.length > 0; } private void initClassContainer() { if (Advised.class.isAssignableFrom(key.getClazz())) { classAdvisor = AspectManager.instance().getAdvisor(key.getClazz()); } else { classAdvisor = getCachedContainer(manager); if (classAdvisor == null) { classAdvisor = createAndCacheContainer(); } } } public static ClassProxyContainer getCachedContainer(ContainerProxyCacheKey key) { HashMap managerContainers = containerCache.get(key.getClazz()); if (managerContainers != null) { return managerContainers.get(key.getManagerFQN()); } return null; } private ClassProxyContainer getCachedContainer(AspectManager manager) { HashMap managerContainers = containerCache.get(key.getClazz()); if (managerContainers != null) { return managerContainers.get(manager.getManagerFQN()); } return null; } private ClassProxyContainer createAndCacheContainer() { ClassProxyContainer container = createContainer(); cacheContainer(key, container); return container; } private ClassProxyContainer createContainer() { String name = Domain.getDomainName(key.getClazz(), false); ProxyAdvisorDomain domain = new ProxyAdvisorDomain(manager, name, key.getClazz(), false); String classname = (key.getClazz() != null) ? key.getClazz().getName() : "AOP$Hollow"; ClassProxyContainer container = new ClassProxyContainer(classname /*+ " ClassProxy" + (counter++)*/, domain); domain.setAdvisor(container); container.initialise(key.getClazz()); return container; } private void cacheContainer(ContainerProxyCacheKey key, ClassProxyContainer container) { HashMap managerContainers = containerCache.get(key.getClazz()); if (managerContainers == null) { managerContainers = new HashMap(); containerCache.put(key.getClazz(), managerContainers); } managerContainers.put(key.getManagerFQN(), container); } private InterfaceIntroduction getInterfaceIntroduction() { int introductionLength = (hasInterfaceIntroductions()) ? interfaces.length : 0; int mixinLength = (hasMixins()) ? mixins.length : 0; if (introductionLength == 0 && mixinLength == 0) { return null; } Class proxiedClass = classAdvisor.getClazz(); if (proxiedClass == null) { proxiedClass = Object.class; } String[] introducedNames = getClassNames(interfaces); InterfaceIntroduction intro = new InterfaceIntroduction("Introduction" + counter++, proxiedClass.getName(), introducedNames); if (mixinLength > 0) { addMixins(intro); } return intro; } private void addMixins(InterfaceIntroduction intro) { for (int i = 0 ; i < mixins.length && mixins != null; i++) { Class[] mixinInterfaces = mixins[i].getInterfaces(); Class mixinClass = mixins[i].getMixin(); if (mixinInterfaces == null) { throw new RuntimeException("When defining a mixin, interfaces must be defined"); } if (mixinClass == null) { throw new RuntimeException("When defining a mixin, the mixin must be defined"); } String[] mixinInterfaceNames = getClassNames(mixinInterfaces); InterfaceIntroduction.Mixin mixin = new InterfaceIntroduction.Mixin(mixinClass.getName(), mixinInterfaceNames, mixins[i].getConstruction(), false); intro.addMixin(mixin); } } private String[] getClassNames(Class[] classes) { if (classes == null) { return null; } String[] names = new String[classes.length]; for (int i = 0 ; i < classes.length ; i++) { names[i] = classes[i].getName(); } return names; } private void initInstanceContainer() { if (requiresInstanceAdvisor()) { InterfaceIntroduction introduction = null; if (hasInterfaceIntroductions() || hasMixins()) { introduction = getInterfaceIntroduction(); } instanceContainer = InstanceProxyContainer.createInstanceProxyContainer(classAdvisor, introduction, metaData); } } public boolean hasMoreAdvicesOrIntroductionsForInstance() { if (classAdvisor == null) { throw new IllegalStateException("initialise() must be called first"); } if (instanceContainer == null) { return false; } if (!classAdvisor.hasSameMethodAspectLength(instanceContainer)) { return true; } if (!classAdvisor.hasSameConstructorAspectLength(instanceContainer)) { return true; } if (instanceContainer.getInterfaceIntroductions().size() > classAdvisor.getInterfaceIntroductions().size()) { return true; } return false; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/Delegate.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/Delegate.jav0000644000175000017500000000265711145122054033237 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; /** * comment * * @author Bill Burke */ public interface Delegate { Object getDelegate(); void setDelegate(Object delegate); void setContainerProxyCacheKey(ContainerProxyCacheKey key); void localUnmarshal(MarshalledContainerProxy proxy); void remoteUnmarshal(MarshalledContainerProxy proxy, MarshalledProxyAdvisor advisor); } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ProxyAdvisorDomain.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ProxyAdvisor0000644000175000017500000000432511145122062033410 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.lang.ref.WeakReference; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.GeneratedAdvisorDomain; /** * The domain used by the container proxies * * @author Kabir Khan * @version $Revision: 77239 $ */ public class ProxyAdvisorDomain extends GeneratedAdvisorDomain { protected WeakReference advisor; public ProxyAdvisorDomain(AspectManager manager, String name, Class clazz) { this(manager, name, clazz, false); } public ProxyAdvisorDomain(AspectManager manager, String name, Class clazz, boolean instanceDomain) { super(manager, name, clazz, instanceDomain); super.setInheritsBindings(true); super.setInheritsDeclarations(true); } public Advisor getAdvisor() { return advisor.get(); } public void setAdvisor(Advisor advisor) { this.advisor = new WeakReference(advisor); } public void attachAdvisor() { Advisor adv = advisor.get(); advisors.put(adv.getClazz(), new WeakReference(adv)); } public void removeAdvisor(Advisor advisor) { advisors.remove(advisor.getClazz()); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/MarshalledContainerProxy.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/MarshalledCo0000644000175000017500000003745111145122066033307 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.InstanceAdvisor; import org.jboss.aop.MethodInfo; import org.jboss.aop.advice.AbstractAdvice; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.advice.PerInstanceAdvice; import org.jboss.aop.advice.PerInstanceInterceptor; import org.jboss.aop.advice.PerJoinpointAdvice; import org.jboss.aop.advice.PerJoinpointInterceptor; import org.jboss.aop.instrument.Untransformable; import org.jboss.aop.metadata.SimpleMetaData; import org.jboss.aop.util.MethodHashing; import org.jboss.util.id.GUID; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ public class MarshalledContainerProxy implements Serializable { private static final long serialVersionUID = 1L; //Fields to check if we are unmarshalling in the same JVM public final static GUID GUID = new GUID(); private transient AspectManaged proxyInstance; //Fields from the proxy, used when unmarshalling in the same JVM private String proxyClassName; private ContainerProxyCacheKey key; private Object mixins[]; private Object delegate; private Class clazz; private SimpleMetaData metadata; //Interfaces resulting from a mixin or interface introduction private String[] introducedInterfaces; //Interfaces implemented by mixins that are already implemented by the target class private Set targetInterfaces = new HashSet(); //The interceptor chains for each method used when unmarshalling in a different JVM MarshalledInterceptors marshalledInterceptors; //The instanceAdvisor domain name used when unmarshalling in a different JVM private String instanceAdvisorDomainName; public MarshalledContainerProxy(AspectManaged proxyInstance, ContainerProxyCacheKey key, Object[] mixins, Object delegate, Advisor currentAdvisor, SimpleMetaData metadata) { this.proxyInstance = proxyInstance; Class proxyClass = proxyInstance.getClass(); this.proxyClassName = proxyClass.getName(); this.key = key; this.mixins = mixins; this.delegate = delegate; this.clazz = currentAdvisor.getClazz(); checkInstanceAdvisor(currentAdvisor); this.metadata = metadata; marshalledInterceptors = new MarshalledInterceptors(currentAdvisor, mixins); Class[] proxyInterfaces = proxyClass.getInterfaces(); ArrayList ifs = new ArrayList(); for (int i = 0 ; i < proxyInterfaces.length ; i++) { String name = proxyInterfaces[i].getName(); if (name.equals(Untransformable.class.getName()) || name.equals(Delegate.class.getName()) || name.equals(AspectManaged.class.getName())) { continue; } if (proxyInterfaces[i].isAssignableFrom(clazz)) { targetInterfaces.add(clazz.getName()); continue; } ifs.add(proxyInterfaces[i].getName()); } introducedInterfaces = ifs.toArray(new String[ifs.size()]); } private void checkInstanceAdvisor(Advisor advisor) { if (advisor instanceof InstanceProxyContainer) { AspectManager manager = advisor.getManager(); instanceAdvisorDomainName = manager.getManagerFQN(); } } public Object readResolve() throws ObjectStreamException { try { if (isLocal()) { return localReadResolve(); } return remoteReadResolve(); } catch (Exception e) { InvalidObjectException ex = new InvalidObjectException(e.getMessage()); ex.setStackTrace(e.getStackTrace()); ex.initCause(e); throw ex; } } private Object localReadResolve() throws Exception { ClassLoader tcl = SecurityActions.getContextClassLoader(); Class proxyClass = tcl.loadClass(proxyClassName); Object proxy = proxyClass.newInstance(); Delegate delegate = (Delegate)proxy; delegate.localUnmarshal(this); return proxy; } private Object remoteReadResolve() throws Exception { if (marshalledInterceptors.getException() != null) { throw new Exception("Could not read object, an error happened when writing it on the server", marshalledInterceptors.getException()); } MarshalledProxyAdvisor advisor = marshalledInterceptors.getMarshalledAdvisor(); advisor.setClazz(clazz); boolean objectAsSuper = key.getClazz().equals(Object.class); Class proxyClass = ContainerProxyFactory.getProxyClass(objectAsSuper, key, advisor, this); Delegate proxy = (Delegate)proxyClass.newInstance(); proxy.remoteUnmarshal(this, advisor); return proxy; } private boolean isLocal() { return key.getGuid().equals(GUID); } public ContainerProxyCacheKey getKey() { return key; } public Object[] getMixins() { return mixins; } public Object getDelegate() { return delegate; } public Class getClazz() { return clazz; } public SimpleMetaData getMetadata() { return metadata; } public String getInstanceAdvisorDomainName() { return instanceAdvisorDomainName; } protected String[] getIntroducedInterfaces() { return introducedInterfaces; } protected Set getTargetInterfaces() { return targetInterfaces; } private class MarshalledInterceptors implements Serializable { private static final long serialVersionUID = 1L; transient Advisor currentAdvisor; Object[] mixins; private Exception exception; public MarshalledInterceptors(Advisor currentAdvisor, Object[] mixins) { this.currentAdvisor = currentAdvisor; this.mixins = mixins; } public Exception getException() { return exception; } public MarshalledProxyAdvisor getMarshalledAdvisor() { return (MarshalledProxyAdvisor)currentAdvisor; } private void writeObject(ObjectOutputStream out) throws IOException { ObjectOutputStream test = new ObjectOutputStream(new ByteArrayOutputStream()); try { MethodInfo[] methodInfos = getMethodInfos(); MarshalledMethodInfo[] marshalledInfos = new MarshalledMethodInfo[methodInfos.length]; for (int i = 0 ; i < methodInfos.length ; i++) { MarshalledMethodInfo info = new MarshalledMethodInfo(MarshalledContainerProxy.this, methodInfos[i]); marshalledInfos[i] = info; try { test.writeObject(info); continue; } catch (Exception e) { IOException ex = new IOException("An error happened serializing the info for " + getExceptionExpression(methodInfos[i])); ex.initCause(e); out.writeObject(ex); return; } } out.writeObject(marshalledInfos); } finally { try { test.close(); } catch (Exception e) { } } } private MethodInfo[] getMethodInfos() { if (currentAdvisor instanceof MarshalledProxyAdvisor) { return ((MarshalledProxyAdvisor)currentAdvisor).getMethodInfos(); } return ((ClassProxyContainer)currentAdvisor).getMethodInfos(); } private String getExceptionExpression(MethodInfo info) { Method m = info.getMethod(); StringBuilder expr = new StringBuilder(); if (m == null) { expr.append("a method"); } else { expr.append(m.getDeclaringClass().getName()); expr.append("."); expr.append(m.getName()); expr.append("("); boolean first = true; for (Class c : m.getParameterTypes()) { if (first) { first = false; } else { expr.append(", "); } expr.append(c.getName()); } expr.append(")"); } return expr.toString(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { Object o = in.readObject(); if (o instanceof IOException) { exception = (IOException)o; return; } MarshalledProxyAdvisor advisor = new MarshalledProxyAdvisor("Unmarshalled", AspectManager.getTopLevelAspectManager()); MarshalledMethodInfo[] marshalledInfos = (MarshalledMethodInfo[])o; MethodInfo[] methodInfos = new MethodInfo[marshalledInfos.length]; for (int i = 0 ; i < marshalledInfos.length ; i++) { methodInfos[i] = marshalledInfos[i].getMethodInfo(advisor); advisor.addMethodInfo(methodInfos[i]); } currentAdvisor = advisor; } } private static class MarshalledMethodInfo implements Serializable { private static final long serialVersionUID = 1L; transient MarshalledContainerProxy proxy; long advisedHash; long unadvisedHash; Interceptor[] interceptors; Class clazz; transient boolean requiresInstanceAdvisor; public MarshalledMethodInfo(MarshalledContainerProxy proxy, MethodInfo info) throws IOException { this.proxy = proxy; try { this.advisedHash = MethodHashing.methodHash(info.getMethod()); this.unadvisedHash = MethodHashing.methodHash(info.getUnadvisedMethod()); } catch (Exception e) { throw new MethodHashingException(e); } clazz = info.getMethod().getDeclaringClass(); populateInterceptors(info); } public boolean getRequiresInstanceAdvisor() { return requiresInstanceAdvisor; } private void populateInterceptors(MethodInfo info) { Interceptor[] icptrs = info.getInterceptors(); if (icptrs != null) { ArrayList allIcptrs = new ArrayList(icptrs.length); for (int i = 0 ; i < icptrs.length ; i++) { if (icptrs[i] instanceof AbstractAdvice == false) { Interceptor icptr = null; if (icptrs[i] instanceof PerInstanceInterceptor && !Modifier.isStatic(info.getMethod().getModifiers())) { requiresInstanceAdvisor = true; InstanceAdvisor ia = getProxyInstanceAdvisor(); icptr = ((PerInstanceInterceptor)icptrs[i]).getAspectInstance(ia); } else if (icptrs[i] instanceof PerJoinpointInterceptor && !Modifier.isStatic(info.getMethod().getModifiers())) { requiresInstanceAdvisor = true; InstanceAdvisor ia = getProxyInstanceAdvisor(); icptr = ((PerJoinpointInterceptor)icptrs[i]).getAspectInstance(ia); } else { icptr = icptrs[i]; } if (icptr != null) { allIcptrs.add(icptr); } } else { AbstractAdvice advice = (AbstractAdvice)icptrs[i]; Object aspectInstance = null; if (icptrs[i] instanceof PerInstanceAdvice && !Modifier.isStatic(info.getMethod().getModifiers())) { requiresInstanceAdvisor = true; InstanceAdvisor ia = getProxyInstanceAdvisor(); aspectInstance = ((PerInstanceAdvice)advice).getAspectInstance(ia); } else if (icptrs[i] instanceof PerJoinpointAdvice && !Modifier.isStatic(info.getMethod().getModifiers())) { requiresInstanceAdvisor = true; InstanceAdvisor ia = getProxyInstanceAdvisor(); aspectInstance = ((PerJoinpointAdvice)advice).getAspectInstance(ia); } else { aspectInstance = advice.getAspectInstance(); } if (aspectInstance != null) { MarshalledAdvice ma = new MarshalledAdvice(aspectInstance, icptrs[i].getName(), advice.getAdviceName()); allIcptrs.add(ma); } } } interceptors = allIcptrs.toArray(new Interceptor[allIcptrs.size()]); } } private InstanceAdvisor getProxyInstanceAdvisor() { InstanceAdvisor ia = proxy.proxyInstance.getInstanceAdvisor(); proxy.checkInstanceAdvisor((InstanceProxyContainer)ia); return ia; } public MethodInfo getMethodInfo(Advisor advisor) { MethodInfo info = new MethodInfo(clazz, advisedHash, unadvisedHash, advisor); info.setInterceptors(interceptors); return info; } public String toString() { return advisedHash + " " + ((interceptors == null) ? "null" : Arrays.asList(interceptors)); } } private static class MethodHashingException extends IOException { private static final long serialVersionUID = 1L; MethodHashingException(Exception e) { super("Error hashing method"); super.initCause(e); } } }././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AspectManaged.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AspectManage0000644000175000017500000000310711145122064033266 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import org.jboss.aop.Advisor; import org.jboss.aop.InstanceAdvisor; import org.jboss.aop.metadata.SimpleMetaData; import org.jboss.util.id.GUID; /** * comment * * @author Bill Burke */ public interface AspectManaged { GUID GUID = new GUID(); public Advisor getAdvisor(); public void setAdvisor(Advisor advisor); public InstanceAdvisor getInstanceAdvisor(); public void setInstanceAdvisor(InstanceAdvisor instanceAdvisor); public void setMetadata(SimpleMetaData metadata); } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerProxyCacheKey.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ContainerPro0000644000175000017500000002305011145122066033342 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.io.IOException; import java.io.Serializable; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Comparator; import org.jboss.metadata.spi.MetaData; import org.jboss.util.id.GUID; /** * * @author Kabir Khan * @version $Revision: 72999 $ */ public class ContainerProxyCacheKey implements Serializable { private static final long serialVersionUID = 8758283842273747310L; private static final WeakReference>[] EMTPY_WR_ARRAY = new WeakReference[0]; private static final AOPProxyFactoryMixin[] EMPTY_MIXIN_ARRAY = new AOPProxyFactoryMixin[0]; private String managerFqn; private WeakReference> clazzRef; private WeakReference>[] addedInterfaces = EMTPY_WR_ARRAY; private MetaData metaData; /** In case we are serializing with an unserializable MetaData in the same JVM, give a chance to make sure that the metaData is the same */ private long metaDataIdentityHashCode; private AOPProxyFactoryMixin[] addedMixins = EMPTY_MIXIN_ARRAY; private int hashcode = 0; private GUID guid = MarshalledContainerProxy.GUID; public ContainerProxyCacheKey(String managerFqn, Class clazz) { this.clazzRef = new WeakReference>(clazz); this.managerFqn = managerFqn; } public ContainerProxyCacheKey(Class clazz) { this("/", clazz); } public ContainerProxyCacheKey(String managerFqn, Class clazz, Class[] addedInterfaces, MetaData metaData) { this(managerFqn, clazz); this.addedInterfaces = ContainerCacheUtil.getSortedWeakReferenceForInterfaces(addedInterfaces); this.metaData = metaData; } public ContainerProxyCacheKey(String managerFqn, Class clazz, Class[] addedInterfaces, AOPProxyFactoryMixin[] addedMixins, MetaData metaData) { this(managerFqn, clazz, addedInterfaces, metaData); if (addedMixins != null) { this.addedMixins = addedMixins; Arrays.sort(this.addedMixins, MixinAlphabetical.singleton); } } public Class getClazz() { return clazzRef.get(); } public String getManagerFQN() { return managerFqn; } protected GUID getGuid() { return guid; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj.getClass() != ContainerProxyCacheKey.class) { return false; } ContainerProxyCacheKey other = (ContainerProxyCacheKey)obj; if (!managerFqn.equals(other.managerFqn)) { return false; } if (!compareMetadataContext(other)) { return false; } if (!compareClass(other)) { return false; } if (!compareAddedInterfaces(other)) { return false; } if (!compareAddedMixins(other)) { return false; } if(!guid.equals(other.guid)) { return false; } return true; } public int hashCode() { if (hashcode == 0) { Class clazz = clazzRef.get(); StringBuffer sb = new StringBuffer(); sb.append(managerFqn); if (clazz != null) { sb.append(clazz.getName()); } if (addedInterfaces != null) { for (int i = 0 ; i < addedInterfaces.length ; i++) { sb.append(";"); sb.append((addedInterfaces[i].get()).getName()); } } hashcode = sb.toString().hashCode(); if (metaData != null) { hashcode += metaData.hashCode(); } } return hashcode; } public String toString() { StringBuffer buf = new StringBuffer("ContainerProxyCache{"); buf.append((clazzRef.get()).getName()); buf.append(";fqn=" + managerFqn); buf.append(";interfaces="); if (addedInterfaces == null) { buf.append("null"); } else { buf.append(Arrays.asList(addedInterfaces)); } buf.append(";mixins="); if (addedMixins == null) { buf.append("null"); } else { buf.append(Arrays.asList(addedMixins)); } buf.append("}"); return buf.toString(); } private boolean compareMetadataContext(ContainerProxyCacheKey other) { if (this.metaData == null && this.metaDataIdentityHashCode == 0 && other.metaData == null && other.metaDataIdentityHashCode == 0) { return true; } if (this.metaData != null && other.metaData != null) { return this.metaData.equals(other.metaData); } if (this.metaDataIdentityHashCode != 0 && other.metaDataIdentityHashCode != 0) { return this.metaDataIdentityHashCode == other.metaDataIdentityHashCode; } if (this.metaData != null && other.metaData == null && other.metaDataIdentityHashCode != 0) { long oneHashCode = System.identityHashCode(this.metaData); if (oneHashCode == other.metaDataIdentityHashCode) { other.metaData = this.metaData; return true; } } if (other.metaData != null && this.metaData == null && this.metaDataIdentityHashCode != 0) { long twoHashCode = System.identityHashCode(other.metaData); if (twoHashCode == this.metaDataIdentityHashCode) { this.metaData = other.metaData; return true; } } return false; } private boolean compareClass(ContainerProxyCacheKey other) { return ContainerCacheUtil.compareClassRefs(this.clazzRef, other.clazzRef); } private boolean compareAddedInterfaces(ContainerProxyCacheKey other) { return ContainerCacheUtil.compareInterfaceRefs(this.addedInterfaces, other.addedInterfaces); } private boolean compareAddedMixins(ContainerProxyCacheKey other) { if ((this.addedMixins == null && other.addedMixins != null) || (this.addedMixins == null && other.addedMixins != null)) { return false; } if (this.addedMixins != null && other.addedMixins != null) { if (this.addedMixins.length != other.addedMixins.length) { return false; } for (int i = 0 ; i < this.addedMixins.length ; i++) { if (!this.addedMixins[i].equals(other.addedMixins[i])) { return false; } } } return true; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeUTF(managerFqn); out.writeObject(guid); out.writeObject(clazzRef.get()); Class[] ifs = null; if (addedInterfaces != null) { ifs = new Class[addedInterfaces.length]; for (int i = 0 ; i < addedInterfaces.length ; i++) { ifs[i] = addedInterfaces[i].get(); } } out.writeObject(ifs); if (metaData instanceof Serializable) { out.writeObject(metaData); } else { out.writeObject(null); } out.writeLong(System.identityHashCode(metaData)); out.writeObject(addedMixins); out.writeInt(hashCode()); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { managerFqn = in.readUTF(); guid = (GUID)in.readObject(); clazzRef = new WeakReference>((Class)in.readObject()); Class[] ifs = (Class[])in.readObject(); if (ifs != null) { addedInterfaces = new WeakReference[ifs.length]; for (int i = 0 ; i < ifs.length ; i++) { addedInterfaces[i] = new WeakReference>(ifs[i]); } } metaData = (MetaData)in.readObject(); metaDataIdentityHashCode = in.readLong(); addedMixins = (AOPProxyFactoryMixin[])in.readObject(); hashcode = in.readInt(); } static class MixinAlphabetical implements Comparator { static MixinAlphabetical singleton = new MixinAlphabetical(); public int compare(AOPProxyFactoryMixin o1, AOPProxyFactoryMixin o2) { String name1 = o1.getMixin().getName(); String name2 = o2.getMixin().getName(); return (name1).compareTo(name2); } } }././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/GeneratedAOPProxyFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/GeneratedAOP0000644000175000017500000001433011145122060033170 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.lang.reflect.Constructor; import org.jboss.aop.Advised; import org.jboss.aop.AspectManager; import org.jboss.aop.instrument.Untransformable; import org.jboss.aop.util.logging.AOPLogger; /** * * @author Kabir Khan * @version $Revision: 77480 $ */ public class GeneratedAOPProxyFactory implements AOPProxyFactory { private static final AOPLogger logger = AOPLogger.getLogger(GeneratedAOPProxyFactory.class); /** * Create a proxy * * @param the expected type * @param target the target * @param interfaceClass the interface class * @return the proxy */ public static T createProxy(T target, Class interfaceClass) { if (target == null) return null; GeneratedAOPProxyFactory proxyFactory = new GeneratedAOPProxyFactory(); AOPProxyFactoryParameters params = new AOPProxyFactoryParameters(); params.setInterfaces(new Class[] { interfaceClass }); params.setObjectAsSuperClass(true); params.setTarget(target); Object proxy = proxyFactory.createAdvisedProxy(params); if( AspectManager.verbose && logger.isDebugEnabled()) logger.debug("Created proxy: "+proxy.getClass()+"@"+System.identityHashCode(proxy)+" target: "+target.getClass()); return interfaceClass.cast(proxy); } public Object createAdvisedProxy(AOPProxyFactoryParameters params) { if (params.getTarget() != null) { if (params.getProxiedClass() != null) { if (params.getProxiedClass().isAssignableFrom(params.getTarget().getClass()) == false) { throw new RuntimeException("Specified class type " + params.getProxiedClass().getName() + " and target " + params.getTarget().getClass().getName() + " are not compatible"); } } else { params.setProxiedClass(params.getTarget().getClass()); } } else if (params.getProxiedClass() == null) { params.setProxiedClass(Object.class); } return getProxy(params); } private Object getProxy(AOPProxyFactoryParameters params) { try { Class proxyClass = null; boolean isAdvised = Advised.class.isAssignableFrom(params.getProxiedClass()); if (params.getTarget() instanceof Untransformable || (isAdvised && params.getInterfaces() == null && params.getMixins() == null && (params.getMetaData() == null || !params.getMetaDataHasInstanceLevelData()) && params.getSimpleMetaData() == null)) { return params.getTarget(); } synchronized (ContainerCache.mapLock) { ContainerCache cache = params.getContainerCache(); if (cache == null) { cache = ContainerCache.initialise(AspectManager.instance(), params); params.setContainerCache(cache); } boolean hasMoreAdvicesOrIntroductionsForInstance = cache.hasMoreAdvicesOrIntroductionsForInstance(); if (!cache.hasAspects() && !cache.hasIntroductionsForClassAdvisor() && !hasMoreAdvicesOrIntroductionsForInstance) { return params.getTarget(); } else { boolean needsProxy = false; if (isAdvised && hasMoreAdvicesOrIntroductionsForInstance) { needsProxy = true; } else { needsProxy = true; } if (needsProxy) { proxyClass = generateProxy(params); } } } return instantiateAndConfigureProxy(proxyClass, params); } catch (Exception e) { throw new RuntimeException(e); } } private Class generateProxy(AOPProxyFactoryParameters params) throws Exception { Class proxyClass = ContainerProxyFactory.getProxyClass(params.isObjectAsSuperClass(), params.getContainerCache().getKey(), params.getContainerCache().getAdvisor()); return proxyClass; } private Object instantiateAndConfigureProxy(Class proxyClass, AOPProxyFactoryParameters params) throws Exception { AspectManaged proxy; if (params.getCtor() != null) { Constructor ctor = proxyClass.getConstructor(params.getCtor().getSignature()); proxy = (AspectManaged)ctor.newInstance(params.getCtor().getArguments()); } else { proxy = (AspectManaged)proxyClass.newInstance(); } proxy.setAdvisor(params.getContainerCache().getClassAdvisor()); if (params.getContainerCache().getInstanceContainer() != null) { proxy.setInstanceAdvisor(params.getContainerCache().getInstanceContainer()); } if (params.getSimpleMetaData() != null) { proxy.setMetadata(params.getSimpleMetaData()); } if (params.getTarget() != null) { ((Delegate)proxy).setDelegate(params.getTarget()); } else { ((Delegate)proxy).setDelegate(new Object()); } ((Delegate)proxy).setContainerProxyCacheKey(params.getContainerCache().getKey()); return proxy; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/MarshalledAdvice.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/MarshalledAd0000644000175000017500000000572611145122060033264 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.jboss.aop.advice.AbstractAdvice; import org.jboss.aop.joinpoint.Invocation; class MarshalledAdvice extends AbstractAdvice implements Serializable { private static final long serialVersionUID = 1L; private Object aspect; private String name; private volatile boolean initialised = false; public MarshalledAdvice(Object aspect, String name, String adviceName) { this.aspect = aspect; this.name = name; super.adviceName = adviceName; super.aspectClass = aspect.getClass(); } @Override public Object getAspectInstance() { return aspect; } public String getName() { return name; } public Object invoke(Invocation invocation) throws Throwable { if (!initialised) { super.init(adviceName, aspect.getClass()); initialised = true; } Method advice = resolveAdvice(invocation); Object[] args = {invocation}; try { return advice.invoke(aspect, args); } catch (InvocationTargetException e) { throw e.getCause(); //To change body of catch statement use Options | File Templates. } } private void writeObject(ObjectOutputStream out) throws IOException { out.writeUTF(name); out.writeUTF(super.adviceName); out.writeObject(aspect); out.writeObject(super.aspectClass); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { name = in.readUTF(); super.adviceName = in.readUTF(); aspect = in.readObject(); super.aspectClass = (Class)in.readObject(); } }././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AOPProxyFactoryMixin.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/AOPProxyFact0000644000175000017500000001234411145122064033220 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.io.IOException; import java.io.Serializable; import java.lang.ref.WeakReference; public class AOPProxyFactoryMixin implements Serializable { private static final long serialVersionUID = 1L; private String construction; private WeakReference> mixinClassRef; private WeakReference>[] interfaceClassRefs; private int hashcode; public AOPProxyFactoryMixin(Class mixin, Class[] interfaces) { mixinClassRef = new WeakReference>(mixin); interfaceClassRefs = ContainerCacheUtil.getSortedWeakReferenceForInterfaces(interfaces); } public AOPProxyFactoryMixin(Class mixin, Class[] interfaces, String parameters) { this(mixin, interfaces); StringBuffer construction = new StringBuffer(" new "); construction.append(mixin.getName()); if (!parameters.startsWith("(")) { construction.append("("); } construction.append(parameters); if (!parameters.endsWith(")")) { construction.append(")"); } this.construction = construction.toString(); } public String getConstruction() { return construction; } public Class[] getInterfaces() { if (interfaceClassRefs != null) { Class[] interfaces = new Class[interfaceClassRefs.length]; for (int i = 0 ; i < interfaces.length ; i++) { interfaces[i] = interfaceClassRefs[i].get(); } return interfaces; } return null; } public Class getMixin() { return mixinClassRef.get(); } public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof AOPProxyFactoryMixin)) { return false; } AOPProxyFactoryMixin other = (AOPProxyFactoryMixin)obj; if (!compareConstruction(other)) { return false; } if (!ContainerCacheUtil.compareClassRefs(this.mixinClassRef, other.mixinClassRef)) { return false; } if (!ContainerCacheUtil.compareInterfaceRefs(this.interfaceClassRefs, other.interfaceClassRefs)) { return false; } return true; } public int hashCode() { if (hashcode == 0) { Class clazz = mixinClassRef.get(); StringBuffer sb = new StringBuffer(); if (clazz != null) { sb.append(clazz.getName()); } if (interfaceClassRefs != null) { for (int i = 0 ; i < interfaceClassRefs.length ; i++) { sb.append(";"); sb.append((interfaceClassRefs[i].get()).getName()); } } hashcode = sb.toString().hashCode(); if (construction != null) { hashcode += construction.hashCode(); } } return hashcode; } public String toString() { return super.toString(); } private boolean compareConstruction(AOPProxyFactoryMixin other) { if (this.construction == null && other.construction != null) { return false; } if (this.construction != null && other.construction == null) { return false; } if (this.construction != null) { if (!this.construction.equals(other.construction)) { return false; } } return true; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeObject(construction); out.writeObject(mixinClassRef.get()); out.writeObject(getInterfaces()); out.writeInt(hashCode()); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { construction = (String)in.readObject(); mixinClassRef = new WeakReference>((Class)in.readObject()); Class[] ifs = (Class[])in.readObject(); interfaceClassRefs = new WeakReference[ifs.length]; for (int i = 0 ; i < ifs.length ; i++) { interfaceClassRefs[i] = new WeakReference>(ifs[i]); } hashcode = in.readInt(); } }././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ClassProxyContainer.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/container/ClassProxyCo0000644000175000017500000001646011145122060033331 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy.container; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.lang.reflect.Method; import org.jboss.aop.Advisor; import org.jboss.aop.ClassContainer; import org.jboss.aop.AspectManager; import org.jboss.aop.ClassAdvisor; import org.jboss.aop.MethodInfo; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.util.ConstructorComparator; import org.jboss.aop.util.MethodHashing; /** * Extension of ClassContainer needed because of Mixins * we want to be able to match pointcut expressions on the base class of the delegate * we also want to be able to match pointcuts of instanceof{} of the Mixin interfaces. * * We also want to create constructor tables based on the constructor of the delegate so we can intercept * construction * * @author Bill Burke */ public class ClassProxyContainer extends ClassContainer { public ClassProxyContainer(String name, AspectManager manager) { super(name, manager); } protected void createConstructorTables() { Class useClass = clazz; if (clazz.getName().startsWith(ContainerProxyFactory.PROXY_NAME_PREFIX) && clazz != null && clazz.getSuperclass() != null) { useClass = clazz.getSuperclass(); } if (useClass != null) { final Class theUseClass = useClass; AccessController.doPrivileged(new PrivilegedAction() { public Object run() { constructors = theUseClass.getDeclaredConstructors(); for (int i = 0; i < constructors.length; i++) { constructors[i].setAccessible(true); } return null; } }); Arrays.sort(constructors, ConstructorComparator.INSTANCE); } } protected void createMethodMap() { initAdvisedMethodsMap(); try { Method[] declaredMethods = clazz.getMethods(); Class superclass = clazz.getSuperclass(); for (int i = 0; i < declaredMethods.length; i++) { Method method = declaredMethods[i]; if (ClassAdvisor.isAdvisable(method)) { long hash = MethodHashing.methodHash(method); try { if (method.getDeclaringClass().getName().indexOf(ContainerProxyFactory.PROXY_NAME_PREFIX) >= 0 && superclass != null) method = superclass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ignored) { // this is a mixin method or a proxy method } advisedMethods.put(hash, method); } } for (int i = 0; i < interfaceIntroductions.size(); ++i) { InterfaceIntroduction ii = interfaceIntroductions.get(i); String[] intf = ii.getInterfaces(); addMethodsFromInterfaces(intf); ArrayList mixins = ii.getMixins(); if (mixins.size() > 0) { for (InterfaceIntroduction.Mixin mixin : mixins) { String[] mintf = mixin.getInterfaces(); addMethodsFromInterfaces(mintf); } } } } catch (Exception e) { throw new RuntimeException(e); } } private void addMethodsFromInterfaces(String[] intf) throws Exception { ClassLoader cl = SecurityActions.getClassLoader(clazz); if (cl == null) { //Fall back to context classloader cl = SecurityActions.getContextClassLoader(); } for (int j = 0; intf != null && j < intf.length; ++j) { Class iface = cl.loadClass(intf[j]); Method[] ifaceMethods = iface.getMethods(); for (int k = 0; k < ifaceMethods.length; k++) { long hash = MethodHashing.methodHash(ifaceMethods[k]); if (advisedMethods.get(hash) == null) { advisedMethods.put(hash, ifaceMethods[k]); } } } } public InstanceProxyContainer createInstanceProxyContainer() { //This seems to get thrown away with every invocation ProxyAdvisorDomain domain = new ProxyAdvisorDomain(manager, null, clazz, false); domain.setInheritsBindings(true); domain.setInheritsDeclarations(true); InstanceProxyContainer ia = new InstanceProxyContainer(super.getName(), domain, this, null); return ia; } @SuppressWarnings("deprecation") public void initialise(Class proxiedClass) { setClass(proxiedClass); ((ProxyAdvisorDomain)manager).attachAdvisor(); initializeInterfaceIntroductions(proxiedClass); super.initializeClassContainer(); } protected Advisor getParentAdvisor() { return null; } @Override public void addPerClassAspect(AspectDefinition def) { Advisor parentAdvisor = getParentAdvisor(); if (parentAdvisor != null) { parentAdvisor.addPerClassAspect(def); return; } super.addPerClassAspect(def); } /** * If this is an instance advisor, will check with parent advisor if the aspect * is already registered. If so, we should use the one from the parent advisor */ @Override public Object getPerClassAspect(AspectDefinition def) { Advisor parentAdvisor = getParentAdvisor(); if (parentAdvisor != null) { Object aspect = parentAdvisor.getPerClassAspect(def); if (aspect != null) return aspect; } return super.getPerClassAspect(def); } /** * @return true always * @see Advisor#chainOverridingForInheritedMethods() */ @Override public boolean chainOverridingForInheritedMethods() { return true; } public MethodInfo[] getMethodInfos() { long[] keys = methodInfos.keys(); MethodInfo[] minfos = new MethodInfo[keys.length]; for (int i = 0 ; i < keys.length ; i++) { minfos[i] = methodInfos.getMethodInfo(keys[i]); } return minfos; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ProxyMixin.java0000644000175000017500000000322011145122056032017 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import java.io.Serializable; /** * Comment * * @author Bill Burke * @version $Revision: 71276 $ */ public class ProxyMixin implements Serializable { static final long serialVersionUID = -6150046185716362835L; private Object mixin; private Class[] interfaces; protected ProxyMixin() { } public ProxyMixin(Object mixin, Class[] interfaces) { this.interfaces = interfaces; this.mixin = mixin; } public Object getMixin() { return mixin; } public Class[] getInterfaces() { return interfaces; } }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ProxyFactory.java0000644000175000017500000002340511145122056032351 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import org.jboss.aop.AspectManager; import org.jboss.aop.ClassInstanceAdvisor; import org.jboss.aop.InstanceAdvisor; import org.jboss.aop.instrument.Instrumentor; import org.jboss.aop.instrument.TransformerCommon; import org.jboss.aop.util.JavassistMethodHashing; import org.jboss.aop.util.reference.MethodPersistentReference; import org.jboss.util.collection.WeakValueHashMap; import org.jboss.util.id.GUID; import java.lang.reflect.Field; import java.security.ProtectionDomain; import java.util.HashSet; import java.util.Map; /** * Comment * * @author Bill Burke * @version $Revision: 81449 $ */ public class ProxyFactory { private static long counter = 0; private static WeakValueHashMap> proxyCache = new WeakValueHashMap>(); public static Proxy createInterfaceProxy(ClassLoader loader, Class[] interfaces, ProxyMixin[] mixins, InstanceAdvisor advisor) throws Exception { Class clazz = createProxyClass(loader, mixins, interfaces); Proxy instance = (Proxy) clazz.newInstance(); instance.instanceAdvisor = advisor; instance.mixins = mixins; instance.interfaces = interfaces; instance.guid = new GUID(); synchronized (proxyCache) { proxyCache.put(instance.guid, clazz); } return instance; } public static Class getProxyClass(GUID guid) { synchronized (proxyCache) { return proxyCache.get(guid); } } public static Proxy createInterfaceProxy(GUID guid, ClassLoader loader, Class[] interfaces) throws Exception { return createInterfaceProxy(guid, loader, interfaces, null, new ClassInstanceAdvisor()); } public static Proxy createInterfaceProxy(GUID guid, ClassLoader loader, Class[] interfaces, ProxyMixin[] mixins, InstanceAdvisor advisor) throws Exception { Class clazz = getProxyClass(guid); boolean wasFound = true; if (clazz == null) { wasFound = false; clazz = createProxyClass(loader, mixins, interfaces); } Proxy instance = (Proxy) clazz.newInstance(); instance.instanceAdvisor = advisor; instance.mixins = mixins; instance.interfaces = interfaces; instance.guid = guid; if (!wasFound) { synchronized (proxyCache) { proxyCache.put(guid, clazz); } } return instance; } private static Class createProxyClass(ClassLoader loader, ProxyMixin[] mixins, Class[] interfaces) throws Exception { CtClass proxy = createProxyCtClass(loader, mixins, interfaces); // Choose the first non-null ProtectionDomain ProtectionDomain pd = null; for(int n = 0; n < interfaces.length && pd == null; n ++) { pd = interfaces[n].getProtectionDomain(); } Class clazz = TransformerCommon.toClass(proxy, loader, pd); Map methodmap = ClassProxyFactory.getMethodMap(clazz); Field field = clazz.getDeclaredField("methodMap"); SecurityActions.setAccessible(field); field.set(null, methodmap); return clazz; } public static GUID generateProxyClass(ClassLoader loader, ProxyMixin[] mixins, Class[] interfaces) throws Exception { Class clazz = createProxyClass(loader, mixins, interfaces); GUID guid = new GUID(); synchronized (proxyCache) { proxyCache.put(guid, clazz); } return guid; } private static CtClass createProxyCtClass(ClassLoader loader, ProxyMixin[] mixins, Class[] interfaces) throws Exception { ClassPool pool = AspectManager.instance().findClassPool(loader); if (pool == null) throw new NullPointerException("Could not find ClassPool"); String classname = "AOPProxy$" + counter++; CtClass base = pool.get("org.jboss.aop.proxy.Proxy"); CtClass proxy = TransformerCommon.makeClass(pool, classname, base); proxy.addInterface(pool.get("org.jboss.aop.instrument.Untransformable")); CtClass map = pool.get("java.util.Map"); CtField methodMap = new CtField(map, "methodMap", proxy); methodMap.setModifiers(Modifier.PRIVATE | Modifier.STATIC); Instrumentor.addSyntheticAttribute(methodMap); proxy.addField(methodMap); CtMethod getMethodMap = CtNewMethod.getter("getMethodMap", methodMap); getMethodMap.setModifiers(Modifier.PUBLIC); Instrumentor.addSyntheticAttribute(getMethodMap); proxy.addMethod(getMethodMap); HashSet addedInterfaces = new HashSet(); HashSet addedMethods = new HashSet(); if (mixins != null) { for (int i = 0; i < mixins.length; i++) { HashSet mixinMethods = new HashSet(); Class[] mixinf = mixins[i].getInterfaces(); ClassPool mixPool = AspectManager.instance().findClassPool(mixins[i].getMixin().getClass()); CtClass mixClass = mixPool.get(mixins[i].getMixin().getClass().getName()); for (int j = 0; j < mixinf.length; j++) { if (addedInterfaces.contains(mixinf[j].getName())) throw new Exception("2 mixins are implementing the same interfaces"); ClassPool mixIntfPool = AspectManager.instance().findClassPool(mixinf[j]); CtClass intfClass = mixIntfPool.get(mixinf[j].getName()); CtMethod[] methods = intfClass.getMethods(); for (int m = 0; m < methods.length; m++) { if (methods[m].getDeclaringClass().getName().equals("java.lang.Object")) continue; Long hash = new Long(JavassistMethodHashing.methodHash(methods[m])); if (mixinMethods.contains(hash)) continue; if (addedMethods.contains(hash)) throw new Exception("More than one mixin has same method"); mixinMethods.add(hash); addedMethods.add(hash); String returnStr = (methods[m].getReturnType().equals(CtClass.voidType)) ? "" : "return "; String code = "{" + " " + mixClass.getName() + " mixin = (" + mixClass.getName() + ")mixins[" + i + "].getMixin();" + " " + returnStr + " mixin." + methods[m].getName() + "($$);" + "}"; CtMethod newMethod = CtNewMethod.make(methods[m].getReturnType(), methods[m].getName(), methods[m].getParameterTypes(), methods[m].getExceptionTypes(), code, proxy); newMethod.setModifiers(Modifier.PUBLIC); proxy.addMethod(newMethod); } proxy.addInterface(intfClass); addedInterfaces.add(intfClass.getName()); } } } for (int i = 0; i < interfaces.length; i++) { if (addedInterfaces.contains(interfaces[i].getName())) continue; ClassPool mixPool = AspectManager.instance().findClassPool(interfaces[i]); CtClass intfClass = mixPool.get(interfaces[i].getName()); CtMethod[] methods = intfClass.getMethods(); for (int m = 0; m < methods.length; m++) { if (methods[m].getDeclaringClass().getName().equals("java.lang.Object")) continue; Long hash = new Long(JavassistMethodHashing.methodHash(methods[m])); if (addedMethods.contains(hash)) continue; addedMethods.add(hash); String aopReturnStr = (methods[m].getReturnType().equals(CtClass.voidType)) ? "" : "return ($r)"; String args = "null"; if (methods[m].getParameterTypes().length > 0) args = "$args"; String code = "{ " + " org.jboss.aop.advice.Interceptor[] aspects = instanceAdvisor.getInterceptors(); " + " org.jboss.aop.MethodInfo mi = new org.jboss.aop.MethodInfo(); " + " mi.setHash(" + hash.longValue() + "L);" + " org.jboss.aop.proxy.ProxyMethodInvocation invocation = new org.jboss.aop.proxy.ProxyMethodInvocation(this, mi, aspects); " + " invocation.setInstanceResolver(instanceAdvisor.getMetaData()); " + " invocation.setArguments(" + args + "); " + " " + aopReturnStr + " invocation.invokeNext(); " + "}"; CtMethod newMethod = CtNewMethod.make(methods[m].getReturnType(), methods[m].getName(), methods[m].getParameterTypes(), methods[m].getExceptionTypes(), code, proxy); newMethod.setModifiers(Modifier.PUBLIC); proxy.addMethod(newMethod); } proxy.addInterface(intfClass); } return proxy; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/SecurityActions.java0000644000175000017500000001056511145122054033031 0ustar twernertwerner/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import java.lang.reflect.AccessibleObject; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; /** * * @author Kabir Khan * @version $Revision: 1.1 $ */ class SecurityActions { interface SetAccessibleAction { void setAccessible(AccessibleObject accessibleObject); SetAccessibleAction PRIVILEGED = new SetAccessibleAction() { public void setAccessible(final AccessibleObject accessibleObject) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { accessibleObject.setAccessible(true); return null; } }); } catch (PrivilegedActionException e) { throw new RuntimeException("Error setting " + accessibleObject + " as accessible ", e.getException()); } } }; SetAccessibleAction NON_PRIVILEGED = new SetAccessibleAction() { public void setAccessible(AccessibleObject accessibleObject) { accessibleObject.setAccessible(true); } }; } static void setAccessible(AccessibleObject accessibleObject) { if (System.getSecurityManager() == null) { SetAccessibleAction.NON_PRIVILEGED.setAccessible(accessibleObject); } else { SetAccessibleAction.PRIVILEGED.setAccessible(accessibleObject); } } public static class GetContextClassLoaderAction implements PrivilegedAction { public static GetContextClassLoaderAction INSTANCE = new GetContextClassLoaderAction(); public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } } static ClassLoader getContextClassLoader() { if (System.getSecurityManager() == null) return Thread.currentThread().getContextClassLoader(); else return AccessController.doPrivileged(GetContextClassLoaderAction.INSTANCE); } interface GetClassLoaderAction { ClassLoader getClassLoader(Class clazz); GetClassLoaderAction NON_PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(Class clazz) { return clazz.getClassLoader(); }}; GetClassLoaderAction PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction() { public ClassLoader run() { return clazz.getClassLoader(); }}); }}; } static ClassLoader getClassLoader(Class clazz) { if (System.getSecurityManager() == null) { return GetClassLoaderAction.NON_PRIVILEGED.getClassLoader(clazz); } else { return GetClassLoaderAction.PRIVILEGED.getClassLoader(clazz); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ClassProxyTemplate.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ClassProxyTemplate.jav0000644000175000017500000000515311145122054033340 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import java.io.ObjectStreamException; /** * @author Bill Burke * @version $Revision: 71276 $ */ public class ClassProxyTemplate implements ClassProxy, java.io.Externalizable { static final long serialVersionUID = 7776009946350762531L; public ClassProxyTemplate() { } public org.jboss.aop.InstanceAdvisor instanceAdvisor; public org.jboss.aop.proxy.ProxyMixin[] mixins; public org.jboss.aop.InstanceAdvisor _getInstanceAdvisor() { return instanceAdvisor; } public void _setInstanceAdvisor(org.jboss.aop.InstanceAdvisor newAdvisor) { instanceAdvisor = newAdvisor; } public org.jboss.aop.joinpoint.InvocationResponse _dynamicInvoke(org.jboss.aop.joinpoint.Invocation invocation) throws Throwable { ((org.jboss.aop.joinpoint.InvocationBase) invocation).setInstanceResolver(instanceAdvisor.getMetaData()); org.jboss.aop.advice.Interceptor[] aspects = instanceAdvisor.getInterceptors(); return new org.jboss.aop.joinpoint.InvocationResponse(invocation.invokeNext(aspects)); } public Object writeReplace() throws ObjectStreamException { return new org.jboss.aop.proxy.MarshalledClassProxy(this.getClass().getSuperclass(), mixins, instanceAdvisor); } public void setMixins(org.jboss.aop.proxy.ProxyMixin[] mixins) { this.mixins = mixins; } public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) throws java.io.IOException, ClassNotFoundException { } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/MarshalledInterfaceProxy.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/MarshalledInterfacePro0000644000175000017500000000471411145122062033335 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import org.jboss.aop.InstanceAdvisor; import org.jboss.util.id.GUID; import java.io.ObjectStreamException; import java.io.Serializable; /** * Comment * * @author Bill Burke * @version $Revision: 77246 $ */ public class MarshalledInterfaceProxy implements Serializable { static final long serialVersionUID = -7939451715003985857L; private Class[] interfaces; private ProxyMixin[] mixins; private InstanceAdvisor advisor; private GUID guid; protected MarshalledInterfaceProxy() { } public MarshalledInterfaceProxy(GUID guid, Class[] intfs, ProxyMixin[] mixins, InstanceAdvisor advisor) { this.guid = guid; this.advisor = advisor; this.interfaces = intfs; this.mixins = mixins; } public Object readResolve() throws ObjectStreamException { try { ClassLoader cl = null; if (advisor.getInstance() != null) { cl = SecurityActions.getClassLoader(advisor.getInstance().getClass()); } //FIXME: When will instance not be null? if (cl == null) { //Fall back to the context classloader cl = SecurityActions.getContextClassLoader(); } return ProxyFactory.createInterfaceProxy(guid, cl, interfaces, mixins, advisor); } catch (Exception e) { throw new RuntimeException(e); } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ClassProxy.java0000644000175000017500000000263511145122060032004 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import org.jboss.aop.InstanceAdvised; /** * @author Bill Burke * @version $Revision: 41096 $ */ public interface ClassProxy extends InstanceAdvised { public org.jboss.aop.joinpoint.InvocationResponse _dynamicInvoke(org.jboss.aop.joinpoint.Invocation invocation) throws Throwable; public void setMixins(ProxyMixin[] mixins); } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ClassProxyFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ClassProxyFactory.java0000644000175000017500000004431411145122064033340 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.jboss.aop.AspectManager; import org.jboss.aop.ClassAdvisor; import org.jboss.aop.ClassInstanceAdvisor; import org.jboss.aop.InstanceAdvisor; import org.jboss.aop.instrument.Instrumentor; import org.jboss.aop.instrument.TransformerCommon; import org.jboss.aop.util.JavassistMethodHashing; import org.jboss.aop.util.reference.MethodPersistentReference; import org.jboss.aop.util.reference.PersistentReference; import org.jboss.util.collection.WeakValueHashMap; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import javassist.SerialVersionUID; /** * @author Bill Burke * @version $Revision: 81449 $ */ public class ClassProxyFactory { private static Object maplock = new Object(); private static WeakValueHashMap> classnameMap = new WeakValueHashMap>(); private static WeakHashMap, WeakReference>>> proxyCache = new WeakHashMap, WeakReference>>>(); private static WeakHashMap, Map> methodMapCache = new WeakHashMap, Map>(); public static ClassProxy newInstance(Class clazz) throws Exception { return newInstance(clazz, null); } public static ClassProxy newInstance(Class clazz, ProxyMixin[] mixins) throws Exception { return newInstance(clazz, mixins, new ClassInstanceAdvisor()); } public static ClassProxy newInstance(Class clazz, ProxyMixin[] mixins, boolean interceptWriteReplace) throws Exception { return newInstance(clazz, mixins, new ClassInstanceAdvisor(), interceptWriteReplace); } private static Class getProxyClass(Class clazz, ProxyMixin[] mixins, boolean interceptWriteReplace) throws Exception { // Don't make a proxy of a proxy ! if (ClassProxy.class.isAssignableFrom(clazz)) clazz = clazz.getSuperclass(); ClassPool pool = AspectManager.instance().findClassPool(clazz); if (pool == null) throw new NullPointerException("Could not find ClassPool"); Class proxyClass = null; synchronized (maplock) { WeakHashMap, WeakReference>> proxiesForLoader = proxyCache.get(pool.getClassLoader()); if (proxiesForLoader == null) { proxiesForLoader = new WeakHashMap, WeakReference>>(); proxyCache.put(pool.getClassLoader(), proxiesForLoader); } if (proxiesForLoader != null) { WeakReference> ref = proxiesForLoader.get(pool.getClassLoader()); if (ref != null) { proxyClass = ref.get(); } } if (proxyClass == null) { proxyClass = generateProxy(pool, clazz, mixins, interceptWriteReplace); classnameMap.put(clazz.getName(), proxyClass); proxiesForLoader.put(clazz, new WeakReference>(proxyClass)); HashMap map = methodMap(clazz); methodMapCache.put(proxyClass, map); } } return proxyClass; } public static ClassProxy newInstance(Class clazz, ProxyMixin[] mixins, InstanceAdvisor advisor) throws Exception { return newInstance(clazz, mixins, advisor, false); } public static ClassProxy newInstance(Class clazz, ProxyMixin[] mixins, InstanceAdvisor advisor, boolean interceptWriteReplace) throws Exception { Class proxyClass = getProxyClass(clazz, mixins, interceptWriteReplace); ClassProxy proxy = (ClassProxy) proxyClass.newInstance(); proxy.setMixins(mixins); proxy._setInstanceAdvisor(advisor); return proxy; } public static HashMap getMethodMap(String classname) { synchronized (maplock) { Class clazz = classnameMap.get(classname); if (clazz == null) return null; return (HashMap) methodMapCache.get(clazz); } } public static HashMap getMethodMap(Class clazz) { HashMap map = getMethodMap(clazz.getName()); if (map != null) return map; try { return methodMap(clazz); } catch (Exception e) { throw new RuntimeException(e); //To change body of catch statement use Options | File Templates. } } private static int counter = 0; private static CtClass createProxyCtClass(ClassPool pool, ProxyMixin[] mixins, Class clazz, boolean interceptWriteReplace) throws Exception { String classname = "AOPClassProxy$" + counter++; CtClass template = pool.get("org.jboss.aop.proxy.ClassProxyTemplate"); CtClass superclass = pool.get(clazz.getName()); CtField mixinField = template.getField("mixins"); CtField instanceAdvisor = template.getField("instanceAdvisor"); CtClass proxy = TransformerCommon.makeClass(pool, classname, superclass); mixinField = new CtField(mixinField.getType(), "mixins", proxy); mixinField.setModifiers(Modifier.PRIVATE); Instrumentor.addSyntheticAttribute(mixinField); proxy.addField(mixinField); instanceAdvisor = new CtField(instanceAdvisor.getType(), "instanceAdvisor", proxy); instanceAdvisor.setModifiers(Modifier.PRIVATE); proxy.addField(instanceAdvisor); CtMethod writeEx = CtNewMethod.make(" public void writeExternal(java.io.ObjectOutput out)\n" + " throws java.io.IOException\n" + " {\n" + " }", proxy); Instrumentor.addSyntheticAttribute(writeEx); CtMethod readEx = CtNewMethod.make(" public void readExternal(java.io.ObjectInput in)\n" + " throws java.io.IOException, ClassNotFoundException\n" + " {\n" + " }", proxy); Instrumentor.addSyntheticAttribute(readEx); CtMethod getInstanceAdvisor = CtNewMethod.make(" public org.jboss.aop.InstanceAdvisor _getInstanceAdvisor()\n" + " {\n" + " return instanceAdvisor;\n" + " }", proxy); Instrumentor.addSyntheticAttribute(getInstanceAdvisor); CtMethod setInstanceAdvisor = CtNewMethod.make(" public void _setInstanceAdvisor(org.jboss.aop.InstanceAdvisor newAdvisor)\n" + " {\n" + " instanceAdvisor = (org.jboss.aop.ClassInstanceAdvisor) newAdvisor;\n" + " }", proxy); Instrumentor.addSyntheticAttribute(setInstanceAdvisor); CtMethod dynamicInvoke = CtNewMethod.make(" public org.jboss.aop.joinpoint.InvocationResponse _dynamicInvoke(org.jboss.aop.joinpoint.Invocation invocation)\n" + " throws Throwable\n" + " {\n" + " ((org.jboss.aop.joinpoint.InvocationBase) invocation).setInstanceResolver(instanceAdvisor.getMetaData());\n" + " org.jboss.aop.advice.Interceptor[] aspects = instanceAdvisor.getInterceptors();\n" + " return new org.jboss.aop.joinpoint.InvocationResponse(invocation.invokeNext(aspects));\n" + " }", proxy); Instrumentor.addSyntheticAttribute(dynamicInvoke); CtMethod setMixins = CtNewMethod.make(" public void setMixins(org.jboss.aop.proxy.ProxyMixin[] mixins)\n" + " {\n" + " this.mixins = mixins;\n" + " }", proxy); Instrumentor.addSyntheticAttribute(setMixins); CtMethod writeReplace = CtNewMethod.make(" public Object writeReplace() throws java.io.ObjectStreamException\n" + " {\n" + " return new org.jboss.aop.proxy.MarshalledClassProxy(this.getClass().getSuperclass(), mixins, instanceAdvisor);\n" + " }", proxy); Instrumentor.addSyntheticAttribute(writeReplace); proxy.addMethod(writeEx); proxy.addMethod(readEx); proxy.addMethod(getInstanceAdvisor); proxy.addMethod(setInstanceAdvisor); proxy.addMethod(dynamicInvoke); proxy.addMethod(setMixins); if (!interceptWriteReplace) proxy.addMethod(writeReplace); /* CtMethod writeEx = template.getDeclaredMethod("writeExternal"); CtMethod readEx = template.getDeclaredMethod("readExternal"); CtMethod getInstanceAdvisor = template.getDeclaredMethod("_getInstanceAdvisor"); CtMethod setInstanceAdvisor = template.getDeclaredMethod("_setInstanceAdvisor"); CtMethod dynamicInvoke = template.getDeclaredMethod("_dynamicInvoke"); CtMethod setMixins = template.getDeclaredMethod("setMixins"); CtMethod writeReplace = template.getDeclaredMethod("writeReplace"); proxy.addMethod(CtNewMethod.copy(writeEx, proxy, null)); proxy.addMethod(CtNewMethod.copy(readEx, proxy, null)); proxy.addMethod(CtNewMethod.copy(getInstanceAdvisor, proxy, null)); proxy.addMethod(CtNewMethod.copy(setInstanceAdvisor, proxy, null)); proxy.addMethod(CtNewMethod.copy(dynamicInvoke, proxy, null)); proxy.addMethod(CtNewMethod.copy(setMixins, proxy, null)); proxy.addMethod(CtNewMethod.copy(writeReplace, proxy, null)); */ proxy.addInterface(pool.get("org.jboss.aop.proxy.ClassProxy")); proxy.addInterface(pool.get("java.io.Externalizable")); proxy.addInterface(pool.get("org.jboss.aop.instrument.Untransformable")); proxy.addInterface(pool.get("org.jboss.aop.proxy.MethodMapped")); CtClass map = pool.get("java.util.Map"); CtField methodMap = new CtField(map, "methodMap", proxy); methodMap.setModifiers(Modifier.PRIVATE | Modifier.STATIC); proxy.addField(methodMap); CtMethod getMethodMap = CtNewMethod.getter("getMethodMap", methodMap); getMethodMap.setModifiers(Modifier.PUBLIC); proxy.addMethod(getMethodMap); HashSet addedInterfaces = new HashSet(); HashSet addedMethods = new HashSet(); if (mixins != null) { for (int i = 0; i < mixins.length; i++) { HashSet mixinMethods = new HashSet(); Class[] mixinf = mixins[i].getInterfaces(); ClassPool mixPool = AspectManager.instance().findClassPool(mixins[i].getMixin().getClass()); CtClass mixClass = mixPool.get(mixins[i].getMixin().getClass().getName()); for (int j = 0; j < mixinf.length; j++) { if (addedInterfaces.contains(mixinf[j].getName())) throw new Exception("2 mixins are implementing the same interfaces"); ClassPool mixIntfPool = AspectManager.instance().findClassPool(mixinf[j]); CtClass intfClass = mixIntfPool.get(mixinf[j].getName()); CtMethod[] methods = intfClass.getMethods(); for (int m = 0; m < methods.length; m++) { if (methods[m].getDeclaringClass().getName().equals("java.lang.Object")) continue; Long hash = new Long(JavassistMethodHashing.methodHash(methods[m])); if (mixinMethods.contains(hash)) continue; if (addedMethods.contains(hash)) throw new Exception("More than one mixin has same method"); mixinMethods.add(hash); addedMethods.add(hash); String returnStr = (methods[m].getReturnType().equals(CtClass.voidType)) ? "" : "return "; String code = "{" + " " + mixClass.getName() + " mixin = (" + mixClass.getName() + ")mixins[" + i + "].getMixin();" + " " + returnStr + " mixin." + methods[m].getName() + "($$);" + "}"; CtMethod newMethod = CtNewMethod.make(methods[m].getReturnType(), methods[m].getName(), methods[m].getParameterTypes(), methods[m].getExceptionTypes(), code, proxy); newMethod.setModifiers(Modifier.PUBLIC); proxy.addMethod(newMethod); } proxy.addInterface(intfClass); addedInterfaces.add(intfClass.getName()); } } } HashMap allMethods = JavassistMethodHashing.getMethodMap(superclass); if (interceptWriteReplace) allMethods.put(JavassistMethodHashing.methodHash(writeReplace), writeReplace); for (Map.Entry entry : allMethods.entrySet()) { CtMethod m = entry.getValue(); if (!Modifier.isPublic(m.getModifiers()) || Modifier.isStatic(m.getModifiers())) continue; Long hash = entry.getKey(); if (addedMethods.contains(hash)) continue; addedMethods.add(hash); String aopReturnStr = (m.getReturnType().equals(CtClass.voidType)) ? "" : "return ($r)"; String args = "null"; if (m.getParameterTypes().length > 0) args = "$args"; String code = "{ " + " org.jboss.aop.advice.Interceptor[] aspects = instanceAdvisor.getInterceptors(); " + " org.jboss.aop.MethodInfo mi = new org.jboss.aop.MethodInfo(); " + " mi.setHash(" + hash.longValue() + "L);" + " org.jboss.aop.proxy.ProxyMethodInvocation invocation = new org.jboss.aop.proxy.ProxyMethodInvocation(this, mi, aspects); " + " invocation.setInstanceResolver(instanceAdvisor.getMetaData()); " + " invocation.setArguments(" + args + "); " + " " + aopReturnStr + " invocation.invokeNext(); " + "}"; CtMethod newMethod = CtNewMethod.make(m.getReturnType(), m.getName(), m.getParameterTypes(), m.getExceptionTypes(), code, proxy); newMethod.setModifiers(Modifier.PUBLIC); proxy.addMethod(newMethod); } SerialVersionUID.setSerialVersionUID(proxy); return proxy; } private static Class generateProxy(ClassPool pool, Class clazz, ProxyMixin[] mixins, boolean interceptWriteReplace) throws Exception { CtClass proxy = createProxyCtClass(pool, mixins, clazz, interceptWriteReplace); ProtectionDomain pd = clazz.getProtectionDomain(); Class proxyClass = TransformerCommon.toClass(proxy, pd); Map methodmap = ClassProxyFactory.getMethodMap(proxyClass); Field field = proxyClass.getDeclaredField("methodMap"); SecurityActions.setAccessible(field); field.set(null, methodmap); return proxyClass; } private static void populateMethodTables(HashMap advised, List ignoredHash, Class superclass) throws Exception { if (superclass == null) return; if (superclass.getName().equals("java.lang.Object")) return; Method[] declaredMethods = superclass.getDeclaredMethods(); for (int i = 0; i < declaredMethods.length; i++) { if (ClassAdvisor.isAdvisable(declaredMethods[i])) { //if a method is marked as a "volatile/bridge" method, we need to //ignore it and check that other implementations of that method // (in superclasses) are not added either. if(!java.lang.reflect.Modifier.isVolatile( declaredMethods[i].getModifiers())) { long hash = org.jboss.aop.util.MethodHashing.methodHash(declaredMethods[i]); if(!ignoredHash.contains(new Long(hash))) advised.put(new Long(hash), new MethodPersistentReference(declaredMethods[i], PersistentReference.REFERENCE_WEAK)); } else { long hash = org.jboss.aop.util.MethodHashing.methodHash(declaredMethods[i]); ignoredHash.add(new Long(hash)); } } } populateMethodTables(advised, ignoredHash, superclass.getSuperclass()); } public static HashMap methodMap(Class clazz) throws Exception { HashMap methods = new HashMap(); List ignoredHash = new ArrayList(); populateMethodTables(methods, ignoredHash, clazz); return methods; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/Proxy.java0000644000175000017500000000502411145122064031015 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import org.jboss.aop.InstanceAdvised; import org.jboss.aop.util.reference.MethodPersistentReference; import org.jboss.util.id.GUID; import java.io.ObjectStreamException; import java.util.Map; /** * @author Bill Burke * @version $Revision: 71276 $ */ public abstract class Proxy implements InstanceAdvised, java.io.Serializable, MethodMapped { private static final long serialVersionUID = -6040609385293748583L; public org.jboss.aop.InstanceAdvisor instanceAdvisor; public org.jboss.aop.proxy.ProxyMixin[] mixins; public Class[] interfaces; public GUID guid; public org.jboss.aop.InstanceAdvisor _getInstanceAdvisor() { return instanceAdvisor; } public void _setInstanceAdvisor(org.jboss.aop.InstanceAdvisor newAdvisor) { instanceAdvisor = newAdvisor; } public org.jboss.aop.joinpoint.InvocationResponse _dynamicInvoke(org.jboss.aop.joinpoint.Invocation invocation) throws Throwable { ((org.jboss.aop.joinpoint.InvocationBase) invocation).setInstanceResolver(instanceAdvisor.getMetaData()); org.jboss.aop.advice.Interceptor[] aspects = instanceAdvisor.getInterceptors(); return new org.jboss.aop.joinpoint.InvocationResponse(invocation.invokeNext(aspects)); } public Object writeReplace() throws ObjectStreamException { return new MarshalledInterfaceProxy(guid, interfaces, mixins, instanceAdvisor); } public abstract Map getMethodMap(); } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ProxyMethodInvocation.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/proxy/ProxyMethodInvocation.0000644000175000017500000000415311145122060033344 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.proxy; import org.jboss.aop.MethodInfo; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.joinpoint.MethodInvocation; import org.jboss.aop.util.reference.MethodPersistentReference; import java.lang.reflect.Method; /** * Comment * * @author Bill Burke * @version $Revision: 71276 $ */ public class ProxyMethodInvocation extends MethodInvocation { static final long serialVersionUID = 2451434088790560691L; private transient MethodMapped proxy; public ProxyMethodInvocation(MethodMapped mapped, MethodInfo info, Interceptor[] interceptors) { super(info, interceptors); this.proxy = mapped; } public ProxyMethodInvocation(MethodMapped mapped, Interceptor[] interceptors) { super(interceptors); this.proxy = mapped; } public ProxyMethodInvocation() { } public Method getMethod() { MethodPersistentReference ref = proxy.getMethodMap().get(new Long(methodHash)); return (Method)ref.get(); } public Method getActualMethod() { return getMethod(); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/AdvisorFactory.java0000644000175000017500000001443011145122056031454 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import javassist.CtClass; import org.jboss.aop.instrument.GeneratedAdvisorInstrumentor; import org.jboss.aop.instrument.InstrumentorEnum; import org.jboss.aop.instrument.InstrumentorFactory; import org.jboss.aop.util.logging.AOPLogger; /** * * * @author Staale W. Pedersen * @version $Revision */ public class AdvisorFactory { private static final AOPLogger logger = AOPLogger.getLogger(AdvisorFactory.class); protected static final int CLASS = 1; protected static final int OTHER_ADVISOR = 1000; //The jrockit aop advisor is in another jar which we should not depend on protected static int advisor = 0; protected static Constructor otherAdvisorConstructor; private static final Class[] NO_ARGS = new Class[0]; private static final Class[] CONSTRUCTOR_SIG = new Class[] {String.class, AspectManager.class}; public static void initialise(String property) { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("Passed in advisor: " + property); } if(property != null) { if (property.equals(ClassAdvisor.class.getName())) { advisor = CLASS; } else { try { //Context classloader is fine in this case since this is only called when initialising the main AspectManager Class otherAdvisorClass = SecurityActions.getContextClassLoader().loadClass(property); otherAdvisorConstructor = otherAdvisorClass.getConstructor(CONSTRUCTOR_SIG); } catch (ClassNotFoundException e) { throw new RuntimeException("Invalid advisor " + property + " was used"); } catch(NoSuchMethodException e) { throw new RuntimeException(property + " does not have a constructor with the expected signature"); } } } else { if (AspectManager.verbose && logger.isDebugEnabled()) { logger.debug("[debug] Defaulting advisor to: " + ClassAdvisor.class.getName()); } advisor = CLASS; } } public static ClassAdvisor getClassAdvisor(Class clazz, AspectManager am) { ClassAdvisor classAdvisor = getClassAdvisor(clazz.getName(), am, clazz); classAdvisor.setClazz(clazz); return classAdvisor; } public static ClassAdvisor getClassAdvisor(CtClass clazz, AspectManager am) { ClassAdvisor classAdvisor = getClassAdvisor(clazz.getName(), am, null); classAdvisor.setClassLoader(clazz.getClassPool().getClassLoader()); return classAdvisor; } private static ClassAdvisor getClassAdvisor(String className, AspectManager am, Class loadedClass) { if(advisor == CLASS) { if (loadedClass != null) { if (InstrumentorFactory.getInstrumentor() == InstrumentorEnum.GENERATED_ADVISOR) { //Generated advisors need to be initialised via the class itself try { final Method getAdvisor = loadedClass.getMethod(GeneratedAdvisorInstrumentor.GET_CLASS_ADVISOR, NO_ARGS); if (!getAdvisor.isAccessible()) { if (System.getSecurityManager() == null) { getAdvisor.setAccessible(true); } else { AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { getAdvisor.setAccessible(true); return null; } }); } } ClassAdvisor advisor = (ClassAdvisor)getAdvisor.invoke(null, null); if (advisor != null && advisor.getClazz() == loadedClass) { //Sub classes may not be instrumented, in which case we have the super class advisor here, which we don't want return advisor; } } catch (NoSuchMethodException e) { //This is an interface or the class is not advised, fall back to creating a normalClassAdvisor } catch (Exception e) { throw new RuntimeException(e); } } } return new ClassAdvisor(className, am); } else if(otherAdvisorConstructor != null) { try { return (ClassAdvisor) otherAdvisorConstructor.newInstance(new Object[] {className, am}); } catch (Exception e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Advisor is not set"); } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/SecurityActions.java0000644000175000017500000001527611145122054031654 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import javassist.CtClass; /** * * @author Kabir Khan * @version $Revision: 70823 $ */ class SecurityActions { interface SetAccessibleAction { void setAccessible(AccessibleObject accessibleObject); SetAccessibleAction PRIVILEGED = new SetAccessibleAction() { public void setAccessible(final AccessibleObject accessibleObject) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { accessibleObject.setAccessible(true); return null; } }); } catch (PrivilegedActionException e) { throw new RuntimeException("Error setting " + accessibleObject + " as accessible ", e.getException()); } } }; SetAccessibleAction NON_PRIVILEGED = new SetAccessibleAction() { public void setAccessible(AccessibleObject accessibleObject) { accessibleObject.setAccessible(true); } }; } static void setAccessible(AccessibleObject accessibleObject) { if (System.getSecurityManager() == null) { SetAccessibleAction.NON_PRIVILEGED.setAccessible(accessibleObject); } else { SetAccessibleAction.PRIVILEGED.setAccessible(accessibleObject); } } interface CtClassDebugWriteFileAction { void debugWriteFile(CtClass ctClass); CtClassDebugWriteFileAction PRIVILEGED = new CtClassDebugWriteFileAction() { public void debugWriteFile(final CtClass ctClass) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { ctClass.debugWriteFile(); return null; } }); } catch (PrivilegedActionException e) { //Not really a problem if we're not able to write the debug class file } } }; CtClassDebugWriteFileAction NON_PRIVILEGED = new CtClassDebugWriteFileAction() { public void debugWriteFile(CtClass ctClass) { ctClass.debugWriteFile(); } }; } static void debugWriteFile(CtClass ctClass) { if (System.getSecurityManager() == null) { CtClassDebugWriteFileAction.NON_PRIVILEGED.debugWriteFile(ctClass); } else { CtClassDebugWriteFileAction.PRIVILEGED.debugWriteFile(ctClass); } } public static class GetContextClassLoaderAction implements PrivilegedAction { public static GetContextClassLoaderAction INSTANCE = new GetContextClassLoaderAction(); public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } } static ClassLoader getContextClassLoader() { if (System.getSecurityManager() == null) return Thread.currentThread().getContextClassLoader(); else return AccessController.doPrivileged(GetContextClassLoaderAction.INSTANCE); } interface GetDeclaredConstructorsAction { Constructor[] getDeclaredConstructors(Class clazz); GetDeclaredConstructorsAction NON_PRIVILEGED = new GetDeclaredConstructorsAction() { public Constructor[] getDeclaredConstructors(Class clazz) { return clazz.getDeclaredConstructors(); }}; GetDeclaredConstructorsAction PRIVILEGED = new GetDeclaredConstructorsAction() { public Constructor[] getDeclaredConstructors(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction[]>() { public Constructor[] run() { return clazz.getDeclaredConstructors(); }}); }}; } static Constructor[] getDeclaredConstructors(Class clazz) { if (System.getSecurityManager() == null) { return GetDeclaredConstructorsAction.NON_PRIVILEGED.getDeclaredConstructors(clazz); } else { return GetDeclaredConstructorsAction.PRIVILEGED.getDeclaredConstructors(clazz); } } interface GetClassLoaderAction { ClassLoader getClassLoader(Class clazz); GetClassLoaderAction NON_PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(Class clazz) { return clazz.getClassLoader(); }}; GetClassLoaderAction PRIVILEGED = new GetClassLoaderAction() { public ClassLoader getClassLoader(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction() { public ClassLoader run() { return clazz.getClassLoader(); }}); }}; } static ClassLoader getClassLoader(Class clazz) { if (System.getSecurityManager() == null) { return GetClassLoaderAction.NON_PRIVILEGED.getClassLoader(clazz); } else { return GetClassLoaderAction.PRIVILEGED.getClassLoader(clazz); } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/MethodInterceptors.java0000644000175000017500000000366511145122066032350 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import gnu.trove.TLongObjectHashMap; /** * * @author Kabir Khan * @version $Revision: 69354 $ */ public class MethodInterceptors { Advisor advisor; TLongObjectHashMap infos = new TLongObjectHashMap(); public MethodInterceptors(Advisor advisor) { this.advisor = advisor; } public long[] keys() { return infos.keys (); } public MethodInfo getMethodInfo(long hash) { MethodMatchInfo info = getMatchInfo(hash); if (info != null) { return info.getInfo(); } return null; } public MethodMatchInfo getMatchInfo(long hash) { return (MethodMatchInfo)infos.get(hash); } public void put(long hash, MethodInfo info) { infos.put(hash, new MethodMatchInfo(advisor, info)); } public void clear() { infos.clear(); } public int size() { return infos.size(); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/FieldInfo.java0000644000175000017500000001415411145122060030352 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import org.jboss.aop.joinpoint.FieldJoinpoint; import org.jboss.aop.joinpoint.FieldAccess; import org.jboss.aop.joinpoint.Joinpoint; import org.jboss.aop.util.MethodHashing; /** * Comment * * @author Kabir Khan * @version $Revision$ */ public class FieldInfo extends JoinPointInfo implements FieldAccess { private int index; private Field advisedField; private Method wrapper; private boolean read; public FieldInfo() { } public FieldInfo(Advisor advisor, boolean read) { super(advisor, null); this.read = read; } public FieldInfo(Class clazz, int index, String fieldName, long wrapperHash, Advisor advisor, boolean read) { super(advisor, clazz); try { this.index = index; this.advisedField = (System.getSecurityManager() == null) ? GetDeclaredFieldAction.NON_PRIVILEGED.get(this, clazz, fieldName) : GetDeclaredFieldAction.PRIVILEGED.get(this, clazz, fieldName); this.wrapper = MethodHashing.findMethodByHash(clazz, wrapperHash); this.setAdvisor(advisor); this.read = read; } catch (Exception e) { throw new RuntimeException(e); } } /* * For copying */ private FieldInfo(FieldInfo other) { super(other); this.index = other.index; this.advisedField = other.advisedField; this.wrapper = other.wrapper; this.read = other.read; } protected Joinpoint internalGetJoinpoint() { return new FieldJoinpoint(advisedField); } public JoinPointInfo copy() { return new FieldInfo(this); } public String toString() { StringBuffer sb = new StringBuffer("Field "); sb.append(read ? " Read" : "Write"); sb.append("["); sb.append("field=" + advisedField); sb.append("]"); return sb.toString(); } public void setIndex(int index) { this.index = index; } public int getIndex() { return index; } public void setAdvisedField(Field advisedField) { this.advisedField = advisedField; } //Use getField instead @Deprecated public Field getAdvisedField() { return advisedField; } public Field getField() { return advisedField; } public void setWrapper(Method wrapper) { this.wrapper = wrapper; } public Method getWrapper() { return wrapper; } public void setRead(boolean read) { this.read = read; } public boolean isRead() { return read; } public T resolveAnnotation(Class annotation) { T val = super.resolveAnnotation(annotation); if (val != null) return val; if (getAdvisor() != null) { val = getAdvisor().resolveTypedAnnotation(advisedField, annotation); if (val != null) return val; } return null; } private Field doGet(Class clazz, String name)throws NoSuchFieldException { Field field = null; Class superClass = clazz; while (superClass != null) { try { field = superClass.getDeclaredField(name); break; } catch (NoSuchFieldException e) { } //Check super class superClass = superClass.getSuperclass(); } if (field == null) { throw new NoSuchFieldException("Cannot find field in " + clazz.getName() + " or any of its superclasses"); } return field; } interface GetDeclaredFieldAction { Field get(FieldInfo target, Class clazz, String name) throws NoSuchFieldException; GetDeclaredFieldAction PRIVILEGED = new GetDeclaredFieldAction() { public Field get(final FieldInfo target, final Class clazz, final String name) throws NoSuchFieldException { try { return AccessController.doPrivileged(new PrivilegedExceptionAction() { public Field run() throws Exception { return target.doGet(clazz, name); } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof NoSuchFieldException) { throw (NoSuchFieldException)ex; } throw new RuntimeException(ex); } } }; GetDeclaredFieldAction NON_PRIVILEGED = new GetDeclaredFieldAction() { public Field get(FieldInfo target, Class clazz, String name) throws NoSuchFieldException { return target.doGet(clazz, name);//clazz.getDeclaredField(name); } }; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/0000755000175000017500000000000011145122066030001 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/SystemClassLoader.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/SystemClassLoader0000644000175000017500000004337011145122064033332 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.security.cert.Certificate; import java.util.Enumeration; /** * A classloader that can be installed as the system classloader * to enable aop translation based on files in META-INF/jboss-aop.xml * in the classpath.

* * You will need the following jars in your classpath (log4j.jar is optional):

*

    *
  • jboss-aop.jar
  • *
  • javassist.jar
  • *
  • jboss-common.jar
  • *
* * Start the virtual machine with something like the following command: * *
 * java -Djava.system.class.loader=org.jboss.aop.standalone.SystemClassLoader my.Main
 * 
* * Implementation Detail: All access to non-jre classes must be done through reflection the * classes must be loaded using the loadLocally method. * * @todo The delegation for jre classes is important. Need to * figure out how to do this generically * @todo java security model, protection domain, etc. * @author Adrian Brock * @author Juha Lindfors * @version $Revision: 71279 $ */ public class SystemClassLoader extends ClassLoader { /** * Not yet installed as the system classloader */ private static final int NOT_INSTALLED = 0; /** * Installed as the system classloader */ private static final int INSTALLED = 1; /** * Installing the aspect manager */ private static final int INITIALIZING = 2; /** * Aspect manager install */ private static final int INITIALIZED = 3; /** * The current state */ private int state = NOT_INSTALLED; /** * Our parent, the default system classloader */ ClassLoader parent = null; /** * org.jboss.aop.AspectXmlDeployer.deployXML(java.util.URL url); */ Method deployXML; /** Translator.transform(ClassLoader loader, String name, * Class classBeingRedefined, ProtectionDomain pd, * byte[] classfileBuffer) */ Method transform; /** * static org.jboss.aop.AspectManager.instance(); */ Method instance; /** * The aspect manager; */ Object aspectManager; /** * Construct a new system classloader.

* * We cannot do much here, we need to avoid recursion * * @param parent the default system classloader */ public SystemClassLoader(ClassLoader parent) { super(parent); install(); } /** * Load a class, overridden to transform aop enhanced classes * and load non jre classes through this classloader. * * @param name the class name * @param resolve whether to resolve the class * @return the class * @throws ClassNotFoundException when there is no class */ public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // Have we already loaded the class? Class clazz = findLoadedClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return clazz; } // Is it a jre class? clazz = loadClassByDelegation(name); if (clazz != null) { if (resolve) resolveClass(clazz); return clazz; } // First non jre loadClass initializes initialize(); // Load the class try { ClassBytes origBytes = loadClassBytes(name); ClassBytes classBytes = new ClassBytes(); // If we are initialized check for aop translation if (state == INITIALIZED) { final Object[] args = {this, name, null, null, origBytes.bytes}; if (!name.startsWith("org.jboss.aop.")) { classBytes.bytes = (byte[]) transform.invoke(aspectManager, args); classBytes.protectionDomain = origBytes.protectionDomain; } } if (classBytes.bytes == null) classBytes = origBytes; // Define the class return defineClassFromBytes(name, classBytes, resolve); } catch (IOException ioe) { throw new ClassNotFoundException("Unable to load " + name, ioe); } catch (IllegalAccessException iae) { throw new Error(iae); } catch (InvocationTargetException ite) { throw new Error("Error transforming the class " + name, ite.getCause()); } } /** * Load the bytecode for a class */ protected ClassBytes loadClassBytes(String name) throws ClassNotFoundException, IOException { final String classFileName = name.replace('.', '/') + ".class"; final URL url = AccessController.doPrivileged(new PrivilegedAction() { public URL run() { return getParent().getResource(classFileName); } }); ProtectionDomain protectionDomain = null; InputStream in = null; if (url != null) { try { in = AccessController.doPrivileged(new PrivilegedExceptionAction() { public InputStream run() throws Exception { return url.openStream(); } }); } catch (PrivilegedActionException e) { throw new ClassNotFoundException(name, e); } String urlstring = url.toExternalForm(); URL urlCS = url; if (urlstring.startsWith("jar:")) { int i = urlstring.indexOf('!'); String cs = urlstring.substring(4, i); urlCS = new URL(cs); } else { int i = urlstring.indexOf(classFileName); if (i != -1) { String cs = urlstring.substring(0, i); urlCS = new URL(cs); } } CodeSource codeSource = new CodeSource(urlCS, (Certificate[]) null); protectionDomain = new ProtectionDomain(codeSource, null, this, null); } else { /* Try the system tmpdir/aopdynclasses, the default location the AOPClassPool writes dynamic class files to. */ try { in = AccessController.doPrivileged(new PrivilegedExceptionAction() { public InputStream run() throws Exception { String tmpdir = System.getProperty("java.io.tmpdir"); File aopdynclasses = new File(tmpdir, "aopdynclasses"); File classFile = new File(aopdynclasses, classFileName); return new FileInputStream(classFile); } }); } catch (PrivilegedActionException e) { throw new ClassNotFoundException(name, e); } } byte[][] bufs = new byte[8][]; int bufsize = 4096; for (int i = 0; i < 8; ++i) { bufs[i] = new byte[bufsize]; int size = 0; int len = 0; do { len = in.read(bufs[i], size, bufsize - size); if (len >= 0) size += len; else { byte[] result = new byte[bufsize - 4096 + size]; int s = 0; for (int j = 0; j < i; ++j) { System.arraycopy(bufs[j], 0, result, s, s + 4096); s = s + s + 4096; } System.arraycopy(bufs[i], 0, result, s, size); ClassBytes classBytes = new ClassBytes(); classBytes.bytes = result; classBytes.protectionDomain = protectionDomain; return classBytes; } } while (size < bufsize); bufsize *= 2; } throw new IOException("too much data loading class " + name); } /** * Define a class from the bytes * * @name the class to define * @param b the bytecode * @param resolve whether to resolve the class * @returns the class */ protected Class defineClassFromBytes(String name, ClassBytes bytes, boolean resolve) { definePackage(name); byte[] b = bytes.bytes; Class clazz = defineClass(name, b, 0, b.length, bytes.protectionDomain); if (resolve) resolveClass(clazz); return clazz; } /** * Define the package for the class if not already done * * @todo this properly * @param name the class name */ protected void definePackage(String className) { int i = className.lastIndexOf('.'); if (i == -1) return; try { definePackage(className.substring(0, i), null, null, null, null, null, null, null); } catch (IllegalArgumentException alreadyDone) { } } /** * Load a class using this classloader only * * @param name the class name * @return the class * @throws ClassNotFoundException when there is no class */ protected Class loadClassLocally(String name) throws ClassNotFoundException { try { ClassBytes bytes = loadClassBytes(name); return defineClassFromBytes(name, bytes, true); } catch (Throwable ex) { throw new ClassNotFoundException(name, ex); } } /** * Load jre classes from the parent classloader * * @param name the class name * @return the class * @throws ClassNotFoundException when there is no class */ protected Class loadClassByDelegation(String name) throws ClassNotFoundException { // FIXME: Only works for Sun for now if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("sun.") || name.startsWith("com.sun.") || name.startsWith("org.apache.xerces.") || name.startsWith("org.xml.sax.") || name.startsWith("org.w3c.dom.")) return getParent().loadClass(name); return null; } /** * Install the classloader, get reflection objects and load * classes using ourself. */ protected synchronized void install() { try { // AspectManager Class clazz = loadClassLocally("org.jboss.aop.AspectManager"); Class[] transformSig = {ClassLoader.class, String.class, Class.class, ProtectionDomain.class, byte[].class}; transform = clazz.getMethod("transform", transformSig); instance = clazz.getMethod("instance", new Class[0]); // AspectXmlLoader clazz = loadClassLocally("org.jboss.aop.AspectXmlLoader"); deployXML = clazz.getMethod("deployXML", new Class[]{URL.class}); /* // loadClassLocally("org.jboss.aop.Advisable"); loadClassLocally("org.jboss.aop.Advised"); // loadClassLocally("org.jboss.aop.Advisor"); loadClassLocally("org.jboss.aop.AlreadyAdvisedException"); // loadClassLocally("org.jboss.aop.AOPClassPool"); // loadClassLocally("org.jboss.aop.AspectManager"); loadClassLocally("org.jboss.aop.AspectNotificationHandler"); // loadClassLocally("org.jboss.aop.AspectXmlLoader"); // loadClassLocally("org.jboss.aop.ClassAdvisor"); loadClassLocally("org.jboss.aop.ClassInstanceAdvisor"); // loadClassLocally("org.jboss.aop.ClassMetaData"); // loadClassLocally("org.jboss.aop.ClassMetaDataLoader"); loadClassLocally("org.jboss.aop.CLClassPath"); loadClassLocally("org.jboss.aop.ConstructorComparator"); loadClassLocally("org.jboss.aop.ConstructorConfig"); loadClassLocally("org.jboss.aop.ConstructorInvocation"); loadClassLocally("org.jboss.aop.ConstructorMetaData"); loadClassLocally("org.jboss.aop.CtConstructorComparator"); loadClassLocally("org.jboss.aop.CtFieldComparator"); loadClassLocally("org.jboss.aop.CtMethodComparator"); loadClassLocally("org.jboss.aop.Dispatcher"); loadClassLocally("org.jboss.aop.FieldComparator"); loadClassLocally("org.jboss.aop.FieldInvocation"); loadClassLocally("org.jboss.aop.FieldMetaData"); loadClassLocally("org.jboss.aop.GenericInterceptorFactory"); // loadClassLocally("org.jboss.aop.InstanceAdvised"); // loadClassLocally("org.jboss.aop.InstanceAdvisor"); loadClassLocally("org.jboss.aop.Instrumentor"); // loadClassLocally("org.jboss.aop.InterceptorFactory"); loadClassLocally("org.jboss.aop.InterceptorFilter"); // loadClassLocally("org.jboss.aop.Interceptor"); // loadClassLocally("org.jboss.aop.ClassPointcut"); // loadClassLocally("org.jboss.aop.InterceptorStack"); // loadClassLocally("org.jboss.aop.IntroductionPointcut"); loadClassLocally("org.jboss.aop.InvocationFilterInterceptor"); loadClassLocally("org.jboss.aop.Invocation"); loadClassLocally("org.jboss.aop.InvocationResponse"); loadClassLocally("org.jboss.aop.InvocationType"); loadClassLocally("org.jboss.aop.Loader"); loadClassLocally("org.jboss.aop.MarshalledValueInputStream"); loadClassLocally("org.jboss.aop.MarshalledValue"); loadClassLocally("org.jboss.aop.MarshalledValueOutputStream"); // loadClassLocally("org.jboss.aop.MetaDataResolver"); loadClassLocally("org.jboss.aop.MethodComparator"); loadClassLocally("org.jboss.aop.MethodConfig"); loadClassLocally("org.jboss.aop.MethodHashing"); loadClassLocally("org.jboss.aop.MethodInvocation"); loadClassLocally("org.jboss.aop.MethodMetaData"); loadClassLocally("org.jboss.aop.NotAdvisableException"); loadClassLocally("org.jboss.aop.NotAdvisedException"); loadClassLocally("org.jboss.aop.PayloadKey"); loadClassLocally("org.jboss.aop.SimpleClassMetaData"); loadClassLocally("org.jboss.aop.SimpleClassMetaDataLoader"); loadClassLocally("org.jboss.aop.SimpleMetaData"); loadClassLocally("org.jboss.aop.SingletonInterceptorFactory"); loadClassLocally("org.jboss.aop.StandaloneClassLoader"); loadClassLocally("org.jboss.aop.ThreadMetaData"); loadClassLocally("org.jboss.aop.proxy.ClassProxyFactory"); loadClassLocally("org.jboss.aop.proxy.ClassProxy"); loadClassLocally("org.jboss.aop.proxy.ClassProxyTemplate"); loadClassLocally("org.jboss.aop.proxy.DynamicProxyIH"); // loadClassLocally("org.jboss.aop.proxy.ProxyAdvisor"); loadClassLocally("org.jboss.util.loading.Translatable"); loadClassLocally("javassist.compiler.CompileError"); loadClassLocally("javassist.bytecode.BadBytecode"); loadClassLocally("javassist.bytecode.ClassFile"); loadClassLocally("javassist.bytecode.ConstPool"); */ state = INSTALLED; } catch (Throwable t) { t.printStackTrace(); throw new Error("Error initializing system classloader", t); } } /** * Initialize the aspect manager and load the static aspects */ protected synchronized void initialize() { // Only one thread will initialize if (state != INSTALLED) return; state = INITIALIZING; // Set the context classloader to ourselves Thread.currentThread().setContextClassLoader(this); // Set up the aspect manager, once this is done we // are ready to go try { try { System.setProperty("jboss.aop.optimized", "false"); aspectManager = instance.invoke(null, new Object[0]); } catch (InvocationTargetException ite) { throw ite.getCause(); } state = INITIALIZED; } catch (Throwable t) { t.printStackTrace(); throw new Error("Error installing aspect manager", t); } // Install the aop configurations try { Enumeration enumeration = getParent().getResources("META-INF/jboss-aop.xml"); while (enumeration.hasMoreElements()) { URL url = enumeration.nextElement(); deployXML.invoke(null, new Object[]{url}); } } catch (Throwable t) { t.printStackTrace(); throw new Error("Error deploying aop configrations", t); } } /** * ClassBytes. */ private static class ClassBytes { public ProtectionDomain protectionDomain; public byte[] bytes; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/StandaloneClassPool.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/StandaloneClassPo0000644000175000017500000000576611145122064033315 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import javassist.scopedpool.ScopedClassPoolRepository; import org.jboss.aop.classpool.AOPClassPool; /** * Comment * * @author Bill Burke * @version $Revision: 46253 $ * @deprecated Will be removed when Javassist is upgraded past 3.0 beta2 */ public class StandaloneClassPool extends AOPClassPool { public StandaloneClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { super(cl, src, repository); } public StandaloneClassPool(ClassPool src, ScopedClassPoolRepository repository) { super(src, repository); } public Class toClass(CtClass ctClass) throws CannotCompileException { try { byte[] b = ctClass.toBytecode(); Class cl = Class.forName("java.lang.ClassLoader"); java.lang.reflect.Method method = cl.getDeclaredMethod("defineClass", new Class[]{String.class, byte[].class, int.class, int.class}); method.setAccessible(true); Object[] args = new Object[]{ctClass.getName(), b, new Integer(0), new Integer(b.length)}; Class clazz = (Class) method.invoke(getClassLoader(), args); method.setAccessible(false); return clazz; } catch (RuntimeException e) { throw e; } catch (java.lang.reflect.InvocationTargetException e) { throw new CannotCompileException(e); } catch (Exception e) { throw new CannotCompileException(e); } } public synchronized CtClass getLocally(String classname) throws NotFoundException { return super.getLocally(classname); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/AOPTransformer.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/AOPTransformer.ja0000644000175000017500000000721611145122054033162 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import org.jboss.aop.AspectManager; import org.jboss.aop.instrument.JoinPointGenerator; /** * Comment * * @author Bill Burke * @version $Revision: 44099 $ */ public class AOPTransformer implements ClassFileTransformer { public boolean isNonAdvisableClassName(String classname) { return (classname.startsWith("org.jboss.aop.") || classname.endsWith("$aop") || classname.startsWith("javassist") || classname.startsWith("org.jboss.util.") || classname.startsWith("gnu.trove.") || classname.startsWith("EDU.oswego.cs.dl.util.concurrent.") || // System classes classname.startsWith("org.apache.crimson") || classname.startsWith("org.apache.xalan") || classname.startsWith("org.apache.xml") || classname.startsWith("org.apache.xpath") || classname.startsWith("org.ietf.") || classname.startsWith("org.omg.") || classname.startsWith("org.w3c.") || classname.startsWith("org.xml.sax.") || classname.startsWith("sunw.") || classname.startsWith("sun.") || classname.startsWith("java.") || classname.startsWith("javax.") || classname.startsWith("com.sun.") || classname.startsWith("$Proxy") || classname.contains('.' + JoinPointGenerator.JOINPOINT_CLASS_PREFIX) ); } public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { className = className.replace('/', '.'); try { if (classBeingRedefined != null || isNonAdvisableClassName(className)) { return null; } return aspectTransform(className, loader, classBeingRedefined, protectionDomain, classfileBuffer); } finally { } } private byte[] aspectTransform(String className, ClassLoader loader, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { try { //Make sure that we use the correct classloader, in order to get the correct domain if it is a scoped loader return AspectManager.instance(loader).transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); } catch (Exception e) { throw new RuntimeException(e); } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/Package.java0000644000175000017500000000563511145122064032206 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; /** * Comment * * @author Bill Burke * @version $Revision: 84101 $ */ public class Package implements java.io.Serializable { static final long serialVersionUID = 6188655039267365373L; public HashMap advisors = new HashMap(); public HashMap packages = new HashMap(); public String name; public Package(String name) { this.name = name; } static void parse(AspectManager manager, Class clazz, Package root) { Advisor advisor = manager.findAdvisor(clazz); StringTokenizer tokenizer = new StringTokenizer(clazz.getName(), "."); while (tokenizer.hasMoreTokens()) { String pkgName = tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) { Package subpkg = root.packages.get(pkgName); if (subpkg == null) { subpkg = new Package(pkgName); root.packages.put(pkgName, subpkg); } root = subpkg; } else { root.advisors.put(pkgName, advisor); } } } public static Package aopClassMap() { return aopClassMap(AspectManager.getTopLevelAspectManager()); } public static Package aopClassMap(AspectManager manager) { Map, WeakReference> advisors = manager.getAdvisors(); Iterator> it = advisors.keySet().iterator(); Package root = new Package("classes"); while (it.hasNext()) { Class clazz = it.next(); parse(manager, clazz, root); } return root; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/Agent.java0000644000175000017500000000441611145122062031703 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import org.jboss.aop.AspectManager; import org.jboss.aop.DynamicAOPStrategy; import org.jboss.aop.HotSwapStrategy; import java.lang.instrument.Instrumentation; /** * Comment * * @author Bill Burke * @version $Revision: 46253 $ */ public class Agent { private static Instrumentation instrumentation; public static Instrumentation getInstrumentation() { return instrumentation; } public static void premain(String agentArgs, Instrumentation inst) { instrumentation = inst; StandaloneClassPoolFactory factory = new StandaloneClassPoolFactory(); AspectManager.setClassPoolFactory(factory); // necessary for configuration AspectManager.instance(); if (agentArgs != null && agentArgs.indexOf("-hotSwap") != -1) { // setting dynamic aop strategy: hot swap classes through InstrumentationAdapter DynamicAOPStrategy strategy = new HotSwapStrategy(new InstrumentationAdapter(inst)); AspectManager.instance().setDynamicAOPStrategy(strategy); AspectManager.setPrune(false); // no prune } inst.addTransformer(new AOPTransformer()); } }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/Compiler.java0000644000175000017500000003176311145122054032425 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import javassist.bytecode.ClassFile; import org.jboss.aop.AspectManager; import org.jboss.aop.Deployment; import org.jboss.aop.instrument.TransformationException; /** * takes jar or class files and adds needed jboss bytecode * * @author Bill Burke * @version $Revision: 79707 $ */ public class Compiler { private FileFilter classFileFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }; private FileFilter directoryFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory(); } }; public boolean verbose = false; public boolean suppress = true; public boolean optimized = true; public boolean isJarFile(File src) { return (src.isFile() && (src.getName().toLowerCase().endsWith(".jar") || src.getName().toLowerCase().endsWith(".zip")) ); } public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); Compiler c = new Compiler(); try { c.compile(args); } catch (Exception e) { if (c.verbose) throw e; if (e instanceof TransformationException) { System.exit(1); } throw e; } System.out.println("Build Successful: " + (System.currentTimeMillis() -start) + " ms"); } public void usage() { System.err.println("Usage: aopc [-cp ] [-classpath ] [-report] [-noopt] [-verbose] [-aoppath ]

+"); } // Make public and static so that transformers can locate it to do work // transformers may generate class files and they need to determine // file locations and such. This will also be used as a flag to tell // transformers whether they are in compile or load-time mode. public static URLClassLoader loader; public void compile(String[] args) throws Exception { if (args.length == 0) { usage(); System.exit(1); return; } ArrayList paths = new ArrayList(); ArrayList files = new ArrayList(); boolean report = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-verbose")) { verbose = true; continue; } else if (args[i].equals("-suppress")) { suppress = true; continue; } else if (args[i].equals("-noopt")) { optimized = false; continue; } else if (args[i].equals("-report")) { report = true; continue; } else if (args[i].equals("-cp") || args[i].equals("-classpath")) { if (i + 1 > args.length - 1) { usage(); System.exit(1); return; } i++; StringTokenizer tokenizer = new StringTokenizer(args[i], File.pathSeparator); while (tokenizer.hasMoreTokens()) { String cpath = tokenizer.nextToken(); File f = new File(cpath); // use toURI().toURL() because of bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4273532 paths.add(f.toURI().toURL()); } continue; } else if (args[i].equals("-aoppath")) { System.setProperty("jboss.aop.path", args[++i]); continue; } else if (args[i].equals("-aopclasspath")) { System.setProperty("jboss.aop.class.path", args[++i]); continue; } else if (args[i].equals("--SOURCEPATH")) { addFilesFromSourcePathFile(files, args[++i]); continue; } File f = new File(args[i]).getCanonicalFile(); files.add(f); } URL[] urls = paths.toArray(new URL[paths.size()]); loader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); Thread.currentThread().setContextClassLoader(loader); Deployment.searchClasspath = true; // turn on dynamic finding of DDs AspectManager.verbose = verbose; AspectManager.suppressReferenceErrors = suppress; AspectManager.optimize = optimized; AspectManager.instance(); if (report) { for (int i = 0; i < files.size(); i++) { File f = files.get(i); if (f.isDirectory()) { loadDirectory(f); } else if (classFileFilter.accept(f)) { loadFile(f); } else { if (verbose) System.out.println("[aopc] " + f + " is neither a java class or a directory"); } } FileOutputStream reportFile = new FileOutputStream("aop-report.xml"); reportFile.write(XmlReport.toXml().getBytes()); reportFile.close(); } else { //Add all the classes to compile for (int i = 0 ; i < files.size() ; i++) { File f = files.get(i); if (f.isDirectory()) { addDirectory(f); } else if (classFileFilter.accept(f)) { addFile(f); } else { if (verbose) System.out.println("[aopc] " + f + " is neither a java class or a directory"); } } //Compile each class for (String className : classesToCompile.keySet()) { CompilerClassInfo info = classesToCompile.get(className); compileFile(info); } } } private HashMap classesToCompile = new HashMap(); private void addDirectory(File dir) throws Exception { File[] directories = dir.listFiles(directoryFilter); File[] classFiles = dir.listFiles(classFileFilter); for (int i = 0; i < classFiles.length; i++) { addFile(classFiles[i]); } for (int i = 0; i < directories.length; i++) { addDirectory(directories[i]); } } private void loadDirectory(File dir) throws Exception { File[] directories = dir.listFiles(directoryFilter); File[] classFiles = dir.listFiles(classFileFilter); for (int i = 0; i < classFiles.length; i++) { loadFile(classFiles[i]); } for (int i = 0; i < directories.length; i++) { loadDirectory(directories[i]); } } private void addFile(File file)throws Exception { int index = file.getName().indexOf('$'); if (index != -1) { String fileName = file.getName().substring(0, index) + ".class"; File superClassFile = new File(fileName); // checking last modified date is not enough // because these values can differ in some miliseconds sometimes if (superClassFile.lastModified() > file.lastModified() // so, check this class has been recompiled and, hence, // is not Advised anymore && !loadFile(superClassFile)) { file.delete(); return; } } ClassFile cf = createClassFile(file); String className = cf.getName(); String superClassName = cf.getSuperclass(); CompilerClassInfo info = new CompilerClassInfo(file, className, superClassName); classesToCompile.put(className, info); } private ClassFile createClassFile(final File file) throws Exception{ DataInputStream is = new DataInputStream(new FileInputStream(file)); ClassFile cf = new ClassFile(is); is.close(); return cf; } private void addFilesFromSourcePathFile(ArrayList files, String sourcePathFile) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(new File(sourcePathFile).getCanonicalFile())); String fileName = reader.readLine(); while (fileName != null) { files.add(new File(fileName).getCanonicalFile()); fileName = reader.readLine(); } } catch (Exception e) { try { reader.close(); } catch (IOException e1) { } throw new RuntimeException(e); } } /** * Loads the file and, if it is an advised class, sets its advisor field as * accessible. * @param file the file of the class to be loaded * @return {@code true} is {@code file} contains an advised class. */ public boolean loadFile(File file) throws Exception { DataInputStream is = new DataInputStream(new FileInputStream(file)); ClassFile cf = new ClassFile(is); is.close(); Class clazz = loader.loadClass(cf.getName()); if (org.jboss.aop.Advised.class.isAssignableFrom(clazz)) { Field f = clazz.getDeclaredField("aop$classAdvisor$aop"); f.setAccessible(true); f.get(null); return true; } return false; } public void compileFile(CompilerClassInfo info) throws Exception { if (info.isCompiled()) { return; } if (info.getSuperClassName() != null) { CompilerClassInfo superInfo = classesToCompile.get(info.getSuperClassName()); if (superInfo != null) { compileFile(superInfo); } } //System.err.println("[classname] " + className); URL classUrl = loader.getResource(info.getClassName().replace('.', '/') + ".class"); if (classUrl == null) { System.out.println("[warning] Unable to find " + info.getFile() + " within classpath. Make sure all transforming classes are within classpath."); return; } File classUrlFile = new File(URLDecoder.decode(classUrl.getFile(), "UTF-8")); File infoFile = new File(URLDecoder.decode(info.getFile().toString(), "UTF-8")); if (!classUrlFile.equals(infoFile)) { System.out.println("[warning] Trying to compile " + info.getFile() + " and found it also within " + classUrl.getFile() + " will not proceed. "); return; } byte[] bytes = AspectManager.instance().transform(loader, info.getClassName(), null, null, null); if (bytes == null) { if (verbose) System.out.println("[no comp needed] " + info.getFile()); return; } FileOutputStream os = new FileOutputStream(infoFile); os.write(bytes); os.close(); info.setCompiled(true); if (verbose) System.out.println("[compiled] " + info.getFile()); } private class CompilerClassInfo { File file; String className; String superClassName; boolean compiled; CompilerClassInfo(File file, String className, String superClassName) { this.file = file; this.className = className; this.superClassName = superClassName; } public File getFile() { return file; } public boolean isCompiled() { return compiled; } public void setCompiled(boolean compiled) { this.compiled = compiled; } public String getClassName() { return className; } public String getSuperClassName() { return superClassName; } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/XmlReport.java0000644000175000017500000005277311145122060032610 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import gnu.trove.TLongObjectHashMap; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.CallerConstructorInfo; import org.jboss.aop.CallerMethodInfo; import org.jboss.aop.ClassAdvisor; import org.jboss.aop.MethodInfo; import org.jboss.aop.advice.AbstractAdvice; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.CFlowInterceptor; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.metadata.ConstructorMetaData; import org.jboss.aop.metadata.FieldMetaData; import org.jboss.aop.metadata.MetaDataResolver; import org.jboss.aop.metadata.MethodMetaData; import org.jboss.aop.metadata.SimpleMetaData; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; /** * Comment * * @author Bill Burke * @version $Revision: 71279 $ */ public class XmlReport { public static String toXml() { Package root = Package.aopClassMap(); StringWriter writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); pw.println(""); pw.println(""); outputPackage(1, pw, root); outputUnboundBindings(1, pw); pw.println(""); pw.flush(); return writer.toString(); } private static String getIndent(int indent) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < indent; i++) { sb.append(" "); } return sb.toString(); } public static void indenter(Writer w, int indent) { try { w.write(getIndent(indent)); } catch (IOException e) { throw new RuntimeException("IOException in indent", e); } } protected static String simpleType(Class type) { Class ret = type; if (ret.isArray()) { Class arr = ret; String array = ""; while (arr.isArray()) { array += "[]"; arr = arr.getComponentType(); } return arr.getName(); } return ret.getName(); } public static void outputPackage(int indent, PrintWriter pw, Package root) { Iterator> it1 = root.packages.entrySet().iterator(); while (it1.hasNext()) { Map.Entry entry = it1.next(); String pkgName = entry.getKey(); indenter(pw, indent); pw.println(""); Package p = entry.getValue(); outputPackage(indent + 1, pw, p); indenter(pw, indent); pw.println(""); } Iterator> it2 = root.advisors.entrySet().iterator(); while (it2.hasNext()) { Map.Entry entry = it2.next(); String classname = entry.getKey(); indenter(pw, indent); pw.println(""); ClassAdvisor advisor = (ClassAdvisor) entry.getValue(); outputAdvisor(indent + 1, pw, advisor, classname); indenter(pw, indent); pw.println(""); } } public static void outputAdvisor(int indent, PrintWriter pw, ClassAdvisor advisor, String baseName) { ArrayList introductions = advisor.getInterfaceIntroductions(); if (introductions != null && introductions.size() > 0) { indenter(pw, indent); pw.println(""); indent++; for (int i = 0; i < introductions.size(); i++) { InterfaceIntroduction pointcut = introductions.get(i); indenter(pw, indent); pw.println(""); indent++; String[] intfs = pointcut.getInterfaces(); ArrayList mixins = pointcut.getMixins(); if (intfs != null && intfs.length > 0) { //Show interfaces for (int j = 0; j < intfs.length; j++) { indenter(pw, indent); pw.println(""); } } else if (mixins != null && mixins.size() > 0) { //Show mixins for (int j = 0; j < mixins.size(); j++) { InterfaceIntroduction.Mixin mixin = mixins.get(j); String[] mixifs = mixin.getInterfaces(); for (int k = 0; k < mixifs.length; k++) { indenter(pw, indent); pw.println(""); } indenter(pw, indent); pw.println(""); } } indent--; indenter(pw, indent); pw.println(""); } indent--; indenter(pw, indent); pw.println(""); } indenter(pw, indent); pw.println(""); indent++; for (int i = 0; i < advisor.getConstructors().length; i++) { Constructor con = advisor.getConstructors()[i]; Interceptor[] chain = advisor.getConstructorInfos()[i].getInterceptors(); HashMap methodCallers = advisor.getMethodCalledByConInterceptors()[i]; HashMap conCallers = advisor.getConCalledByConInterceptors()[i]; if ((chain != null && chain.length > 0) || methodCallers != null || conCallers != null) { indenter(pw, indent); pw.println(""); if (chain != null && chain.length > 0) { outputChain(indent + 1, pw, chain); } if (methodCallers != null) { outputMethodCallers(indent + 1, pw, methodCallers); } if (conCallers != null) { outputConCallers(indent + 1, pw, conCallers); } indenter(pw, indent); pw.println(""); } } indent--; indenter(pw, indent); pw.println(""); indenter(pw, indent); pw.println(""); indent++; for (int i = 0; i < advisor.getAdvisedFields().length; i++) { Field f = advisor.getAdvisedFields()[i]; Interceptor[] chain = advisor.getFieldReadInfos()[i].getInterceptors(); if (chain != null && chain.length > 0) { indenter(pw, indent); pw.println(""); outputChain(indent + 1, pw, chain); indenter(pw, indent); pw.println(""); } } indent--; indenter(pw, indent); pw.println(""); indenter(pw, indent); pw.println(""); indent++; for (int i = 0; i < advisor.getAdvisedFields().length; i++) { Field f = advisor.getAdvisedFields()[i]; Interceptor[] chain = advisor.getFieldReadInfos()[i].getInterceptors(); if (chain != null && chain.length > 0) { indenter(pw, indent); pw.println(""); outputChain(indent + 1, pw, chain); indenter(pw, indent); pw.println(""); } } indent--; indenter(pw, indent); pw.println(""); indenter(pw, indent); pw.println(""); indent++; long[] keys = advisor.getMethodInterceptors().keys(); for (int i = 0; i < keys.length; i++) { long key = keys[i]; MethodInfo method = (MethodInfo) advisor.getMethodInterceptors().get(key); @SuppressWarnings("unchecked") HashMap methodCallers = (HashMap) advisor.getMethodCalledByMethodInterceptors().get(key); @SuppressWarnings("unchecked") HashMap conCallers = (HashMap) advisor.getConCalledByMethodInterceptors().get(key); if (method == null && methodCallers == null) continue; if (method != null && methodCallers == null && (method.getInterceptors() == null || method.getInterceptors().length < 1)) continue; indenter(pw, indent); pw.println(""); if (method != null) { Interceptor[] chain = method.getInterceptors(); if (chain != null && chain.length > 0) { outputChain(indent + 1, pw, chain); } } if (methodCallers != null) { outputMethodCallers(indent + 1, pw, methodCallers); } if (conCallers != null) { outputConCallers(indent + 1, pw, conCallers); } indenter(pw, indent); pw.println(""); } indent--; indenter(pw, indent); pw.println(""); outputMetadata(indent, pw, advisor); } public static void outputMethodCallers(int indent, PrintWriter pw, HashMap called) { indenter(pw, indent); pw.println(""); indent++; Iterator it = called.values().iterator(); while (it.hasNext()) { TLongObjectHashMap map = it.next(); Object[] values = map.getValues(); for (int i = 0; i < values.length; i++) { CallerMethodInfo caller = (CallerMethodInfo) values[i]; indenter(pw, indent); if (caller.getInterceptors() != null) { pw.println(""); outputChain(indent + 1, pw, caller.getInterceptors()); indenter(pw, indent); pw.println(""); } else { pw.println(""); } } } indent--; indenter(pw, indent); pw.println(""); } public static void outputConCallers(int indent, PrintWriter pw, HashMap called) { indenter(pw, indent); pw.println(""); indent++; Iterator it = called.values().iterator(); while (it.hasNext()) { TLongObjectHashMap map = it.next(); Object[] values = map.getValues(); for (int i = 0; i < values.length; i++) { CallerConstructorInfo caller = (CallerConstructorInfo) values[i]; indenter(pw, indent); if (caller.getInterceptors() != null) { pw.println(""); outputChain(indent + 1, pw, caller.getInterceptors()); indenter(pw, indent); pw.println(""); } else { pw.println(""); } } } indent--; indenter(pw, indent); pw.println(""); } public static void outputChain(int indent, PrintWriter pw, Interceptor[] chain) { indenter(pw, indent); pw.println(""); indent++; for (int i = 0; i < chain.length; i++) { if (chain[i] instanceof AbstractAdvice) { indenter(pw, indent); pw.println(""); } else if (chain[i] instanceof CFlowInterceptor) { indenter(pw, indent); pw.println(""); } else { indenter(pw, indent); pw.println(""); } } indent--; indenter(pw, indent); pw.println(""); } public static void outputUnboundBindings(int indent, PrintWriter pw) { boolean first = true; for (AdviceBinding binding : AspectManager.instance().getBindings().values()) { if (!binding.hasAdvisors()) { if (first) { first = false; indenter(pw, indent); pw.println(""); indent++; } indenter(pw, indent); pw.print(""); } } if (!first) { indent--; indenter(pw, indent); pw.println(""); } } public static void outputMetadata(int indent, PrintWriter pw, ClassAdvisor advisor) { StringWriter sw = new StringWriter(); PrintWriter metaWriter = new PrintWriter(sw); StringBuffer sb = new StringBuffer(); sb.append(getDefaultMetadataXml(indent, metaWriter, advisor)); sb.append(getClassMetadataXml(indent, metaWriter, advisor)); sb.append(getConstructorMetadataXml(indent, pw, advisor)); sb.append(getMethodMetadataXml(indent, pw, advisor)); sb.append(getFieldMetadataXml(indent, pw, advisor)); //sb.append(); if (sb.length() > 0) { indenter(pw, indent); pw.println(""); pw.print(sb.toString()); indenter(pw, indent); pw.println(""); } } public static String getDefaultMetadataXml(int indent, PrintWriter pw, ClassAdvisor advisor) { SimpleMetaData metadata = advisor.getDefaultMetaData(); indent++; StringBuffer xml = getMetadataXml(indent, advisor, metadata); if (xml != null) { xml.insert(0, getIndent(indent) + "\r\n"); xml.append(getIndent(indent) + "\r\n"); return xml.toString(); } indent--; return ""; } public static String getClassMetadataXml(int indent, PrintWriter pw, ClassAdvisor advisor) { SimpleMetaData metadata = advisor.getClassMetaData(); indent++; StringBuffer xml = getMetadataXml(indent, advisor, metadata); if (xml != null) { xml.insert(0, getIndent(indent) + "\r\n"); xml.append(getIndent(indent) + "\r\n"); return xml.toString(); } indent--; return ""; } public static String getFieldMetadataXml(int indent, PrintWriter pw, ClassAdvisor advisor) { FieldMetaData fieldMetaData = advisor.getFieldMetaData(); StringBuffer xml = new StringBuffer(); indent++; for (Iterator it = fieldMetaData.getFields(); it.hasNext();) { String field = it.next(); org.jboss.aop.metadata.SimpleMetaData fieldData = fieldMetaData.getFieldMetaData(field); indent++; indent++; StringBuffer sb = getMetadataXml(indent, advisor, fieldData); indent--; indent--; if (sb != null) { indent++; xml.append(getIndent(indent) + "" + "\r\n"); xml.append(sb); xml.append(getIndent(indent) + "" + "\r\n"); indent--; } } if (xml.length() > 0) { xml.insert(0, getIndent(indent) + "" + "\r\n"); xml.append(getIndent(indent) + "" + "\r\n"); } indent--; return xml.toString(); } public static String getConstructorMetadataXml(int indent, PrintWriter pw, ClassAdvisor advisor) { ConstructorMetaData constructorMetaData = advisor.getConstructorMetaData(); StringBuffer xml = new StringBuffer(); indent++; for (Iterator it = constructorMetaData.getConstructors(); it.hasNext();) { String constructor = it.next(); org.jboss.aop.metadata.SimpleMetaData constructorData = constructorMetaData.getConstructorMetaData(constructor); indent++; indent++; StringBuffer sb = getMetadataXml(indent, advisor, constructorData); indent--; indent--; if (sb != null) { indent++; xml.append(getIndent(indent) + "" + "\r\n"); xml.append(sb); xml.append(getIndent(indent) + "" + "\r\n"); indent--; } } if (xml.length() > 0) { xml.insert(0, getIndent(indent) + "" + "\r\n"); xml.append(getIndent(indent) + "" + "\r\n"); } indent--; return xml.toString(); } public static String getMethodMetadataXml(int indent, PrintWriter pw, ClassAdvisor advisor) { MethodMetaData methodMetaData = advisor.getMethodMetaData(); StringBuffer xml = new StringBuffer(); indent++; for (Iterator it = methodMetaData.getMethods(); it.hasNext();) { String method = it.next(); org.jboss.aop.metadata.SimpleMetaData methodData = methodMetaData.getMethodMetaData(method); indent++; indent++; StringBuffer sb = getMetadataXml(indent, advisor, methodData); indent--; indent--; if (sb != null) { indent++; xml.append(getIndent(indent) + "" + "\r\n"); xml.append(sb); xml.append(getIndent(indent) + "" + "\r\n"); indent--; } } if (xml.length() > 0) { xml.insert(0, getIndent(indent) + "" + "\r\n"); xml.append(getIndent(indent) + "" + "\r\n"); } indent--; return xml.toString(); } public static StringBuffer getMetadataXml(int indent, ClassAdvisor advisor, SimpleMetaData metadata) { StringWriter sw = new StringWriter(); HashSet tags = metadata.tags(); if (tags.size() == 0) { return null; } for (Iterator tagsIt = tags.iterator(); tagsIt.hasNext();) { String tag = (String) tagsIt.next(); HashMap groupAttrs = metadata.tag(tag); indent++; indenter(sw, indent); sw.write("" + "\r\n"); indent++; if (groupAttrs == null) { continue; } boolean hasValues = false; for (Iterator> attrsIt = groupAttrs.entrySet().iterator(); attrsIt.hasNext();) { Map.Entry entry = attrsIt.next(); String attr = (String) entry.getKey(); if (!attr.equals(MetaDataResolver.EMPTY_TAG)) { hasValues = true; SimpleMetaData.MetaDataValue value = entry.getValue(); indenter(sw, indent); sw.write("" + "\r\n"); indent++; indenter(sw, indent); sw.write("" + value.value.getClass().getName() + "" + "\r\n"); indenter(sw, indent); sw.write("" + value.value.toString() + "" + "\r\n"); indenter(sw, indent); sw.write("" + value.type + "" + "\r\n"); indent--; indenter(sw, indent); sw.write("" + "\r\n"); } } if (!hasValues) { indenter(sw, indent); sw.write("" + "\r\n"); } indent--; indenter(sw, indent); sw.write("" + "\r\n"); indent--; } return sw.getBuffer(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/InstrumentationAdapter.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/InstrumentationAd0000644000175000017500000000613611145122066033402 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import java.lang.instrument.ClassDefinition; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; import java.util.ArrayList; import java.util.Collection; import org.jboss.aop.instrument.HotSwapper; /** * This class is an adapter to java.lang.instrument.Instrumentation * and is used to enable hot swap in JBoss AOP through Java 5 agents. * * @author Flavia Rainone */ class InstrumentationAdapter implements HotSwapper { private Instrumentation instrumentation; // delegate private Collection classDefinitions; /** * Constructor. * @param instrumentation */ public InstrumentationAdapter(Instrumentation instrumentation) { this.instrumentation = instrumentation; this.classDefinitions = new ArrayList(); } /** * Register class' byte codes redefinitions. * @param clazz the clazz to be redefined. * @param classCode the new byte code implementation of clazz. */ public synchronized void registerChange(Class clazz, byte[] classCode) { ClassDefinition classDef = new ClassDefinition(clazz, classCode); this.classDefinitions.add(classDef); } /** * Hot swaps previously registered changes. * All classes' byte codes registered through register * are redefined in the system only when hotSwap is invoked. */ public synchronized void hotSwap() { ClassDefinition[] definitions = new ClassDefinition[this.classDefinitions.size()]; definitions = this.classDefinitions.toArray(definitions); try { instrumentation.redefineClasses(definitions); } catch(ClassNotFoundException e) { throw new RuntimeException(e); } catch(UnmodifiableClassException e) { throw new RuntimeException(e); } finally { this.classDefinitions.clear(); } } }././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/StandaloneClassPoolFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/standalone/StandaloneClassPo0000644000175000017500000000341411145122064033301 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.standalone; import org.jboss.aop.classpool.AOPClassPoolFactory; import javassist.ClassPool; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolRepository; /** * Comment * * @author Bill Burke * @version $Revision: 46253 $ */ public class StandaloneClassPoolFactory extends AOPClassPoolFactory { public ScopedClassPool create(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { return new StandaloneClassPool(cl, src, repository); } public ScopedClassPool create(ClassPool src, ScopedClassPoolRepository repository) { return new StandaloneClassPool(src, repository); } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/0000755000175000017500000000000011145122062027644 5ustar twernertwernerlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/AOPClassPool.java0000644000175000017500000001604411145122054032754 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.lang.ref.WeakReference; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.jboss.aop.AspectManager; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolRepository; /** * @author Bill Burke * @version $Revision: 79579 $ */ public class AOPClassPool extends ScopedClassPool { /** Classnames of classes that will be created - we do not want to look for these in other pools */ protected ConcurrentHashMap generatedClasses = new ConcurrentHashMap(); protected ConcurrentHashMap localResources = new ConcurrentHashMap(); /** Classnames of classes that have been loaded, but were not woven */ protected ConcurrentHashMap loadedButNotWovenClasses = new ConcurrentHashMap(); static { ClassPool.doPruning = false; ClassPool.releaseUnmodifiedClassFile = false; } public AOPClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { this(cl, src, repository, false); } protected AOPClassPool(ClassPool src, ScopedClassPoolRepository repository) { this(null, src, repository, true); } private AOPClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository, boolean isTemp) { super(cl, src, repository, isTemp); } public void setClassLoader(ClassLoader cl) { classLoader = new WeakReference(cl); } public void registerGeneratedClass(String className) { generatedClasses.put(className, className); } public void close() { super.close(); AOPClassPoolRepository.getInstance().perfomUnregisterClassLoader(getClassLoader()); } public CtClass getCached(String classname) { CtClass clazz = getCachedLocally(classname); if (clazz == null) { boolean isLocal = false; ClassLoader cl = getClassLoader0(); if (cl != null) { isLocal = isLocalResource(classname); } if (!isLocal) { Object o = generatedClasses.get(classname); if (o == null) { Map registeredCLs = AspectManager.getRegisteredCLs(); synchronized (registeredCLs) { for(ClassPool pl : AspectManager.getRegisteredCLs().values()) { AOPClassPool pool = (AOPClassPool) pl; if (pool.isUnloadedClassLoader()) { AspectManager.instance().unregisterClassLoader(pool.getClassLoader()); continue; } //Do not check classpools for scoped classloaders if (!pool.includeInGlobalSearch()) { continue; } clazz = pool.getCachedLocally(classname); if (clazz != null) { return clazz; } } } } } } // *NOTE* NEED TO TEST WHEN SUPERCLASS IS IN ANOTHER UCL!!!!!! return clazz; } protected boolean includeInGlobalSearch() { return true; } protected String getResourceName(String classname) { final int lastIndex = classname.lastIndexOf('$'); if (lastIndex < 0) { return classname.replaceAll("[\\.]", "/") + ".class"; } else { return classname.substring(0, lastIndex).replaceAll("[\\.]", "/") + classname.substring(lastIndex) + ".class"; } } protected boolean isLocalResource(String resourceName) { String classResourceName = getResourceName(resourceName); Boolean isLocal = localResources.get(classResourceName); if (isLocal != null) { return isLocal.booleanValue(); } boolean localResource = isLocalClassLoaderResource(classResourceName); localResources.put(classResourceName, localResource ? Boolean.TRUE : Boolean.FALSE); return localResource; } public boolean isLocalClassLoaderResource(String classResourceName) { return getClassLoader().getResource(classResourceName) != null; } public synchronized CtClass getLocally(String classname) throws NotFoundException { softcache.remove(classname); CtClass clazz = (CtClass) classes.get(classname); if (clazz == null) { clazz = createCtClass(classname, true); if (clazz == null) throw new NotFoundException(classname); lockInCache(clazz);//Avoid use of the softclasscache } return clazz; } public void setClassLoadedButNotWoven(String classname) { loadedButNotWovenClasses.put(classname, Boolean.TRUE); } public boolean isClassLoadedButNotWoven(String classname) { return loadedButNotWovenClasses.get(classname) == Boolean.TRUE; } public static AOPClassPool createAOPClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { return (AOPClassPool)AspectManager.getClassPoolFactory().create(cl, src, repository); } public static AOPClassPool createAOPClassPool(ClassPool src, ScopedClassPoolRepository repository) { return (AOPClassPool)AspectManager.getClassPoolFactory().create(src, repository); } public String toString() { ClassLoader cl = null; try { cl = getClassLoader(); } catch(IllegalStateException ignore) { } return this.getClass().getName() + "@" + System.identityHashCode(this) + " " + super.toString() + " - dcl:" + cl; } public CtClass internalGet0(String classname, boolean useCache) throws NotFoundException { return super.get0(classname, useCache); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/AOPClassLoaderScopingPolicy.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/AOPClassLoaderScop0000644000175000017500000000374511145122056033164 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import org.jboss.aop.AspectManager; import org.jboss.aop.Domain; /** * AOPClassLoaderScopingPolicy.

* * This is a temporary abstraction to replace AOPScopedClassLoaderHelper * until a better deployment/context resolution mechanism is used rather * than using the classloader to decide things. * * @author Adrian Brock * @version $Revision: 1.1 $ */ public interface AOPClassLoaderScopingPolicy { /** * Get the domain for classloader * * @param classLoader the classloader * @param parent the parent (isn't this always the top level aspect manager?) * @return any scoped domain or the null if not scoped */ Domain getDomain(ClassLoader classLoader, AspectManager parent); /** * Get the top level domain * * @param parent the parent (isn't this always the top level aspect manager?) * @return any scoped domain or the null if not scoped */ Domain getTopLevelDomain(AspectManager parent); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/AOPClassPoolFactory.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/AOPClassPoolFactor0000644000175000017500000000332311145122062033166 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import javassist.ClassPool; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolFactory; import javassist.scopedpool.ScopedClassPoolRepository; /** * Comment * * @author Bill Burke * @version $Revision: 55872 $ * **/ public class AOPClassPoolFactory implements ScopedClassPoolFactory { public ScopedClassPool create(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository) { return new AOPClassPool(cl, src, repository); } public ScopedClassPool create(ClassPool src, ScopedClassPoolRepository repository) { return new AOPClassPool(src, repository); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/AOPClassPoolRepository.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/classpool/AOPClassPoolReposi0000644000175000017500000002116211145122054033213 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.classpool; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.jboss.aop.Advisor; import org.jboss.aop.AspectManager; import org.jboss.aop.advice.SecurityActions; import org.jboss.aop.instrument.Instrumentor; import org.jboss.aop.util.logging.AOPLogger; import javassist.ClassPool; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolFactory; import javassist.scopedpool.ScopedClassPoolRepository; import javassist.scopedpool.ScopedClassPoolRepositoryImpl; /** * Singleton classpool repository used by aop * * @author Kabir Khan * @version $Revision: 81449 $ */ public class AOPClassPoolRepository implements ScopedClassPoolRepository { private static final AOPLogger logger = AOPLogger.getLogger(AOPClassPoolRepository.class); private final static AOPClassPoolRepository instance = new AOPClassPoolRepository(); /** The classes per classppol */ protected final HashMap>> ucl2classes = new HashMap>>(); /** The top-level AspectManager this pool belongs to */ AspectManager manager; ScopedClassPoolRepository delegate; public static AOPClassPoolRepository getInstance() { return instance; } private AOPClassPoolRepository() { this.delegate = ScopedClassPoolRepositoryImpl.getInstance(); //This was needed when jboss-aop.jar was deployed in the jboss/lib directory since the AspectManager bean had no chance to initialise it delegate.setClassPoolFactory(new AOPClassPoolFactory()); // if (!setJBossSpecificStartupVariables()) // { // delegate.setClassPoolFactory(new AOPClassPoolFactory()); // } } // private boolean setJBossSpecificStartupVariables() // { // //We are running within JBoss 5, let's default to the JBossClassPoolFactory and set the ScopedClassPoolHelper // //so that we get correct behaviour before the AspectManager service has been deployed // try // { // Class jbcpf = Class.forName("org.jboss.aop.deployment.JBossClassPoolFactory"); // ScopedClassPoolFactory factory = (ScopedClassPoolFactory)jbcpf.newInstance(); // // Class hlpr = Class.forName("org.jboss.aop.deployment.JBossScopedClassLoaderHelper"); // AOPScopedClassLoaderHelper helper = (AOPScopedClassLoaderHelper)hlpr.newInstance(); // delegate.setClassPoolFactory(factory); // AspectManager.scopedCLHelper = helper; // return true; // } // catch (Exception e) // { // } // return false;//Not running in JBoss probably // } public void setClassPoolFactory(ScopedClassPoolFactory factory) { delegate.setClassPoolFactory(factory); } public ScopedClassPoolFactory getClassPoolFactory() { return delegate.getClassPoolFactory(); } public boolean isPrune() { return delegate.isPrune(); } public void setPrune(boolean prune) { delegate.setPrune(prune); } public ScopedClassPool createScopedClassPool(ClassLoader cl, ClassPool src) { return delegate.createScopedClassPool(cl, src); } public ClassPool findClassPool(ClassLoader cl) { return delegate.findClassPool(cl); } public void setAspectManager(AspectManager manager) { this.manager = manager; } /** * Get the registered classloaders * * @return the registered classloaders */ public Map getRegisteredCLs() { return delegate.getRegisteredCLs(); } /** * This method will check to see if a register classloader has been undeployed (as in JBoss) */ public void clearUnregisteredClassLoaders() { delegate.clearUnregisteredClassLoaders(); } public ClassPool registerClassLoader(ClassLoader ucl) { return delegate.registerClassLoader(ucl); } public void unregisterClassLoader(ClassLoader cl) { delegate.unregisterClassLoader(cl); } public void registerClass(Class clazz) { ClassLoader classLoader = SecurityActions.getClassLoader(clazz); HashSet> classes = ucl2classes.get(classLoader); if (classes == null) { classes = new HashSet>(); ucl2classes.put(classLoader, classes); } classes.add(clazz); } public void perfomUnregisterClassLoader(ClassLoader cl) { if (System.getSecurityManager() == null) { UnregisterClassLoaderAction.NON_PRIVILEGED.unregister(this, cl); } else { UnregisterClassLoaderAction.PRIVILEGED.unregister(this, cl); } } private void doUnregisterClassLoader(ClassLoader cl) { synchronized (delegate.getRegisteredCLs()) { HashSet> classes = ucl2classes.remove(cl); if (classes != null) { for (Class clazz : classes) { synchronized (manager.getAdvisors()) { WeakReference ref = manager.getAdvisors().get(clazz); if (ref != null) { Advisor advisor = ref.get(); manager.getAdvisors().remove(clazz); if (advisor != null) { advisor.cleanup(); } } Class advisedClass = clazz; try { //The static advisor field should be the only remaining hard reference to the advisor Field f = advisedClass.getDeclaredField(Instrumentor.HELPER_FIELD_NAME); f.setAccessible(true); f.set(null, null); } catch(NoSuchFieldException e) { logger.warn("Error unsetting advisor for " + advisedClass.getName() + " " + e); } catch(IllegalAccessException e) { logger.warn("Error unsetting advisor for " + advisedClass.getName() + " " + e); } } } } } } interface UnregisterClassLoaderAction { void unregister(AOPClassPoolRepository repository, ClassLoader loader); UnregisterClassLoaderAction PRIVILEGED = new UnregisterClassLoaderAction() { public void unregister(final AOPClassPoolRepository repository, final ClassLoader loader) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() { repository.doUnregisterClassLoader(loader); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof RuntimeException) { throw (RuntimeException)ex; } throw new RuntimeException(ex); } } }; UnregisterClassLoaderAction NON_PRIVILEGED = new UnregisterClassLoaderAction() { public void unregister(AOPClassPoolRepository repository, ClassLoader loader) { repository.doUnregisterClassLoader(loader); } }; } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/SuperClassesFirstWeavingStrategy.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/SuperClassesFirstWeavingStra0000644000175000017500000001744611145122062033403 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import org.jboss.aop.classpool.AOPClassPool; import org.jboss.aop.instrument.Instrumentor; import org.jboss.aop.instrument.InstrumentorFactory; import org.jboss.aop.util.logging.AOPLogger; import javassist.ByteArrayClassPath; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; /** * Generated advisors need to load all the superclasses * before we load the actual class. * * @author Stale W. Pedersen * @author Kabir Khan * @version $Revision: */ public class SuperClassesFirstWeavingStrategy extends WeavingStrategySupport { private static final AOPLogger logger = AOPLogger.getLogger(SuperClassesFirstWeavingStrategy.class); private boolean verbose = AspectManager.verbose; public static final String AOP_PACKAGE = Advised.class.getPackage().getName(); public byte[] translate(AspectManager manager, String className, ClassLoader loader, byte[] classfileBuffer) throws Exception { if (isReEntry()) { return null; } setReEntry(); super.setTransformationStarted(); try { if (manager.isNonAdvisableClassName(className)) { return null; } AOPClassPool pool = (AOPClassPool) manager.registerClassLoader(loader); CtClass clazz = obtainCtClassInfo(pool, className, classfileBuffer); CtClass woven = instrumentClass(manager, pool, clazz, true); if (woven != null) { pool.lockInCache(woven); if (AspectManager.debugClasses) { SecurityActions.debugWriteFile(clazz); } byte[] rtn = woven.toBytecode(); if (AspectManager.getPrune()) woven.prune(); return rtn; } else { pool.soften(clazz); } return null; } catch (Exception ex) { if (!(ex instanceof NotFoundException)) { if (verbose) logger.error(ex); else logger.error(ex.getMessage()+".. Do verbose mode if you want full stack trace."); } throw ex; } finally { clearReEntry(); } } private CtClass obtainCtClassInfo(AOPClassPool pool, String className, byte[] classfileBuffer) throws NotFoundException { try { return pool.getLocally(className); } catch (NotFoundException e) { // todo Bill Burke: this scares the shit out of me, but it must be done // I think it will screw up hotdeployment at some time. Then again, maybe not ;) ByteArrayClassPath cp = new ByteArrayClassPath(className, classfileBuffer); pool.insertClassPath(cp); return pool.getLocally(className); } catch(Error e) { return null; } } private CtClass instrumentClass(AspectManager manager, AOPClassPool pool, CtClass clazz, boolean isLoadedClass) throws NotFoundException, Exception { if (pool.isClassLoadedButNotWoven(clazz.getName())) { return null; } try { CtClass superClass = clazz.getSuperclass(); if (superClass != null && !Instrumentor.implementsAdvised(clazz)) { ClassPool superPool = superClass.getClassPool(); if (superPool instanceof AOPClassPool) { AspectManager aspectManager = manager; if (manager instanceof Domain && superPool != pool) { //We are in a scoped classloader and the superclass is not aspectManager = AspectManager.instance(superPool.getClassLoader()); } instrumentClass(aspectManager, (AOPClassPool)superPool, superClass, false); } } if (manager.isNonAdvisableClassName(clazz.getName())) { return null; } if (clazz.isArray()) { if (verbose && logger.isDebugEnabled()) logger.debug("cannot compile, isArray: " + clazz.getName()); pool.flushClass(clazz.getName()); return null; } if (clazz.isInterface()) { if (verbose && logger.isDebugEnabled()) logger.debug("cannot compile, isInterface: " + clazz.getName()); //pool.flushClass(info.getClassName()); clazz.prune(); return null; } if (clazz.isFrozen()) { if(isAdvised(pool, clazz)) return null; if (verbose && logger.isDebugEnabled()) logger.debug("warning, isFrozen: " + clazz.getName() + " " + clazz.getClassPool()); if (!isLoadedClass) { //What's the point of this? clazz = obtainCtClassInfo(pool, clazz.getName(), null); } else return null; //info.getClazz().defrost(); } boolean transformed = clazz.isModified(); if (!transformed) { ClassAdvisor advisor = AdvisorFactory.getClassAdvisor(clazz, manager); Instrumentor instrumentor = InstrumentorFactory.getInstrumentor( pool, manager, manager.dynamicStrategy.getJoinpointClassifier(), manager.dynamicStrategy.getDynamicTransformationObserver(clazz)); if (!Instrumentor.isTransformable(clazz)) { if (verbose && logger.isDebugEnabled()) logger.debug("cannot compile, implements Untransformable: " + clazz.getName()); //Flushing the generated invocation classes breaks things further down the line //pool.flushClass(info.getClassName()); return null; } manager.attachMetaData(advisor, clazz, true); manager.applyInterfaceIntroductions(advisor, clazz); transformed = instrumentor.transform(clazz, advisor); } if (transformed) { return clazz; } if (isLoadedClass) { pool.setClassLoadedButNotWoven(clazz.getName()); } return null; } catch(Exception e) { throw new RuntimeException("Error converting class ", e); } finally { } } public boolean isAdvised(ClassPool pool, CtClass clazz) throws NotFoundException { CtClass[] interfaces = clazz.getInterfaces(); CtClass advised = pool.get(AOP_PACKAGE + ".Advised"); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(advised)) return true; if (interfaces[i].getName().equals(AOP_PACKAGE + ".Advised")) return true; } return false; } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/HotSwapStrategy.java0000644000175000017500000005610111145122062031623 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import gnu.trove.TLongObjectHashMap; import java.lang.reflect.Constructor; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import javassist.ClassPool; import javassist.CodeConverter; import javassist.CtClass; import javassist.CtField; import javassist.NotFoundException; import org.jboss.aop.advice.Interceptor; import org.jboss.aop.instrument.DynamicTransformationObserver; import org.jboss.aop.instrument.HotSwapper; import org.jboss.aop.instrument.Instrumentor; import org.jboss.aop.instrument.InstrumentorFactory; import org.jboss.aop.instrument.JoinpointClassifier; import org.jboss.aop.instrument.JoinpointFullClassifier; import org.jboss.aop.instrument.JoinpointStatusUpdate; /** * Dynamic AOP strategy that hot swaps a class code. * A class code is hot swapped whenever one or more joinpoints * become advised or unadvised through dynamic aop operations. * @see org.jboss.aop.DynamicAOPStrategy * @author Flavia Rainone */ public class HotSwapStrategy implements DynamicAOPStrategy { private HotSwapper hotSwapper; private Collection joinpointUpdates; private Instrumentor instrumentor; /** * Constructor. * @param hotSwapper a hot swapper is necessary for this strategy. */ public HotSwapStrategy(HotSwapper hotSwapper) { this.hotSwapper = hotSwapper; this.joinpointUpdates = new ArrayList(); this.instrumentor = InstrumentorFactory.getInstrumentor(AspectManager.instance(), getJoinpointClassifier()); } /** * Notifies the strategy that one or more interceptor chains in the * system may have been updated. This method hot swaps all classes * whose joinpoints became advised or unadvised due to recent dynamic * aop operations. * @see org.jboss.aop.DynamicAOPStrategy#interceptorChainsUpdated() */ public synchronized void interceptorChainsUpdated() { synchronized(joinpointUpdates) { if (!joinpointUpdates.isEmpty()) { instrumentor.interceptorChainsUpdated(new ArrayList(joinpointUpdates), hotSwapper); joinpointUpdates.clear(); } } } /** * Returns a org.jboss.aop.instrument.JoinpointFullClassifier * instance. * @see org.jboss.aop.DynamicAOPStrategy#getJoinpointClassifier() */ public JoinpointClassifier getJoinpointClassifier() { return new JoinpointFullClassifier(); } /** * Notifies the dynamic strategy that some joinpoints were wrapped due to only * dynamic aop operations. * @param clazz class containing the joinpoints. * @param constructor true if the constructor execution was wrapped due * to only dynamic aop operations. * @param fieldRead collection of CtField instances whose read joinpoint * was wrapped due to only dynamic aop operations. * @param fieldWrite collection of CtField instances whose write joinpoint * was wrapped due to only dynamic aop operations. */ /** * Returns a dynamic transformation observer for clazz. * @see org.jboss.aop.DynamicAOPStrategy#getDynamicTransformationObserver */ public DynamicTransformationObserver getDynamicTransformationObserver(CtClass clazz) { return new DynamicTransformationTracker(clazz); } /** * Returns an interceptor chain observer for clazz. * @see org.jboss.aop.DynamicAOPStrategy#getInterceptorChainObserver */ public InterceptorChainObserver getInterceptorChainObserver(Class clazz) { ClassPool classPool = AspectManager.instance().findClassPool(clazz); CtClass ctClass = null; try { ctClass = classPool.get(clazz.getName()); } catch(NotFoundException e) { throw new RuntimeException("Class " + clazz.getName() + " was not found at class pool."); } return new JoinpointStatusUpdater(ctClass); } /** * Register a joinpoint status update. This registered update will be used in * interceptorChainsUpdated to notify org.jboss.aop.Instrumentor * of the interceptor chains changes. * @param update the update to be registered. */ private synchronized void newJoinpointUpdate(JoinpointStatusUpdate update) { synchronized(this.joinpointUpdates) { this.joinpointUpdates.add(update); } } /** * Implements the org.jboss.aop.instrument.DynamicTransformationObserver * interface in order to update callers code when the callee is instrumented due * to only dynamicaly added bindings. * This instance is associated with a class, and should be used to observe the * transformation process of this class. */ private class DynamicTransformationTracker implements DynamicTransformationObserver { //private CtClass clazz; private Collection fieldReads; private Collection fieldWrites; private boolean constructor; /** * Constructor. * @param clazz to class whose transformation process this object will observe. */ public DynamicTransformationTracker(CtClass clazz) { //this.clazz = clazz; this.fieldReads = new ArrayList(); this.fieldWrites = new ArrayList(); this.constructor = false; } /** * Notifies that during the transformation of clazz, the * field read joinpoint was wrapped due only to bindings added * dynamicaly. * @param field the field whose read joinpoint was dynamicaly wrapped. * @see DynamicTransformationObserver#fieldReadDynamicalyWrapped(CtField) */ public void fieldReadDynamicalyWrapped(CtField field) { this.fieldReads.add(field); } /** * Notifies that during the transformation of clazz, the * field read joinpoint was wrapped due only to bindings added * dynamicaly. * @param field the field whose read joinpoint was dynamicaly wrapped. * @see DynamicTransformationObserver#fieldWriteDynamicalyWrapped(CtField) */ public void fieldWriteDynamicalyWrapped(CtField field) { this.fieldWrites.add(field); } /** * Notifies that during the transformation of clazz, the * constructor execution joinpoints were wrapped due only to bindings added * dynamicaly. * @see DynamicTransformationObserver#constructorDynamicalyWrapped(CtField) */ public void constructorDynamicalyWrapped() { this.constructor = true; } /** * Notifies that the transformation of clazz is finished. */ public void transformationFinished(CtClass clazz, CodeConverter converter) { if (constructor || !fieldReads.isEmpty() || !fieldWrites.isEmpty()) { instrumentor.convertProcessedClasses(hotSwapper, clazz, fieldReads, fieldWrites, constructor); } } } /** * Implements the org.jboss.aop.InteceptorChainObserver * interface in order to register joinpoint status updates in the * HotSwapStrategy. */ private class JoinpointStatusUpdater implements InterceptorChainObserver { private JoinpointStatusUpdate.ClassJoinpoints newlyAdvised; private JoinpointStatusUpdate.ClassJoinpoints newlyUnadvised; private int instanceInterceptors; private WeakHashMap instanceAdvisors; private CtClass clazz; private int fields; private int constructors; private int methods; private Interceptor[][] fieldReadInterceptors; private Interceptor[][] fieldWriteInterceptors; private Interceptor[][] constructorInterceptors; private Map methodInterceptors; private int[] constructorIndexMap; /** * Constructor. * @param clazz the class associated to this observer. */ public JoinpointStatusUpdater(CtClass clazz) { this.clazz = clazz; this.instanceAdvisors = new WeakHashMap(); } /** * This method must be called before any other notification method is invoked. * @see org.jboss.aop.InterceptorChainObserver#initialInterceptorChains(Interceptor[][], Interceptor[][], Interceptor[][], TLongObjectHashMap) */ public synchronized void initialInterceptorChains(final Class reflectionClass, FieldInfo[] fieldReadInfos, FieldInfo[] fieldWriteInfos, ConstructorInfo[] constructorInfos, MethodInterceptors methodInterceptors) { Constructor[] declaredConstructors = null; if (System.getSecurityManager() == null) { declaredConstructors = reflectionClass.getDeclaredConstructors(); } else { try { declaredConstructors = AccessController.doPrivileged(new PrivilegedExceptionAction[]>() { public Constructor[] run() throws Exception { return reflectionClass.getDeclaredConstructors(); } }); } catch (PrivilegedActionException e) { throw new RuntimeException("Error retrieving declared constructors of " + reflectionClass.getName(), e.getException()); } } constructorIndexMap = new int[declaredConstructors.length]; int javassistIndex = 0; for (int reflectionIndex = 0; reflectionIndex < declaredConstructors.length; reflectionIndex++) { Class[] params = declaredConstructors[reflectionIndex].getParameterTypes(); if (params.length > 0 && params[params.length-1].getName().equals("javassist.runtime.Inner")) { constructorIndexMap[reflectionIndex] = -1; } else { constructorIndexMap[reflectionIndex] = javassistIndex ++ ; } } this.fieldReadInterceptors = copyInterceptorChains(fieldReadInfos); this.fieldWriteInterceptors = copyInterceptorChains(fieldWriteInfos); this.constructorInterceptors = copyInterceptorChains(constructorInfos); this.methodInterceptors = new HashMap(); long[] methodKeys = methodInterceptors.keys(); for (int i = 0; i < methodKeys.length; i++) { long key = methodKeys[i]; MethodInfo methodInfo = methodInterceptors.getMethodInfo(key); this.methodInterceptors.put(methodInfo, methodInfo.getInterceptors()); } this.fields = fieldReadInfos.length; this.constructors = constructorInfos.length; this.methods = methodInterceptors.size(); this.newlyAdvised = new JoinpointStatusUpdate.ClassJoinpoints(fields, constructors, methods); this.newlyUnadvised = new JoinpointStatusUpdate.ClassJoinpoints(fields, constructors, methods); } /** * Notification method. * @see InterceptorChainObserver#interceptorChainsUpdated(Interceptor[][], Interceptor[][], Interceptor[][], MethodInterceptors) */ public synchronized void interceptorChainsUpdated(FieldInfo[] newFieldReadInfos, FieldInfo[] newFieldWriteInfos, ConstructorInfo[] newConstructorInfos, MethodInterceptors newMethodInterceptors) { if (instanceInterceptors == 0) { long[] methodKeys = newMethodInterceptors.keys(); for (int i = 0; i < methodKeys.length; i++) { long key = methodKeys[i]; MethodInfo newMethodInfo = newMethodInterceptors.getMethodInfo(key); Interceptor[] oldInterceptorChain = this.methodInterceptors.get(newMethodInfo); if ((oldInterceptorChain == null || oldInterceptorChain.length == 0) && !newMethodInfo.getInterceptorChain().isEmpty()) { newlyAdvised.methodExecutions.add(newMethodInfo); } else if ((oldInterceptorChain != null && oldInterceptorChain.length > 0) && newMethodInfo.getInterceptorChain().isEmpty()) { newlyUnadvised.methodExecutions.add(newMethodInfo); } } fillNewStateCollections(fieldReadInterceptors, newFieldReadInfos, newlyAdvised.fieldReads, newlyUnadvised.fieldReads, null); fillNewStateCollections(fieldWriteInterceptors, newFieldWriteInfos, newlyAdvised.fieldWrites, newlyUnadvised.fieldWrites, null); fillNewStateCollections(constructorInterceptors, newConstructorInfos, newlyAdvised.constructorExecutions, newlyUnadvised.constructorExecutions, this.constructorIndexMap); newJoinpointUpdate(this.getJoinpointStatusUpdate()); } this.fieldReadInterceptors = copyInterceptorChains(newFieldReadInfos); this.fieldWriteInterceptors = copyInterceptorChains(newFieldWriteInfos); this.constructorInterceptors = copyInterceptorChains(newConstructorInfos); long[] methodKeys = newMethodInterceptors.keys(); for (int i = 0; i < methodKeys.length; i++) { long key = methodKeys[i]; MethodInfo methodInfo = newMethodInterceptors.getMethodInfo(key); this.methodInterceptors.put(methodInfo, methodInfo.getInterceptors()); } } /** * Notification method. * @see InterceptorChainObserver#instanceInterceptorAdded(InstanceAdvisor) */ public synchronized void instanceInterceptorAdded(InstanceAdvisor instanceAdvisor) { this.instanceInterceptorsAdded(instanceAdvisor, 1); } /** * Notification method. * @see InterceptorChainObserver#instanceInterceptorsAdded(InstanceAdvisor, int) */ public synchronized void instanceInterceptorsAdded(InstanceAdvisor instanceAdvisor, int howMany) { updateInstanceInterceptorsTable(instanceAdvisor, howMany); updateAdvisenessStatus(this.newlyAdvised); this.instanceInterceptors += howMany; HotSwapStrategy.this.interceptorChainsUpdated(); } /** * Notification method. * @see InterceptorChainObserver#instanceInterceptorRemoved(InstanceAdvisor) */ public synchronized void instanceInterceptorRemoved(InstanceAdvisor instanceAdvisor) { this.instanceInterceptorsRemoved(instanceAdvisor, 1); } /** * Notification method. * @see InterceptorChainObserver#instanceInterceptorsRemoved(InstanceAdvisor, int) */ public synchronized void instanceInterceptorsRemoved(InstanceAdvisor instanceAdvisor, int howMany) { updateInstanceInterceptorsTable(instanceAdvisor, -howMany); this.instanceInterceptors -= howMany; updateAdvisenessStatus(this.newlyUnadvised); HotSwapStrategy.this.interceptorChainsUpdated(); } /** * Notification method. * @see InterceptorChainObserver#allInstanceInterceptorsRemoved(InstanceAdvisor) */ public synchronized void allInstanceInterceptorsRemoved(InstanceAdvisor instanceAdvisor) { if (this.instanceAdvisors.containsKey(instanceAdvisor)) { this.instanceAdvisors.remove(instanceAdvisor); } if (this.instanceInterceptors == 0) return; this.instanceInterceptors = 0; for (Integer interceptors : instanceAdvisors.values()) { instanceInterceptors += interceptors.intValue(); } if (this.instanceInterceptors > 0) return; updateAdvisenessStatus(this.newlyUnadvised); HotSwapStrategy.this.interceptorChainsUpdated(); } /** * Creates a copy of {@code chains}. * * @param chains array of chains to be copied */ private Interceptor[][] copyInterceptorChains(JoinPointInfo[] updatedInfos) { Interceptor[][] copy = new Interceptor[updatedInfos.length][]; for (int i = 0; i < updatedInfos.length; i++) { copy[i] = updatedInfos[i].getInterceptors(); } return copy; } /** * Gets the joinpoint status update containing all the observed interceptor * chain changes information. * @return the joinpoint status update. */ private JoinpointStatusUpdate getJoinpointStatusUpdate() { JoinpointStatusUpdate update = new JoinpointStatusUpdate(); update.clazz = this.clazz; update.newlyAdvisedJoinpoints = this.newlyAdvised; update.newlyUnadvisedJoinpoints = this.newlyUnadvised; this.newlyAdvised = new JoinpointStatusUpdate.ClassJoinpoints(this.fields, this.constructors, this.methods); this.newlyUnadvised = new JoinpointStatusUpdate.ClassJoinpoints(this.fields, this.constructors, this.methods); return update; } /** * Compares the two interceptors chains and adds the newly advised joinpoints * to newlyAdvised and the newly unadvised to newlyUnadvised. * @param interceptors old interceptors chain. * @param newInterceptors new interceptors chain. * @param newlyAdvised collection to which the newly advised joinpoints will be added. * @param newlyAdvised collection to which the newly unadvised joinpoints will be added. */ private void fillNewStateCollections(Interceptor[][] interceptors, JoinPointInfo[] updatedInfos, Collection newlyAdvised, Collection newlyUnadvised, int[] indexMap) { if (instanceInterceptors > 0) return; for (int i = 0; i < interceptors.length; i++) { Interceptor[] oldInterceptorsChain = interceptors[i]; Interceptor[] newInterceptorsChain = updatedInfos[i].getInterceptors(); boolean interceptedBefore = oldInterceptorsChain != null && oldInterceptorsChain.length > 0; boolean interceptedNow = newInterceptorsChain != null && newInterceptorsChain.length > 0; if (!interceptedBefore && interceptedNow) { if (indexMap != null) { if(indexMap[i] != -1) { newlyAdvised.add(new Integer(indexMap[i])); } } else { newlyAdvised.add(new Integer(i)); } } else if (interceptedBefore && !interceptedNow) { if (indexMap != null) { if(indexMap[i] != -1) { newlyUnadvised.add(new Integer(indexMap[i])); } } else { newlyUnadvised.add(new Integer(i)); } } } } /** * Updates the instance interceptor table to contain the interceptorsAdded information. * @param instanceAdvisor the org.jboss.aop.InstanceAdvisor whose interceptors chain * size is being updated. * @param interceptorsAdded the number of interceptors added (or removed, if interceptorsAdded * is negative) to instanceAdvisor. */ private void updateInstanceInterceptorsTable(InstanceAdvisor instanceAdvisor, int interceptorsAdded) { if (this.instanceAdvisors.containsKey(instanceAdvisor)) { Integer interceptors = instanceAdvisors.get(instanceAdvisor); instanceAdvisors.put(instanceAdvisor, new Integer(interceptors.intValue() + interceptorsAdded)); } else { instanceAdvisors.put(instanceAdvisor, new Integer(interceptorsAdded)); } } /** * If there are no instance interceptors to any instance of the class associated to this observer, * this method adds all unadvised joinpoints to joinpoints and records the joinpoint * status update in the HotSwapStrategy. * @param joinpoints ClassJoinpoints to which the unadvised joinpoints will be added. */ private void updateAdvisenessStatus(JoinpointStatusUpdate.ClassJoinpoints joinpoints) { if (this.instanceInterceptors == 0) { for (Map.Entry entry: methodInterceptors.entrySet()) { if (entry.getValue() == null || entry.getValue().length == 0) { joinpoints.methodExecutions.add(entry.getKey()); } } findUnadvisedJoinpoints(this.fieldReadInterceptors, joinpoints.fieldReads); findUnadvisedJoinpoints(this.fieldWriteInterceptors, joinpoints.fieldWrites); findUnadvisedJoinpoints(this.constructorInterceptors, joinpoints.constructorExecutions); newJoinpointUpdate(getJoinpointStatusUpdate()); } } /** * Finds all unadvised joinponts. * @param interceptors the interceptors chains applied to the joinponts. * @param joinpointsFound the collection to which the found joinpoints will be added. */ private void findUnadvisedJoinpoints(Interceptor[][] interceptors, Collection joinpointsFound) { for (int i = 0; i < interceptors.length; i++) { if (interceptors[i] == null || interceptors[i].length == 0) { joinpointsFound.add(new Integer(i)); } } } } }libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/AspectManager.java0000644000175000017500000023020411145122060031221 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import javassist.ClassPool; import javassist.CtClass; import javassist.scopedpool.ScopedClassPool; import javassist.scopedpool.ScopedClassPoolFactory; import org.jboss.aop.advice.AdviceBinding; import org.jboss.aop.advice.AdviceStack; import org.jboss.aop.advice.AspectDefinition; import org.jboss.aop.advice.AspectFactoryWithClassLoader; import org.jboss.aop.advice.ClassifiedBindingAndPointcutCollection; import org.jboss.aop.advice.DynamicCFlowDefinition; import org.jboss.aop.advice.InterceptorFactory; import org.jboss.aop.advice.PrecedenceDef; import org.jboss.aop.advice.PrecedenceDefEntry; import org.jboss.aop.advice.PrecedenceSorter; import org.jboss.aop.advice.Scope; import org.jboss.aop.array.ArrayAdvisor; import org.jboss.aop.array.ArrayBinding; import org.jboss.aop.array.ArrayReplacement; import org.jboss.aop.classpool.AOPClassLoaderScopingPolicy; import org.jboss.aop.classpool.AOPClassPoolRepository; import org.jboss.aop.instrument.GeneratedAdvisorInstrumentor; import org.jboss.aop.instrument.Instrumentor; import org.jboss.aop.instrument.InstrumentorFactory; import org.jboss.aop.instrument.JoinPointGenerator; import org.jboss.aop.instrument.TransformerCommon; import org.jboss.aop.introduction.AnnotationIntroduction; import org.jboss.aop.introduction.InterfaceIntroduction; import org.jboss.aop.metadata.ClassMetaDataBinding; import org.jboss.aop.metadata.ClassMetaDataLoader; import org.jboss.aop.metadata.SimpleClassMetaDataLoader; import org.jboss.aop.microcontainer.lifecycle.LifecycleCallbackBinding; import org.jboss.aop.microcontainer.lifecycle.LifecycleManager; import org.jboss.aop.pointcut.CFlowStack; import org.jboss.aop.pointcut.DeclareDef; import org.jboss.aop.pointcut.DynamicCFlow; import org.jboss.aop.pointcut.Pointcut; import org.jboss.aop.pointcut.PointcutInfo; import org.jboss.aop.pointcut.PointcutStats; import org.jboss.aop.pointcut.Typedef; import org.jboss.aop.pointcut.ast.ClassExpression; import org.jboss.aop.util.AOPLock; import org.jboss.aop.util.UnmodifiableEmptyCollections; import org.jboss.aop.util.logging.AOPLogger; import org.jboss.util.collection.WeakValueHashMap; import org.jboss.util.loading.Translator; /** * This singleton class manages all pointcuts and metadata. * Coders can access it via the AspectManager.instance() method. *

* It is also the middle man between the ClassLoader and * the actual class instrumentation as well. *

* App Developers that want to create and apply, interceptors, * pointcuts, or metadata at runtime can also use this object * to do that. * * @author Bill Burke * @author adrian@jboss.org * @version $Revision: 84101 $ */ public class AspectManager implements Translator { private static final AOPLogger logger = AOPLogger.getLogger(AspectManager.class); /** Indicates that a call to the factory has been made, but it returned null. */ private static final Object NULL_ASPECT = new Object(); /** Lock to be used when lazy creating the collections */ Object lazyCollectionLock = new Object(); /** Advisors registered with this manager/domain */ protected final WeakHashMap, WeakReference> advisors = new WeakHashMap, WeakReference>(); /** A map of domains by class, maintaned by the top level AspectManager */ protected volatile WeakHashMap, WeakReference> subDomainsPerClass = UnmodifiableEmptyCollections.EMPTY_WEAK_HASHMAP; /** A map of domains by name */ protected volatile WeakValueHashMap subDomainsByName = UnmodifiableEmptyCollections.EMPTY_WEAK_VALUE_HASHMAP; /** Each domain may have sub domains interested in changes happening in this manager/domain */ protected volatile WeakHashMap subscribedSubDomains = UnmodifiableEmptyCollections.EMPTY_WEAK_HASHMAP; /** A queue for adding new subscribed subdomains to */ protected volatile WeakHashMap subscribedSubDomainsQueue = UnmodifiableEmptyCollections.EMPTY_WEAK_HASHMAP; protected int subscribedDomainQueueRef; protected volatile LinkedHashMap interfaceIntroductions = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; protected volatile LinkedHashMap arrayReplacements = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; protected volatile LinkedHashMap arrayBindings = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; protected volatile LinkedHashMap annotationIntroductions =UnmodifiableEmptyCollections. EMPTY_LINKED_HASHMAP; protected volatile LinkedHashMap annotationOverrides = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; @Deprecated protected volatile LinkedHashMap bindings = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; protected final ClassifiedBindingAndPointcutCollection bindingCollection; protected volatile LinkedHashMap typedefs = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; protected volatile HashMap interceptorFactories = UnmodifiableEmptyCollections.EMPTY_HASHMAP; protected volatile HashMap classMetaDataLoaders = UnmodifiableEmptyCollections.EMPTY_HASHMAP; protected volatile HashMap interceptorStacks = UnmodifiableEmptyCollections.EMPTY_HASHMAP; protected volatile HashMap declares = UnmodifiableEmptyCollections.EMPTY_HASHMAP; protected volatile ConcurrentHashMap cflowStacks = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; protected volatile ConcurrentHashMap dynamicCFlows = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; protected volatile ConcurrentHashMap aspectDefinitions = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; protected volatile ConcurrentHashMap perVMAspects = UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP; /** class name prefixes to explicitly exclude unless contained in include. Maintained by top-level AspectManager */ protected volatile ArrayList exclude = UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; /** class name prefixes to explicitly include, this overrides whatever was set in exclude. Maintained by top-level AspectManager */ protected volatile ArrayList include = UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; /** A set of wildcard enabled classnames that will be ignored no matter if they have been included. Maintained by top-level AspectManager */ protected volatile ArrayList ignore = UnmodifiableEmptyCollections.EMPTY_ARRAYLIST; /** A set of annotation names that will be included even though they are invisible. */ protected List includeInvisibleAnnotations = Collections .emptyList(); /** ClassExpressions built from ignore. Maintained by top-level AspectManager */ protected ClassExpression[] ignoreExpressions = new ClassExpression[0]; protected static AOPLock lock = new AOPLock(); public static boolean classicOrder = false; protected volatile LinkedHashMap classMetaData = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; protected volatile HashMap containers = UnmodifiableEmptyCollections.EMPTY_HASHMAP; protected volatile LinkedHashMap precedenceDefs = UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP; protected PrecedenceDefEntry[] sortedPrecedenceDefEntries; protected WeavingStrategy weavingStrategy; protected DynamicAOPStrategy dynamicStrategy = new LoadInterceptedClassesStrategy(); /** The classloader scoping policy */ // This shouldn't really be static (artifact of singleton and self-bootstrap design) private static AOPClassLoaderScopingPolicy classLoaderScopingPolicy; //Keeps track of if we need to convert references etc for a given class. Domains for scoped classloaders will have their own version of this protected static Map interceptionMarkers = new WeakHashMap(); private final static ClassLoader NULL_CLASSLOADER = new URLClassLoader(new URL[0]); // Static ------------------------------------------------------- protected static AspectManager manager; public static boolean optimize = true; public static boolean debugClasses;//If true, the generated advisor instrumentor will output the generated classes public static ClassLoaderValidation classLoaderValidator; //Keep track of the microcontainer lifecycle callbacks public LifecycleManager lifecycleManager = new LifecycleManager(this); /** * logging switch. We don't use log4j to avoid another heavy library */ public static boolean verbose = false; /** * Whether or not we should maintain the deprecated Advisor.methodInterceptors field * This is required in jboss 4.x for backwards compatibility with EJB 3 * See JBAOP-517 */ public static boolean maintainAdvisorMethodInterceptors; /** * Get the top level aspect manager * * @return the top level aspect manager */ public static synchronized AspectManager getTopLevelAspectManager() { if (classLoaderScopingPolicy == null) { //We are not running in jboss return instance(); } AspectManager result = initManager(); Domain scopedDomain = classLoaderScopingPolicy.getTopLevelDomain(result); if (scopedDomain != null) result = scopedDomain; return result; } public static synchronized AspectManager instance() { return instance(SecurityActions.getContextClassLoader()); } /** * Get the aspect manager for a classloader * * @param loadingClassLoader the classloader * @return the aspect manager */ public static synchronized AspectManager instance(ClassLoader loadingClassLoader) { AspectManager result = initManager(); if (classLoaderScopingPolicy != null) { Domain scopedDomain = classLoaderScopingPolicy.getDomain(loadingClassLoader, result); if (scopedDomain != null) result = scopedDomain; } return result; } /** * Initialise the manager if not already dones so

* * This method should be invoked in a synchronized block * * @return the manager */ private static AspectManager initManager() { if (manager == null) { AccessController.doPrivileged(new PrivilegedAction() { public AspectManager run() { String optimized = System.getProperty("jboss.aop.optimized", null); if (optimized != null) { optimize = (new Boolean(optimized)).booleanValue(); } String pruneit = System.getProperty("jboss.aop.prune", null); if (pruneit != null) { AOPClassPoolRepository.getInstance().setPrune((new Boolean(pruneit)).booleanValue()); } manager = new AspectManager(); //Initialise frequently used fields needed by the top-level manager manager.subDomainsPerClass = new WeakHashMap, WeakReference>(); manager.exclude = new ArrayList(); manager.include = new ArrayList(); manager.ignore = new ArrayList(); manager.includeInvisibleAnnotations = new ArrayList(); AOPClassPoolRepository.getInstance().setAspectManager(manager); if (!verbose) { verbose = (new Boolean(System.getProperty("jboss.aop.verbose", "false"))).booleanValue(); } String exclude = System.getProperty("jboss.aop.exclude", null); if (exclude != null) { ArrayList list = splitString(exclude, ","); manager.setExclude(list); } String include = System.getProperty("jboss.aop.include", null); if (include != null) { ArrayList list = splitString(include, ","); manager.setInclude(list); } String ignore = System.getProperty("jboss.aop.ignore", null); if (ignore != null) { ArrayList list = splitString(ignore, ","); manager.setIgnore(list); } String invisibleAnnotations = System.getProperty("jboss.aop.invisible.annotations", null); if(invisibleAnnotations != null) { ArrayList list = splitString(invisibleAnnotations, ","); manager.setIncludedInvisibleAnnotations(list); } String instrument = System.getProperty("jboss.aop.instrumentor", null); InstrumentorFactory.initialise(instrument); String advisorName = System.getProperty("jboss.aop.advisor", null); AdvisorFactory.initialise(advisorName); String debugClass = System.getProperty("jboss.aop.debug.classes", null); if (debugClass != null) { debugClasses = (new Boolean(debugClass)).booleanValue(); } String classic = System.getProperty("jboss.aop.classicorder", null); if (classic != null) { classicOrder = (new Boolean(classic)).booleanValue(); } String methodInterceptors = System.getProperty("jboss.aop.advisor.methodInterceptors", null); if (methodInterceptors != null) { maintainAdvisorMethodInterceptors = (new Boolean(methodInterceptors)).booleanValue(); } Deployment.deploy(); return null; } }); } return manager; } private static ArrayList splitString(String string, String delim) { if (string != null) { ArrayList list = new ArrayList(); for(String token : string.split(delim)) { list.add(token.trim()); } return list; } return null; } /** * Get the classLoaderScopingPolicy. * * @return the classLoaderScopingPolicy. */ public static AOPClassLoaderScopingPolicy getClassLoaderScopingPolicy() { return classLoaderScopingPolicy; } /** * Set the classLoaderScopingPolicy. * * TODO does it make sense for this to be modified once it has been set? * @param classLoaderScopingPolicy the classLoaderScopingPolicy. */ public static void setClassLoaderScopingPolicy(AOPClassLoaderScopingPolicy classLoaderScopingPolicy) { AspectManager.classLoaderScopingPolicy = classLoaderScopingPolicy; } public InterceptionMarkers getInterceptionMarkers(ClassLoader loader) { if (loader == null) { loader = NULL_CLASSLOADER; } synchronized(interceptionMarkers) { InterceptionMarkers markers = interceptionMarkers.get(loader); if (markers == null) { markers = new InterceptionMarkers(); interceptionMarkers.put(loader, markers); } return markers; } } public LinkedHashMap getPointcuts() { return bindingCollection.getPointcuts(); } public LinkedHashMap getPointcutInfos() { return bindingCollection.getPointcutInfos(); } public CFlowStack getCFlowStack(String name) { return cflowStacks.get(name); } public void addCFlowStack(CFlowStack stack) { initCflowStacksMap(); cflowStacks.put(stack.getName(), stack); } public void removeCFlowStack(String name) { cflowStacks.remove(name); } @Deprecated public DynamicCFlow getDynamicCFlow(String name) { return getDynamicCFlow(name, SecurityActions.getContextClassLoader()); } public DynamicCFlow getDynamicCFlow(String name, ClassLoader cl) { DynamicCFlowDefinition def = dynamicCFlows.get(name); if (def != null) { return def.create(cl); } return null; } /* (non-Javadoc) * @see org.jboss.aop.Manager#addDynamicCFlow(java.lang.String, org.jboss.aop.advice.DynamicCFlowDefinition) */ public void addDynamicCFlow(String name, DynamicCFlowDefinition cflow) { initDynamicCflowsMap(); dynamicCFlows.put(name, cflow); } public void removeDynamicCFlow(String name) { dynamicCFlows.remove(name); } /** * This is a callback object that receives events about * new pointcuts, interceptors and metadata. * The Aspect Management console hooks into this listener */ public static AspectNotificationHandler notificationHandler = null; public static boolean suppressTransformationErrors = false; /** * Suppress when a class cannot be found that a class references * This may happen if code in a class references something and the * class is not in the classpath. */ public static boolean suppressReferenceErrors = true; // Constructors ------------------------------------------------- /** * Called by subclasses */ public AspectManager() { bindingCollection = createBindingCollection(); } /** * Creates the binding collection * @return a {@link ClassifiedBindingAndPointcutCollection} * @see Domain#ini */ protected ClassifiedBindingAndPointcutCollection createBindingCollection() { return new ClassifiedBindingAndPointcutCollection(); } /** * Every <class-metadata> tag corresponds to * a ClassMetaDataLoader. The ClassMetaDataLoader knows how to take * arbitrary XML and apply it to SimpleMetaData. *

* Given a group, return the loader for that group */ public ClassMetaDataLoader findClassMetaDataLoader(String group) { ClassMetaDataLoader loader = classMetaDataLoaders.get(group); if (loader == null) loader = SimpleClassMetaDataLoader.singleton; return loader; } /** * Every <class-metadata> tag corresponds to * a ClassMetaDataLoader. The ClassMetaDataLoader knows how to take * arbitrary XML and apply it to SimpleMetaData. *

* Add a loader for a given group */ public void addClassMetaDataLoader(String group, ClassMetaDataLoader loader) { initClassMetaDataLoadersMap(); classMetaDataLoaders.put(group, loader); } /** * Remove a loader for a given group */ public void removeClassMetaDataLoader(String group) { classMetaDataLoaders.remove(group); } public Map, WeakReference> getAdvisors() { WeakHashMap, WeakReference> tmpAdvisors = new WeakHashMap, WeakReference>(advisors); if(getSubDomainsPerClass().size() > 0) { Map, WeakReference> domainsMap = getSubDomainsPerClass(); Set> keys = domainsMap.keySet(); Domain subDomain = null; for(Class clazz : keys) { WeakReference ref = getSubDomainsPerClass().get(clazz); if (ref != null) { subDomain = ref.get(); if(subDomain != null) { WeakReference advisorRef = advisors.get(clazz); tmpAdvisors.put(clazz, advisorRef); } } } } return tmpAdvisors; } public Advisor getAdvisor(String name) { /* synchronized (advisors) { return (Advisor) advisors.get(name); } */ throw new RuntimeException("OPERATION NOT SUPPORTED ANYMORE"); } /** * Returns the binding map. *

* The returned map must be used for read purposes only. To edit the * binding collection, call {@link #addBinding(AdviceBinding)} and * {@link #removeBinding(String)} instead. * * @return the map containing all advice bindings indexed by their names */ public LinkedHashMap getBindings() { return bindingCollection.getBindings(); } /** * Returns the classified binding collection. *

* Attention: this collection is not supposed to be edited. Hence, only * get methods can be called by clients. * * @return the classified binding collection */ public ClassifiedBindingAndPointcutCollection getBindingCollection() { return bindingCollection; } protected Map, WeakReference> getSubDomainsPerClass() { return subDomainsPerClass; } public Advisor findAdvisor(Class clazz) { if (getSubDomainsPerClass().size() > 0) { //For generated advisors each advisor has its own domain //This is primarily needed for the reflection aspect Domain subDomain = null; synchronized (getSubDomainsPerClass()) { WeakReference ref = getSubDomainsPerClass().get(clazz); if (ref != null) { subDomain = ref.get(); } } if (subDomain != null && subDomain != this) { Advisor advisor = subDomain.findAdvisor(clazz); if (advisor != null) { return advisor; } } } synchronized (advisors) { WeakReference ref = advisors.get(clazz); if (ref == null) return null; return ref.get(); } } /** * Takes a string of the form /sub1/sub2/sub3 of subdomains by name, where the leading "/" is the main AspectManager. * The main user of the naming of domains is (un)serialization of advisors/containers * * @param The FQN of the domain * @return the domain referenced by the FQN or null if it does not exist */ public AspectManager findManagerByName(String fqn) { String[] nameparts = fqn.split("/"); return findManagerByName(nameparts); } private AspectManager findManagerByName(String[] nameparts) { AspectManager found = this; for (int i = 0 ; i < nameparts.length ; i++) { if (nameparts[i].trim().length() == 0) { continue; } found = found.findManagerByNameInternal(nameparts[i]); if (found == null) { break; } } return found; } private AspectManager findManagerByNameInternal(String name) { return subDomainsByName.get(name); } protected void addSubDomainByName(Domain domain) { initSubDomainsByNameMap(); subDomainsByName.put(domain.getDomainName(), domain); } public String getManagerFQN() { return "/"; } public ClassAdvisor getAdvisorIfAdvised(Class clazz) { return (ClassAdvisor)getAnyAdvisorIfAdvised(clazz); } /** * Take into account that an advisor may be a container */ public Advisor getAnyAdvisorIfAdvised(Class clazz) { try { Advisor advisor; advisor = findAdvisor(clazz); if (advisor == null) { return null; } if (advisor.getClazz() == null && advisor instanceof ClassAdvisor) { ((ClassAdvisor)advisor).attachClass(clazz); if (notificationHandler != null) { notificationHandler.attachClass(clazz.getName()); } } return advisor; } catch (RuntimeException ex) { ex.printStackTrace(); throw ex; } } /** * This method is called by the aspectized class when it is loaded * This causes all initialization of interceptors for ClassAdvisor * * @param clazz * @return */ public synchronized ClassAdvisor getAdvisor(Class clazz) { ClassAdvisor advisor = null; // See if one already exists advisor = (ClassAdvisor)findAdvisor(clazz); // if one does not if (advisor == null) { advisor = AdvisorFactory.getClassAdvisor(clazz, this); initialiseClassAdvisor(clazz, advisor); } return advisor; } public synchronized void initialiseClassAdvisor(Class clazz, ClassAdvisor advisor) { // avoiding deadlock. Other threads first get the bindignCollection lock // and then the advisors // as we know that the bindingCollection lock will be needed during the // Advisor.attachClass method execution, we get the lock at this point // making sure we are avoiding the deadlock. lock.lockRead(); try { synchronized (advisors) { advisors.put(clazz, new WeakReference(advisor)); registerClass(clazz); advisor.attachClass(clazz); InterceptorChainObserver observer = dynamicStrategy.getInterceptorChainObserver(clazz); advisor.setInterceptorChainObserver(observer); if (notificationHandler != null) { notificationHandler.attachClass(clazz.getName()); } } } finally { lock.unlockRead(); } } // Public ------------------------------------------------------- public static Map getRegisteredCLs() { return AOPClassPoolRepository.getInstance().getRegisteredCLs(); } /** * This method will check to see if a register classloader has been undeployed (as in JBoss) */ public static void clearUnregisteredClassLoaders() { AOPClassPoolRepository.getInstance().clearUnregisteredClassLoaders(); } /** * Checks to see if an Advisor represents a class that should have been undeployed. * * @param advisor * @return */ public boolean isAdvisorRegistered(Advisor advisor) { synchronized (getRegisteredCLs()) { if (!advisors.containsKey(advisor.getClazz())) return false; if (classLoaderValidator != null) { if (classLoaderValidator.isValidClassLoader(advisor.getClassLoader())) { return true; } else { unregisterClassLoader(advisor.getClassLoader()); return false; } } else { ScopedClassPool pool = (ScopedClassPool) getRegisteredClassPool(advisor.getClassLoader()); if (pool == null) return false; if (pool.isUnloadedClassLoader()) { unregisterClassLoader(advisor.getClassLoader()); return false; } else { return true; } } } } public ClassPool findClassPool(ClassLoader cl) { if (cl == null) { //!(cl instanceof Translatable) // findClassPool has problems with boot and system classes, because // they may be null return registerClassLoader(SecurityActions.getContextClassLoader()); } return registerClassLoader(cl); } public ClassPool findClassPool(Class clazz) { return findClassPool(SecurityActions.getClassLoader(clazz)); } protected ClassPool getRegisteredClassPool(ClassLoader cl) { return getRegisteredCLs().get(cl); } public ClassPool registerClassLoader(ClassLoader ucl) { return AOPClassPoolRepository.getInstance().registerClassLoader(ucl); } protected void registerClass(Class clazz) { AOPClassPoolRepository.getInstance().registerClass(clazz); } public void unregisterClassLoader(ClassLoader cl) { AOPClassPoolRepository.getInstance().unregisterClassLoader(cl); } public ArrayList getExclude() { return exclude; } public void setExclude(ArrayList exclude) { this.exclude.clear(); this.exclude.addAll(exclude); } public ArrayList getInclude() { return include; } public void setInclude(ArrayList include) { this.include.clear(); this.include.addAll(include); } public ArrayList getIgnore() { return ignore; } public List getIncludedInvisibleAnnotations() { return includeInvisibleAnnotations; } public void setIncludedInvisibleAnnotations(List ia) { includeInvisibleAnnotations.clear(); includeInvisibleAnnotations.addAll(ia); } public ClassExpression[] getIgnoreExpressions() { return ignoreExpressions; } public void setIgnore(ArrayList ignore) { this.ignore.clear(); this.ignore.addAll(ignore); ignoreExpressions = new ClassExpression[ignore.size()]; for (int i = 0 ; i < ignore.size() ; i++) { String ex = ignore.get(i); ignoreExpressions[i] = new ClassExpression(ex); } } public boolean ignoreClass(String classname) { ArrayList ignore = getIgnore(); if (ignore == null) return false; ClassExpression[] ignoreExprs = getIgnoreExpressions(); for (int i = 0; i < ignoreExprs.length; i++) { if(ignoreExprs[i].matches(classname)) return true; } return false; } public boolean includeClass(String classname) { ArrayList include = getInclude(); if (include == null) return false; for (int i = 0; i < include.size(); i++) { String str = include.get(i); if (classname.startsWith(str)) return true; } return false; } public boolean excludeClass(String classname) { ArrayList exclude = getExclude(); if (exclude == null) return false; for (int i = 0; i < exclude.size(); i++) { String str = exclude.get(i); if (str.equals("*")) return true; if (classname.startsWith(str)) return true; } return false; } public static boolean getPrune() { return AOPClassPoolRepository.getInstance().isPrune(); } public static void setPrune(boolean prune) { AOPClassPoolRepository.getInstance().setPrune(prune); } public static void setClassPoolFactory(ScopedClassPoolFactory factory) { AOPClassPoolRepository.getInstance().setClassPoolFactory(factory); } public static ScopedClassPoolFactory getClassPoolFactory() { return AOPClassPoolRepository.getInstance().getClassPoolFactory(); } public boolean isNonAdvisableClassName(String classname) { if (ignoreClass(classname)) return true; if (includeClass(classname)) return false; if (excludeClass(classname)) return true; return (classname.startsWith("org.jboss.aop.") || classname.endsWith("$aop") || classname.startsWith("javassist") || classname.startsWith("org.jboss.util.") || classname.startsWith("gnu.trove.") || classname.startsWith("EDU.oswego.cs.dl.util.concurrent.") || classname.contains('.' + JoinPointGenerator.JOINPOINT_CLASS_PREFIX) || // System classes classname.startsWith("org.apache.tools.ant") || classname.startsWith("org.apache.crimson") || classname.startsWith("org.apache.xalan") || classname.startsWith("org.apache.xml") || classname.startsWith("org.apache.xpath") || classname.startsWith("org.ietf.") || classname.startsWith("org.omg.") || classname.startsWith("org.w3c.") || classname.startsWith("org.xml.sax.") || classname.startsWith("sunw.") || classname.startsWith("sun.") || classname.startsWith("java.") || classname.startsWith("javax.") || classname.startsWith("com.sun.") || classname.startsWith("junit") || classname.startsWith("jrockit.") || classname.startsWith("com.bea.vm.") || classname.startsWith("$Proxy") ); } /** * This is the hook for ClassLoaders that want to instrument their classes with AOP *

* This would be called during a findClass or loadClass call. The return value * is used by defineClass to create the class from bytecode */ public byte[] transform(ClassLoader loader, String className, @SuppressWarnings(value= {"all"}) Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws Exception { byte[] b = translate(className, loader, classfileBuffer); return b; } /** * This is to be backward compatible with JBoss 3.2.3 Translator interface * * @param className * @param loader * @return * @throws Exception */ public byte[] translate(String className, ClassLoader loader) throws Exception { return translate(className, loader, null); } /** * This is to be backward compatible with JBoss 3.2.3 Translator interface * TODO: stalep, added a synchronized block for the entire method to prevent * a deadlock. its not optimal and should be further reviewed. * (commented out sync block inside the method) * * @param className * @param loader * @return * @throws Exception */ public byte[] translate(String className, ClassLoader loader, byte[] classfileBuffer) throws Exception { try { if (isNonAdvisableClassName(className)) { return null; } lock.lockRead(); try { synchronized(this){ if (weavingStrategy == null) { if (TransformerCommon.isCompileTime() || classicOrder) { weavingStrategy = new ClassicWeavingStrategy(); } else if(InstrumentorFactory.getInstrumentor(this,dynamicStrategy.getJoinpointClassifier()) instanceof GeneratedAdvisorInstrumentor) { weavingStrategy = new SuperClassesFirstWeavingStrategy(); } else { weavingStrategy = new ClassicWeavingStrategy(); } } return weavingStrategy.translate(this, className, loader, classfileBuffer); } } finally { lock.unlockRead(); } } catch (Exception e) { // AutoGenerated throw new RuntimeException(e); } } /** * Add an interceptor factory that can be referenced by name. */ public void addInterceptorFactory(String name, InterceptorFactory factory) { initInterceptorFactoriesMap(); synchronized (interceptorFactories) { interceptorFactories.put(name, factory); } } /** * Remove an interceptor factory that can be referenced by name. */ public void removeInterceptorFactory(String name) { synchronized (interceptorFactories) { interceptorFactories.remove(name); } } public Map getInterceptorFactories() { return interceptorFactories; } /** * Find the interceptor factory that can be referenced by name. */ public InterceptorFactory getInterceptorFactory(String name) { synchronized (interceptorFactories) { return interceptorFactories.get(name); } } public void addPrecedence(PrecedenceDef precedenceDef) { initPrecedenceDefsMap(); synchronized (precedenceDefs) { precedenceDefs.put(precedenceDef.getName(), precedenceDef); } forceResortPrecedenceDefs(); } public void removePrecedence(String name) { synchronized (precedenceDefs) { precedenceDefs.remove(name); } forceResortPrecedenceDefs(); } protected void forceResortPrecedenceDefs() { synchronized (precedenceDefs) { sortedPrecedenceDefEntries = null; } synchronized (subscribedSubDomains) { copySubDomainsFromQueue(true); boolean newSubscribers = true; while (newSubscribers) { for (Domain domain : subscribedSubDomains.keySet()) { domain.forceResortPrecedenceDefs(); } newSubscribers = copySubDomainsFromQueue(false); } } } public LinkedHashMap getPrecedenceDefs() { return precedenceDefs; } public PrecedenceDefEntry[] getSortedPrecedenceDefEntries() { if (sortedPrecedenceDefEntries == null) { synchronized (precedenceDefs) { if (sortedPrecedenceDefEntries == null) { sortedPrecedenceDefEntries = PrecedenceSorter.createOverallPrecedence(this); } } } return sortedPrecedenceDefEntries; } /** * Add a referencable InterceptorStack( <stack> ) */ public void addAdviceStack(AdviceStack stack) { initInerceptorStacksMap(); synchronized (interceptorStacks) { interceptorStacks.put(stack.getName(), stack); } } /** * Remove a referencable InterceptorStack( <stack> ) */ public void removeInterceptorStack(String name) { synchronized (interceptorStacks) { interceptorStacks.remove(name); } } /** * Find an interceptor stack referenced by name ( <stack> ) */ public AdviceStack getAdviceStack(String name) { synchronized (interceptorStacks) { return interceptorStacks.get(name); } } protected boolean attachMetaData(ClassAdvisor advisor, CtClass clazz, boolean addAdvisor) throws Exception { boolean attached = false; synchronized (classMetaData) { for (ClassMetaDataBinding data : classMetaData.values()) { if (data.matches(advisor, clazz)) { attached = true; if (addAdvisor) data.addAdvisor(advisor); ClassMetaDataLoader loader = data.getLoader(); loader.bind(advisor, data, clazz.getDeclaredMethods(), clazz.getDeclaredFields(), clazz.getDeclaredConstructors()); } } } return attached; } protected void attachMetaData(Advisor advisor, Class clazz) { synchronized (classMetaData) { for (ClassMetaDataBinding data : classMetaData.values()) { addAdvisorToClassMetaDataBinding(data, clazz, advisor, clazz); } } } public ClassAdvisor getTempClassAdvisor(CtClass clazz) throws Exception { ClassAdvisor advisor = AdvisorFactory.getClassAdvisor(clazz, this); attachMetaData(advisor, clazz, false); applyInterfaceIntroductions(advisor, clazz); return advisor; } public Advisor getTempClassAdvisorIfNotExist(Class clazz) { Advisor advisor = findAdvisor(clazz); if (advisor != null) return advisor; if (Advised.class.isAssignableFrom(clazz)) { Class superClass = clazz; try { while (superClass != null) { try { Field field = superClass.getDeclaredField(Instrumentor.HELPER_FIELD_NAME); SecurityActions.setAccessible(field); advisor = (ClassAdvisor) field.get(null); if (advisor != null) { return advisor; } else { break; } } catch (NoSuchFieldException e) { superClass = superClass.getSuperclass(); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } advisor = AdvisorFactory.getClassAdvisor(clazz, this); advisor.setClazz(clazz); return advisor; } public DomainDefinition getContainer(String name) { return containers.get(name); } public void addContainer(DomainDefinition def) { initContainersMap(); containers.put(def.getName(), def); } public void removeContainer(String name) { containers.remove(name); } /** * Find a pointcut of with a given name */ public Pointcut getPointcut(String name) { return bindingCollection.getPointcut(name); } /** * Remove an interceptor pointcut with a given name */ public void removePointcut(String name) { bindingCollection.removePointcut(name); } /** * Add an interceptor pointcut with a given name */ public synchronized void addPointcut(Pointcut pointcut) { bindingCollection.add(pointcut, this); } public boolean isExecution() { return bindingCollection.isExecution(); } public boolean isConstruction() { return bindingCollection.isConstruction(); } public boolean isCall() { return bindingCollection.isCall(); } public boolean isWithin() { return bindingCollection.isWithin(); } public boolean isWithincode() { return bindingCollection.isWithincode(); } public boolean isGet() { return bindingCollection.isGet(); } public boolean isSet() { return bindingCollection.isSet(); } /** * Remove an interceptor pointcut with a given name */ public synchronized void removeBinding(String name) { lock.lockWrite(); try { AdviceBinding binding = internalRemoveBinding(name); if (binding != null) { binding.clearAdvisors(); dynamicStrategy.interceptorChainsUpdated(); } } finally { lock.unlockWrite(); } } public synchronized void removeBindings(ArrayList binds) { clearUnregisteredClassLoaders(); HashSet bindingAdvisors = new HashSet(); ArrayList removedBindings = null; lock.lockWrite(); try { removedBindings = this.bindingCollection.removeBindings(binds); for (AdviceBinding removedBinding: removedBindings) { ArrayList ads = removedBinding.getAdvisors(); bindingAdvisors.addAll(ads); Pointcut pointcut = removedBinding.getPointcut(); this.removePointcut(pointcut.getName()); } } finally { lock.unlockWrite(); } Iterator it = bindingAdvisors.iterator(); while (it.hasNext()) { Advisor advisor = it.next(); if (!isAdvisorRegistered(advisor)) { //Check sub domains in case of generated advisors WeakReference ref = getSubDomainsPerClass().get(advisor.getClazz()); Domain domain = null; if (ref != null) domain = ref.get(); if (domain != null) { if (subscribedSubDomains.containsKey(domain) || subscribedSubDomainsQueue.containsKey(domain)) { if (!domain.isAdvisorRegistered(advisor))continue; } else { continue;//If advisor does not belong to a subscribed subdomain, we should not rebuild } } } advisor.removeAdviceBindings(removedBindings); } dynamicStrategy.interceptorChainsUpdated(); } /** * Add an interceptor pointcut with a given name */ public void addBinding(AdviceBinding binding) { Set affectedAdvisors = null; AdviceBinding removedBinding = null; // this locked variable is used in order to avoid breaking the try finally block in two pieces boolean locked = false; try { // EXTREMELY IMPORTANT: get this' lock before the bindingCollection's, or // we will end up with a deadlock synchronized(this) { lock.lockWrite(); locked = true; removedBinding = internalRemoveBinding(binding.getName()); affectedAdvisors = removedBinding == null ? null : new HashSet(removedBinding.getAdvisors()); bindingCollection.add(binding, this); } synchronized (advisors) { Set handledAdvisors = new HashSet(); updateAdvisorsForAddedBinding(binding, handledAdvisors); if (affectedAdvisors != null && affectedAdvisors.size() > 0) { for (Advisor advisor : affectedAdvisors) { if (isAdvisorRegistered(advisor)) advisor.removeAdviceBinding(removedBinding); } } } this.dynamicStrategy.interceptorChainsUpdated(); } finally { if (locked) { lock.unlockWrite(); } } } protected void updateAdvisorsForAddedBinding(AdviceBinding binding, Set handledAdvisors) { synchronized (advisors) { Collection> keys = advisors.keySet(); if (keys.size() > 0) { Iterator> it = keys.iterator(); while (it.hasNext()) { Advisor advisor = getAdvisorFromAdvisorsKeySetIterator(it); if (advisor == null) continue; if (handledAdvisors.contains(advisor)) continue; handledAdvisors.add(advisor); if (binding.getPointcut().softMatch(advisor)) { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("softmatch succeeded for : " + advisor.getName() + " " + binding + " " + binding.getPointcut().getExpr()); advisor.newBindingAdded(binding); //affectedAdvisors.remove(advisor); } else { if (AspectManager.verbose && logger.isDebugEnabled()) logger.debug("softmatch failed for : " + advisor.getName() + " " + binding + " " + binding.getPointcut().getExpr()); } } } } synchronized (subscribedSubDomains) { copySubDomainsFromQueue(true); boolean newSubscribers = true; while (newSubscribers) { Collection domains = subscribedSubDomains.keySet(); if (domains.size() > 0) { //When interceptors are installed as beans in the microcontainer, creating the interceptor instances for (Domain domain : domains) { domain.updateAdvisorsForAddedBinding(binding, handledAdvisors); } } newSubscribers = copySubDomainsFromQueue(false); } } } public void removeClassMetaData(String name) { internalRemoveClassMetaData(name); } public void internalRemoveClassMetaData(String name) { synchronized (classMetaData) { ClassMetaDataBinding meta = classMetaData.remove(name); if (meta == null) return; meta.clearAdvisors(); } } public void addClassMetaData(ClassMetaDataBinding meta) { internalRemoveClassMetaData(meta.getName()); //Add the metadata before we update the advisors. Important for the generated instance advisors initClassMetaDataMap(); synchronized (classMetaData) { classMetaData.put(meta.getName(), meta); } updateAdvisorsForAddedClassMetaData(meta); } protected void updateAdvisorsForAddedClassMetaData(ClassMetaDataBinding meta) { synchronized (advisors) { Iterator> it = advisors.keySet().iterator(); while (it.hasNext()) { Advisor advisor = getAdvisorFromAdvisorsKeySetIterator(it); if (advisor == null) continue; Class clazz = advisor.getClazz(); addAdvisorToClassMetaDataBinding(meta, clazz, advisor, clazz); } } synchronized (subscribedSubDomains) { copySubDomainsFromQueue(true); boolean newSubscribers = true; while (newSubscribers) { if (subscribedSubDomains.size() > 0) { for (Domain domain : subscribedSubDomains.keySet()) { domain.updateAdvisorsForAddedClassMetaData(meta); } } newSubscribers = copySubDomainsFromQueue(false); } } } protected void addAdvisorToClassMetaDataBinding(ClassMetaDataBinding meta, Class clazz, Advisor advisor, Class advisedClass) { if (meta.matches(advisor, clazz)) { meta.addAdvisor(advisor); } else if (advisor.chainOverridingForInheritedMethods()) { //If advisor class does not match class metadata directly, try the superclasses so that methods can inherit //old skool weaving doesn't support metadata overriding for inherited methods, so only do this extra work for generated advisors Class superClass = clazz.getSuperclass(); if (superClass != null && superClass != Object.class) { addAdvisorToClassMetaDataBinding(meta, superClass, advisor, advisedClass); } } } //--- Introductions /** * Retrieve an introduction pointcut of a certain name */ public InterfaceIntroduction getInterfaceIntroduction(String name) { synchronized (interfaceIntroductions) { return interfaceIntroductions.get(name); } } /** * Register an introduction pointcut */ public synchronized void addInterfaceIntroduction(InterfaceIntroduction pointcut) { removeInterfaceIntroduction(pointcut.getName()); initInterfaceIntroductionsMap(); synchronized (interfaceIntroductions) { interfaceIntroductions.put(pointcut.getName(), pointcut); } } /** * remove an introduction pointcut of a certain name */ public void removeInterfaceIntroduction(String name) { synchronized (interfaceIntroductions) { InterfaceIntroduction pointcut = interfaceIntroductions.remove(name); if (pointcut == null) return; pointcut.clearAdvisors(); } } /** * Retrieve an introduction pointcut of a certain name */ public ArrayReplacement getArrayReplacement(String name) { synchronized (arrayReplacements) { return arrayReplacements.get(name); } } /** * Register an introduction pointcut */ public synchronized void addArrayReplacement(ArrayReplacement pointcut) { removeArrayReplacement(pointcut.getName()); initArrayReplacementMap(); synchronized (arrayReplacements) { arrayReplacements.put(pointcut.getName(), pointcut); } } /** * remove an introduction pointcut of a certain name */ public void removeArrayReplacement(String name) { synchronized (arrayReplacements) { arrayReplacements.remove(name); } } /** * Retrieve an introduction pointcut of a certain name */ public ArrayBinding getArrayBinding(String name) { synchronized (arrayBindings) { return arrayBindings.get(name); } } /** * Register an introduction pointcut */ public synchronized void addArrayBinding(ArrayBinding binding) { removeArrayBinding(binding.getName()); initArrayBindingMap(); synchronized (arrayBindings) { arrayBindings.put(binding.getName(), binding); ArrayAdvisor.addBinding(binding); } } /** * remove an introduction pointcut of a certain name */ public void removeArrayBinding(String name) { synchronized (arrayBindings) { ArrayBinding pointcut = arrayBindings.remove(name); if (pointcut == null) return; ArrayAdvisor.removeBinding(pointcut); } } /** * Register an annotation introduction */ public synchronized void addAnnotationIntroduction(AnnotationIntroduction pointcut) { String name = pointcut.getOriginalAnnotationExpr() + pointcut.getOriginalExpression(); removeAnnotationIntroduction(pointcut); initAnnotationIntroductionsMap(); synchronized (annotationIntroductions) { annotationIntroductions.put(name, pointcut); } } /** * remove an annotation pointcut */ public void removeAnnotationIntroduction(AnnotationIntroduction pointcut) { String name = pointcut.getOriginalAnnotationExpr() + pointcut.getOriginalExpression(); synchronized (annotationIntroductions) { annotationIntroductions.remove(name); } } public List getAnnotationIntroductions() { synchronized (annotationIntroductions) { return new ArrayList(annotationIntroductions.values()); } } public synchronized void addDeclare(DeclareDef declare) { removeDeclare(declare.getName()); initDeclaresMap(); synchronized (declares) { declares.put(declare.getName(), declare); } if (declare.isPointcut()) { PointcutStats stats; stats = new PointcutStats(declare.getAst(), manager); stats.matches(); bindingCollection.updateStats(stats); } } public void removeDeclare(String name) { synchronized (declares) { declares.remove(name); } } public Iterator getDeclares() { return declares.values().iterator(); } protected void applyInterfaceIntroductions(Advisor advisor, Class clazz) { Map interfaceIntroductions = getInterfaceIntroductions(); if (interfaceIntroductions != null && interfaceIntroductions.size() > 0) { for (InterfaceIntroduction pointcut : interfaceIntroductions.values()) { if (pointcut.matches(advisor, clazz)) { pointcut.addAdvisor(advisor); } } } } protected void applyInterfaceIntroductions(ClassAdvisor advisor, CtClass clazz) throws Exception { Map interfaceIntroductions = getInterfaceIntroductions(); if (interfaceIntroductions != null && interfaceIntroductions.size() > 0) { for (InterfaceIntroduction pointcut : interfaceIntroductions.values()) { if (pointcut.matches(advisor, clazz)) { pointcut.addAdvisor(advisor); } } } } /** * Register an annotation introduction */ public synchronized void addAnnotationOverride(AnnotationIntroduction pointcut) { String name = pointcut.getOriginalAnnotationExpr() + pointcut.getOriginalExpression(); initAnnotationOverridesMap(); synchronized (annotationOverrides) { annotationOverrides.put(name, pointcut); } updateAdvisorsForAddedAnnotationOverride(pointcut); } public void updateAdvisorsForAddedAnnotationOverride(AnnotationIntroduction introduction) { synchronized (advisors) { Iterator> it = advisors.keySet().iterator(); while (it.hasNext()) { Advisor advisor = getAdvisorFromAdvisorsKeySetIterator(it); if (advisor == null) continue; advisor.deployAnnotationOverride(introduction); } } synchronized (subscribedSubDomains) { copySubDomainsFromQueue(true); boolean newSubscribers = true; while (newSubscribers) { for (Domain domain : subscribedSubDomains.keySet()) { domain.updateAdvisorsForAddedAnnotationOverride(introduction); } newSubscribers = copySubDomainsFromQueue(false); } } } /** * remove an annotation pointcut */ public void removeAnnotationOverride(AnnotationIntroduction pointcut) { String name = pointcut.getOriginalAnnotationExpr() + pointcut.getOriginalExpression(); synchronized (annotationOverrides) { annotationOverrides.remove(name); } } public List getAnnotationOverrides() { synchronized (annotationOverrides) { return new ArrayList(annotationOverrides.values()); } } public Object getPerVMAspect(AspectDefinition def) { return getPerVMAspect(def.getName()); } public Object getPerVMAspect(String def) { Object aspect = perVMAspects.get(def); if (aspect == null) { AspectDefinition adef = aspectDefinitions.get(def); if (adef != null && adef.getScope() == Scope.PER_VM) { synchronized (adef) { // double check but, now, in a sync block aspect = perVMAspects.get(def); if (aspect == null) { aspect = createPerVmAspect(def, adef, null); } } } } if (aspect == NULL_ASPECT) { return null; } return aspect; } protected Object createPerVmAspect(String def, AspectDefinition adef, ClassLoader scopedClassLoader) { Object instance = null; synchronized (adef) { try { if (scopedClassLoader != null && adef.getFactory() instanceof AspectFactoryWithClassLoader) { //If a scoped classloader with no parent delegation redefines the class, we need to make sure that that class is pushed on the stack ((AspectFactoryWithClassLoader)adef.getFactory()).pushScopedClassLoader(scopedClassLoader); } instance = adef.getFactory().createPerVM(); initPerVMAspectsMap(); if (instance == null) { // indicates that the factory must not be called again // the factory has already been called and returned null perVMAspects.put(def, NULL_ASPECT); } else { perVMAspects.put(def, instance); } } finally { if (scopedClassLoader != null && adef.getFactory() instanceof AspectFactoryWithClassLoader) { ((AspectFactoryWithClassLoader)adef.getFactory()).popScopedClassLoader(); } } } return instance; } public void addAspectDefinition(AspectDefinition def) { removeAspectDefinition(def.getName()); initAspectDefintitionsMap(); aspectDefinitions.put(def.getName(), def); } public void removeAspectDefinition(String name) { internalRemoveAspectDefintion(name); } protected AspectDefinition internalRemoveAspectDefintion(String name) { AspectDefinition def = aspectDefinitions.remove(name); if (def != null) { def.undeploy(); if (def.getScope() == Scope.PER_VM) perVMAspects.remove(def.getName()); } return def; } public Map getAspectDefinitions() { return aspectDefinitions; } public AspectDefinition getAspectDefinition(String name) { return aspectDefinitions.get(name); } public synchronized void addTypedef(Typedef def) throws Exception { removeTypedef(def.getName()); initTypedefsMap(); synchronized (typedefs) { typedefs.put(def.getName(), def); } } public void removeTypedef(String name) { synchronized (typedefs) { typedefs.remove(name); } } public Typedef getTypedef(String name) { synchronized (typedefs) { return typedefs.get(name); } } public Map getInterfaceIntroductions() { return interfaceIntroductions; } public Map getArrayReplacements() { return arrayReplacements; } public Map getTypedefs() { return typedefs; } public Map getInterceptorStacks() { return interceptorStacks; } public Map getClassMetaDataLoaders() { return classMetaDataLoaders; } public Map getCflowStacks() { return cflowStacks; } public Map getDynamicCFlows() { return dynamicCFlows; } public Map getPerVMAspects() { return perVMAspects; } public Map getClassMetaData() { return classMetaData; } /** * Returns the dynamic aop strategy to be used. */ public DynamicAOPStrategy getDynamicAOPStrategy() { return this.dynamicStrategy; } /** * Sets the dynamic aop strategy to be used. * Should be called only before any class is transformed. * @param strategy the new dynamic aop strategy. */ public void setDynamicAOPStrategy(DynamicAOPStrategy strategy) { // avoid users calling this method in run time if (hasTransformationStarted()) { throw new RuntimeException("Dynamic AOP Strategy Update not allowed in run time"); } this.dynamicStrategy = strategy; } /** * Removes an AdviceBinding without notifying dynamic aop strategy. * @param name the binding to be removed. */ private synchronized AdviceBinding internalRemoveBinding(String name) { AdviceBinding binding = bindingCollection.removeBinding(name); if (binding == null) { return null; } Pointcut pointcut = binding.getPointcut(); this.removePointcut(pointcut.getName()); return binding; } // public void setBindings(LinkedHashMap bindings) // { // initBindingsMap(); // this.bindings.clear(); // this.bindings.putAll(bindings); // } public void addSubDomainPerClass(Class clazz, Domain domain) { synchronized (getSubDomainsPerClass()) { getSubDomainsPerClass().put(clazz, new WeakReference(domain)); } } /** * Add subscriber to queue * @see AspectManager#copySubDomainsFromQueue(boolean) */ public void subscribeSubDomain(Domain domain) { initSubscribedSubDomainsMap(); initSubscribedSubDomainsQueueMap(); synchronized (subscribedSubDomains) { subscribedSubDomainsQueue.put(domain, "Contents do not matter"); } } public void unsubscribeSubDomain(Domain domain) { synchronized (subscribedSubDomains) { subscribedSubDomains.remove(domain); } } public Map getSubscribedSubDomains() { return subscribedSubDomains; } private Advisor getAdvisorFromAdvisorsKeySetIterator(Iterator> it) { Class clazz = it.next(); if (classLoaderValidator != null && !classLoaderValidator.isValidClassLoader(SecurityActions.getClassLoader(clazz))) { it.remove(); return null; } WeakReference ref = advisors.get(clazz); if (ref == null) return null; Advisor advisor = ref.get(); if (advisor == null) { it.remove(); return null; } return advisor; } /** * When running in the microcontainer with aspects installed as beans, a ClassProxyContainer will be created per bean * to check if this bean needs interceptors, each container creates a sunscribed domain for matching. This subscribed * domain is added to a queue, which is checked when we need to iterate over the subscribed domains. */ private boolean copySubDomainsFromQueue(boolean increment) { boolean copied = false; initSubscribedSubDomainsMap(); synchronized (subscribedSubDomains) { if (!increment && subscribedDomainQueueRef > 0) subscribedDomainQueueRef--; if (subscribedDomainQueueRef == 0 && subscribedSubDomainsQueue.size() > 0){ subscribedSubDomains.putAll(subscribedSubDomainsQueue); subscribedSubDomainsQueue.clear(); copied = true; } if (increment) subscribedDomainQueueRef++; } return copied; } public void addLifecycleDefinition(AspectDefinition def) { lifecycleManager.addLifecycleDefinition(def); } public void removeLifecycleDefinition(String name) { lifecycleManager.removeLifecycleDefinition(name); } public void addLifecycleBinding(LifecycleCallbackBinding lifecycleBinding) { lifecycleManager.addLifecycleBinding(lifecycleBinding); } public Map getLifecycleBindings() { return lifecycleManager.getLifecycleBindings(); } public void removeLifecycleBinding(String name) { lifecycleManager.removeLifecycleBinding(name); } public static boolean hasTransformationStarted() { return WeavingStrategySupport.transformationStarted(); } // public void dumpSubDomainsAndAdvisors(int indent) // { // indent(indent); // System.out.println("Manager: " + this); // indent++; // indent(indent); // System.out.println(""); // //indent(indent); // // for (Iterator it = advisors.keySet().iterator() ; it.hasNext() ; ) // { // Class clazz = (Class) it.next(); // Advisor advisor = null; // WeakReference ref = (WeakReference) advisors.get(clazz); // if (ref != null) advisor = (Advisor) ref.get(); // indent(indent); // System.out.println(System.identityHashCode(advisor) + " " + advisor); // indent(indent); // } // indent--; // indent(indent); // System.out.println(""); // // indent(indent); // System.out.println(""); // indent++; // for (Iterator it = subscribedSubDomains.keySet().iterator(); it.hasNext() ; ) // { // AspectManager manager = (AspectManager)it.next(); // manager.dumpSubDomainsAndAdvisors(indent); // } // indent--; // indent(indent); // System.out.println(""); // indent--; // // } // // private void indent(int indent) // { // for (int i = 0 ; i < indent ; i++) System.out.print(" "); // } protected void initSubDomainsByNameMap() { if (subDomainsByName == UnmodifiableEmptyCollections.EMPTY_WEAK_VALUE_HASHMAP) { synchronized(lazyCollectionLock) { if (subDomainsByName == UnmodifiableEmptyCollections.EMPTY_WEAK_VALUE_HASHMAP) { subDomainsByName = new WeakValueHashMap(); } } } } protected void initSubscribedSubDomainsMap() { if (subscribedSubDomains == UnmodifiableEmptyCollections.EMPTY_WEAK_HASHMAP) { synchronized(lazyCollectionLock) { if (subscribedSubDomains == UnmodifiableEmptyCollections.EMPTY_WEAK_HASHMAP) { subscribedSubDomains = new WeakHashMap(); } } } } protected void initSubscribedSubDomainsQueueMap() { if (subscribedSubDomainsQueue == UnmodifiableEmptyCollections.EMPTY_WEAK_HASHMAP) { synchronized(lazyCollectionLock) { if (subscribedSubDomainsQueue == UnmodifiableEmptyCollections.EMPTY_WEAK_HASHMAP) { subscribedSubDomainsQueue = new WeakHashMap(); } } } } protected void initInterfaceIntroductionsMap() { if (interfaceIntroductions == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (interfaceIntroductions == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { interfaceIntroductions = new LinkedHashMap(); } } } } protected void initArrayReplacementMap() { if (arrayReplacements == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (arrayReplacements == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { arrayReplacements = new LinkedHashMap(); } } } } protected void initArrayBindingMap() { if (arrayBindings == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (arrayBindings == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { arrayBindings = new LinkedHashMap(); } } } } protected void initAnnotationIntroductionsMap() { if (annotationIntroductions == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (annotationIntroductions == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { annotationIntroductions = new LinkedHashMap(); } } } } protected void initAnnotationOverridesMap() { if (annotationOverrides == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (annotationOverrides == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { annotationOverrides = new LinkedHashMap(); } } } } protected void initTypedefsMap() { if (typedefs == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (typedefs == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { typedefs = new LinkedHashMap(); } } } } protected void initInterceptorFactoriesMap() { if (interceptorFactories == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { synchronized(lazyCollectionLock) { if (interceptorFactories == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { interceptorFactories = new HashMap(); } } } } protected void initClassMetaDataLoadersMap() { if (classMetaDataLoaders == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { synchronized(lazyCollectionLock) { if (classMetaDataLoaders == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { classMetaDataLoaders = new HashMap(); } } } } protected void initInerceptorStacksMap() { if (interceptorStacks == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { synchronized(lazyCollectionLock) { if (interceptorStacks == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { interceptorStacks = new HashMap(); } } } } protected void initDeclaresMap() { if (declares == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { synchronized(lazyCollectionLock) { if (declares == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { declares = new HashMap(); } } } } protected void initCflowStacksMap() { if (cflowStacks == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (cflowStacks == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { cflowStacks = new ConcurrentHashMap(); } } } } protected void initDynamicCflowsMap() { if (dynamicCFlows == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (dynamicCFlows == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { dynamicCFlows = new ConcurrentHashMap(); } } } } protected void initAspectDefintitionsMap() { if (aspectDefinitions == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (aspectDefinitions == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { aspectDefinitions = new ConcurrentHashMap(); } } } } protected void initPerVMAspectsMap() { if (perVMAspects == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { synchronized(lazyCollectionLock) { if (perVMAspects == UnmodifiableEmptyCollections.EMPTY_CONCURRENT_HASHMAP) { perVMAspects = new ConcurrentHashMap(); } } } } protected void initClassMetaDataMap() { if (classMetaData == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (classMetaData == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { classMetaData = new LinkedHashMap(); } } } } protected void initContainersMap() { if (containers == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { synchronized(lazyCollectionLock) { if (containers == UnmodifiableEmptyCollections.EMPTY_HASHMAP) { containers = new HashMap(); } } } } protected void initPrecedenceDefsMap() { if (precedenceDefs == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { synchronized(lazyCollectionLock) { if (precedenceDefs == UnmodifiableEmptyCollections.EMPTY_LINKED_HASHMAP) { precedenceDefs = new LinkedHashMap(); } } } } } libjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/instrument/0000755000175000017500000000000011145122066030061 5ustar twernertwerner././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/instrument/GeneratedAdvisorCallerInfoAdder.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/instrument/GeneratedAdvisorC0000644000175000017500000000715311145122064033341 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.instrument; import javassist.CannotCompileException; import javassist.CtClass; import javassist.Modifier; import javassist.NotFoundException; /** * Adds CallerInfo fields to generated advisor * * @author Kabir Khan * @version $Revision$ */ public class GeneratedAdvisorCallerInfoAdder extends CallerInfoAdder { public GeneratedAdvisorCallerInfoAdder(Instrumentor instrumentor) { super(instrumentor, Modifier.PROTECTED); } protected void addMethodByMethodInfoField(CtClass addTo, String fieldName, long callingHash, String classname, long calledHash) throws NotFoundException, CannotCompileException { // addTo is the advisor class String init = "resolveCallerMethodInfo(" + callingHash + "L, \"" + classname + "\", " + calledHash + "L)"; addMethodByMethodInfoField(addTo, fieldName, null); ((GeneratedAdvisorInstrumentor)instrumentor).initialiseCallerInfoField(fieldName, init); } protected void addConByMethodInfoField(CtClass addTo, String fieldName, long callingHash, String classname, long calledHash) throws NotFoundException, CannotCompileException { String init = "resolveCallerConstructorInfo(" + callingHash + "L, \"" + classname + "\", " + calledHash + "L)"; addConByMethodInfoField(addTo, fieldName, null); ((GeneratedAdvisorInstrumentor)instrumentor).initialiseCallerInfoField(fieldName, init); } protected void addConByConInfoField(CtClass addTo, String fieldName, String callingClassName, int callingIndex, String classname, long calledHash) throws NotFoundException, CannotCompileException { String init = "resolveConstructorCallerConstructorInfo(" + callingClassName + ".class, " + callingIndex + ", \"" + classname + "\", " + calledHash + "L)"; addConByConInfoField(addTo, fieldName, null); ((GeneratedAdvisorInstrumentor)instrumentor).initialiseCallerInfoField(fieldName, init); } protected void addMethodByConInfoField(CtClass addTo, String fieldName, String callingClassName, int callingIndex, String classname, long calledHash) throws NotFoundException, CannotCompileException { String init = "resolveConstructorCallerMethodInfo(" + callingClassName + ".class, " + callingIndex + ", \"" + classname + "\", " + calledHash + "L)"; addMethodByConInfoField(addTo, fieldName, null); ((GeneratedAdvisorInstrumentor)instrumentor).initialiseCallerInfoField(fieldName, init); } protected boolean addInfoAsWeakReference() { return false; } protected boolean markInfoAsSynthetic() { return true; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/instrument/JoinpointClassifier.javalibjboss-aop-java-2.0.1.GA.orig/src/aspect-framework/main/org/jboss/aop/instrument/JoinpointClassifi0000644000175000017500000002274011145122060033432 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.instrument; import java.util.Collection; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMember; import javassist.CtMethod; import javassist.NotFoundException; import org.jboss.aop.Advisor; import org.jboss.aop.pointcut.Pointcut; import org.jboss.aop.pointcut.PointcutInfo; /** * This class performs the joinpoint classifications. It is responsible for classifying * a joinpoint into: