diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ebda2a8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,53 @@ +# built application files +*.apk +*.ap_ + +# files for the dex VM +*.dex + +# Java class files +*.class + +# generated files +bin/ +gen/ +out/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Eclipse project files +.classpath +.project + +# Windows thumbnail db +.DS_Store + +# IDEA/Android Studio project files, because +# the project can be imported from settings.gradle +.idea +*.iml + +# Old-style IDEA project files +*.ipr +*.iws + +# Local IDEA workspace +.idea/workspace.xml + +# Gradle cache +.gradle + +# Sandbox stuff +_sandbox + +# Backup files +*~ + +.directory +*.trace +*.hprof +logs/ +captures/ +.localrepo diff --git a/README.md b/README.md new file mode 100644 index 0000000..92944d1 --- /dev/null +++ b/README.md @@ -0,0 +1,107 @@ +# Hook + +Minimalist, annotation based, hook framework for Java/Android built on top of [AspectJ](https://eclipse.org/aspectj/). + +# Basic Usage + +```java + +public class Math { + + @Hooked("my_hook") + public int add(int a,int b) { + return a+b; + } +} + +public class IncrementHook { + + @Hook("my_hook") + int hook(HookedMethod method) throws Throwable { + return method.proceed() + 1; // add one + } +} + +final Math math = new Math(); +final IncrementHook hook = new IncrementHook(); + +Hooker.instance().register(hook); +assertThat(math.add(5, 3), is(9)); // 5 + 3 = 9 +Hooker.instance().unregister(hook); +assertThat(math.add(5, 3), is(8)); // 5 + 3 = 8 + +``` + +# Advanced Usage + +```java + +public class Math { + + @Hooked("my_hook") + public int add(@Param("a") int a, @Param("b") int b) { + System.out.println(" calling add("+a+", "+b+")"); + return a+b; + } +} + +public class Hooks { + + @Before("my_hook") + void before(int a, int b) { + System.out.println(" @Before(a="+a+", b="+b+")"); + } + + @Call("my_hook") + void call(int a, int b) { + System.out.println("@Call(a="+a+", b="+b+")"); + } + + @After("my_hook") + void after(@Param("a") int a, @Param("b") int b, @Target Math math, @Result int result) { + System.out.println(" @After(a="+a+", b="+b+", result="+result+")"); + } + + @Returning("my_hook") + void returning(@Param("a") int a, @Param("b") int b, @Result int result) { + System.out.println("@Returning(a="+a+", b="+b+", result="+result+")"); + } + + @Hook("my_hook") + int hook(HookedMethod method, @Param("a") int a, @Param("b") int b, @Target Math math) throws Throwable { + System.out.println("entering @Hook(a="+a+", b="+b+")"); + int ret = method.proceed(2*a, 2*b) + 1; // double operands and increment result + System.out.println("exiting @Hook (return "+ret+")"); + return ret; + } +} + +final Math math = new Math(); +final Hooks hook = new Hooks(); + +Hooker.instance().register(hook); +assertThat(math.add(5, 3), is(17)); +Hooker.instance().unregister(hook); +``` + +For clarity, here's the output of the snippet above : + +``` +@Call(a=5, b=3) +entering @Hook(a=5, b=3) + @Before(a=10, b=6) + calling add(10, 6) + @After(a=10, b=6, result=16) +exiting @Hook (return 17) +@Returning(a=10, b=6, result=17) +``` + +# Installation + +## Android Studio (Gradle) +TODO + + + + + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..14ab10b --- /dev/null +++ b/build.gradle @@ -0,0 +1,31 @@ +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.1.2' + } +} + +allprojects { + + repositories { + jcenter() + maven { url "https://jitpack.io" } + } +} + +ext { + ASPECTJ_VERSION = '1.8.9' +} + +ext.deps = [ + aspectj: [ + core: "org.aspectj:aspectjrt:${ext.ASPECTJ_VERSION}", + tools: "org.aspectj:aspectjtools:${ext.ASPECTJ_VERSION}", + ], +] + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..1d3591c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..eea4f13 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Dec 28 10:00:20 PST 2015 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.12-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..9d82f78 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/plugin/.gitignore b/plugin/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/plugin/.gitignore @@ -0,0 +1 @@ +/build diff --git a/plugin/build.gradle b/plugin/build.gradle new file mode 100644 index 0000000..993f573 --- /dev/null +++ b/plugin/build.gradle @@ -0,0 +1,13 @@ +apply plugin: 'groovy' +apply plugin: 'maven' + +targetCompatibility = '1.7' +sourceCompatibility = '1.7' + +dependencies { + compile gradleApi() + compile localGroovy() + compile 'com.android.tools.build:gradle:1.3.1' + compile deps.aspectj.core + compile deps.aspectj.tools +} \ No newline at end of file diff --git a/plugin/src/main/groovy/com/mypopsy/hook/HookPlugin.groovy b/plugin/src/main/groovy/com/mypopsy/hook/HookPlugin.groovy new file mode 100644 index 0000000..7f9904e --- /dev/null +++ b/plugin/src/main/groovy/com/mypopsy/hook/HookPlugin.groovy @@ -0,0 +1,71 @@ +package com.mypopsy.hook + +import com.android.build.gradle.AppPlugin +import com.android.build.gradle.LibraryPlugin +import org.aspectj.bridge.IMessage +import org.aspectj.bridge.MessageHandler +import org.aspectj.tools.ajc.Main +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.tasks.compile.JavaCompile + +class HookPlugin implements Plugin { + + @Override void apply(Project project) { + def hasApp = project.plugins.withType(AppPlugin) + def hasLib = project.plugins.withType(LibraryPlugin) + if (!hasApp && !hasLib) { + throw new IllegalStateException("'android' or 'android-library' plugin required.") + } + + final def log = project.logger + final def variants + if (hasApp) { + variants = project.android.applicationVariants + } else { + variants = project.android.libraryVariants + } + + + variants.all { variant -> + JavaCompile javaCompile = variant.javaCompile + javaCompile.doLast { + String[] args = [ + "-showWeaveInfo", + "-1.5", + "-inpath", javaCompile.destinationDir.toString(), + "-aspectpath", javaCompile.classpath.asPath, + "-d", javaCompile.destinationDir.toString(), + "-classpath", javaCompile.classpath.asPath, + "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator) + ] + log.debug "ajc args: " + Arrays.toString(args) + + MessageHandler handler = new MessageHandler(true); + new Main().run(args, handler); + for (IMessage message : handler.getMessages(null, true)) { + switch (message.getKind()) { + case IMessage.ABORT: + case IMessage.ERROR: + case IMessage.FAIL: + log.error message.message, message.thrown + break; + case IMessage.WARNING: + log.warn message.message, message.thrown + break; + case IMessage.INFO: + log.info message.message, message.thrown + break; + case IMessage.DEBUG: + log.debug message.message, message.thrown + break; + } + } + } + } + + project.dependencies { + compile 'com.github.renaudcerrato.Hook:runtime:1.0.0' + } + } +} \ No newline at end of file diff --git a/plugin/src/main/resources/META-INF/gradle-plugins/hook.properties b/plugin/src/main/resources/META-INF/gradle-plugins/hook.properties new file mode 100644 index 0000000..6f1d702 --- /dev/null +++ b/plugin/src/main/resources/META-INF/gradle-plugins/hook.properties @@ -0,0 +1 @@ +implementation-class=com.mypopsy.hook.HookPlugin \ No newline at end of file diff --git a/runtime/.gitignore b/runtime/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/runtime/.gitignore @@ -0,0 +1 @@ +/build diff --git a/runtime/build.gradle b/runtime/build.gradle new file mode 100644 index 0000000..aa96fd2 --- /dev/null +++ b/runtime/build.gradle @@ -0,0 +1,36 @@ +buildscript { + repositories { + maven { + url "https://maven.eveoh.nl/content/repositories/releases" + } + } + + dependencies { + classpath "nl.eveoh:gradle-aspectj:1.6" + } +} + +repositories { + mavenCentral() +} + +project.ext { + aspectjVersion = ASPECTJ_VERSION +} + +apply plugin: 'java' +apply plugin: 'maven' +apply plugin: 'aspectj' + +targetCompatibility = '1.7' +sourceCompatibility = '1.7' + + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile deps.aspectj.core + + testCompile 'junit:junit:4.12' + testCompile "org.mockito:mockito-core:1.10.19" + testAspectpath sourceSets.main.output +} \ No newline at end of file diff --git a/runtime/src/main/java/com/mypopsy/hook/HookAspect.java b/runtime/src/main/java/com/mypopsy/hook/HookAspect.java new file mode 100644 index 0000000..9197847 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/HookAspect.java @@ -0,0 +1,84 @@ +package com.mypopsy.hook; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; + +import java.lang.reflect.Method; + +@Aspect +public class HookAspect { + + private HookAspect() {} + + @Pointcut("@annotation(com.mypopsy.hook.annotations.Register)") + public void annotationRegister() {} + + @Pointcut("@annotation(com.mypopsy.hook.annotations.Unregister)") + public void annotationUnregister() {} + + @Pointcut("@annotation(com.mypopsy.hook.annotations.Hooked)") + public void annotationHooked() {} + + @Pointcut("execution(* *(..))") + public void atExecution(){} + + @Before("annotationRegister() && atExecution()") + public void register(JoinPoint pointcut) { + Hooker.instance().register(pointcut.getTarget()); + } + + @After("annotationUnregister() && atExecution()") + public void unregister(JoinPoint pointcut) { + Hooker.instance().unregister(pointcut.getTarget()); + } + + @Around("annotationHooked() && atExecution()") + public Object hooked(final ProceedingJoinPoint joinPoint) throws Throwable { + return Hooker.instance().proceed(new HookedMethodImpl(joinPoint)); + } + + static private class HookedMethodImpl extends HookedMethod { + + private ProceedingJoinPoint joinPoint; + + public HookedMethodImpl(ProceedingJoinPoint joinPoint) { + this.joinPoint = joinPoint; + } + + @Override + public Object proceed() throws Throwable { + return joinPoint.proceed(); + } + + @Override + public Object proceed(Object... args) throws Throwable { + return joinPoint.proceed(args); + } + + @Override + public Method method() { + return ((MethodSignature)joinPoint.getSignature()).getMethod(); + } + + @Override + public Object target() { + return joinPoint.getTarget(); + } + + @Override + public Object[] args() { + return joinPoint.getArgs(); + } + + @Override + public String toString() { + return joinPoint.toString(); + } + } +} diff --git a/runtime/src/main/java/com/mypopsy/hook/HookedMethod.java b/runtime/src/main/java/com/mypopsy/hook/HookedMethod.java new file mode 100644 index 0000000..7de9676 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/HookedMethod.java @@ -0,0 +1,41 @@ +package com.mypopsy.hook; + +import com.mypopsy.hook.annotations.Param; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +abstract public class HookedMethod { + + private Map namedArguments; + + public T proceed() throws Throwable { + return proceed(args()); + } + + abstract public T proceed(Object ... args) throws Throwable; + abstract public Method method(); + abstract public Object target(); + abstract public Object[] args(); + + + int getPosition(Param param) { + if(namedArguments == null) { + final Annotation[][] annotations = method().getParameterAnnotations(); + namedArguments = new HashMap<>(); + for(int i = 0; i < annotations.length; i++) { + for(Annotation annotation: annotations[i]) { + if(annotation instanceof Param) { + namedArguments.put(((Param) annotation).value(), i); + break; + } + } + } + } + final Integer position = namedArguments.get(param.value()); + if(position == null) return -1; + return position; + } +} diff --git a/runtime/src/main/java/com/mypopsy/hook/HookedMethodDelegate.java b/runtime/src/main/java/com/mypopsy/hook/HookedMethodDelegate.java new file mode 100644 index 0000000..e38014f --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/HookedMethodDelegate.java @@ -0,0 +1,53 @@ +package com.mypopsy.hook; + +import com.mypopsy.hook.annotations.Param; + +import java.lang.reflect.Method; + +class HookedMethodDelegate extends HookedMethod { + + private final HookedMethod instance; + + HookedMethodDelegate(HookedMethod instance) { + this.instance = instance; + } + + @Override + public int getPosition(Param param) { + return instance.getPosition(param); + } + + @Override + public Object proceed() throws Throwable { + return instance.proceed(); + } + + @Override + public Object proceed(Object... args) throws Throwable { + return instance.proceed(args); + } + + @Override + public Method method() { + return instance.method(); + } + + @Override + public Object target() { + return instance.target(); + } + + @Override + public Object[] args() { + return instance.args(); + } + + @Override + public String toString() { + return instance.toString(); + } + + final public HookedMethod delegate() { + return instance; + } +} \ No newline at end of file diff --git a/runtime/src/main/java/com/mypopsy/hook/Hooker.java b/runtime/src/main/java/com/mypopsy/hook/Hooker.java new file mode 100644 index 0000000..ba4bced --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/Hooker.java @@ -0,0 +1,523 @@ +package com.mypopsy.hook; + +import com.mypopsy.hook.annotations.After; +import com.mypopsy.hook.annotations.Before; +import com.mypopsy.hook.annotations.Call; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.annotations.Param; +import com.mypopsy.hook.annotations.Result; +import com.mypopsy.hook.annotations.Returning; +import com.mypopsy.hook.annotations.Target; +import com.mypopsy.hook.internal.OrderedLinkedList; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class Hooker { + + private static Hooker sInstance; + + private final Map> hooks = + Collections.synchronizedMap(new HashMap>()); + + private final Map> befores = + Collections.synchronizedMap(new HashMap>()); + + private final Map> calls = + Collections.synchronizedMap(new HashMap>()); + + private final Map> afters = + Collections.synchronizedMap(new HashMap>()); + + private final Map> returnings = + Collections.synchronizedMap(new HashMap>()); + + private final HashMap> subscribers = new HashMap<>(); + + + public static Hooker instance() { + if(sInstance == null) sInstance = new Hooker(); + return sInstance; + } + + private Hooker() {} + + public synchronized void register(Object subscriber) { + if(isRegistered(subscriber)) return; + + Class klass = subscriber.getClass(); + while (klass != Object.class) + { + final List allMethods = new ArrayList<>(Arrays.asList(klass.getDeclaredMethods())); + for (final Method method : allMethods) { + if(method.isBridge() || method.isSynthetic()) { + continue; + } + if (method.isAnnotationPresent(Hook.class)) { + register(subscriber, method, method.getAnnotation(Hook.class)); + }else if (method.isAnnotationPresent(Before.class)) { + register(subscriber, method, method.getAnnotation(Before.class)); + }else if (method.isAnnotationPresent(After.class)) { + register(subscriber, method, method.getAnnotation(After.class)); + }else if (method.isAnnotationPresent(Call.class)) { + register(subscriber, method, method.getAnnotation(Call.class)); + }else if (method.isAnnotationPresent(Returning.class)) { + register(subscriber, method, method.getAnnotation(Returning.class)); + } + } + klass = klass.getSuperclass(); + } + } + + public boolean isRegistered(Object object) { + return subscribers.containsKey(object); + } + + public synchronized void unregister(Object subscriber) { + final Set entries = subscribers.remove(subscriber); + if(entries == null) return; + for(OrderedLinkedList.Node entry : entries) { + entry.remove(); + } + } + + private void register(Object subscriber, Method method, Hook annotation) { + if(annotation == null) return; + + final String name = annotation.value(); + LL nodes = hooks.get(name); + + if(nodes == null) { + hooks.put(name, nodes = new LL<>()); + } + + add(subscriber, nodes.insert(nodes.new HookEntry(subscriber, method, annotation.priority()))); + } + + private void register(Object subscriber, Method method, Before annotation) { + if(annotation == null) return; + + final String name = annotation.value(); + LL nodes = befores.get(name); + + if(nodes == null) { + befores.put(name, nodes = new LL<>()); + } + + add(subscriber, nodes.insert(nodes.new BeforeEntry(subscriber, method, annotation.priority()))); + } + + private void register(Object subscriber, Method method, Call annotation) { + if(annotation == null) return; + + final String name = annotation.value(); + LL nodes = calls.get(name); + + if(nodes == null) { + calls.put(name, nodes = new LL<>()); + } + + add(subscriber, nodes.insert(nodes.new BeforeEntry(subscriber, method, annotation.priority()))); + } + + private void register(Object subscriber, Method method, After annotation) { + if(annotation == null) return; + + final String name = annotation.value(); + LL nodes = afters.get(name); + + if(nodes == null) { + afters.put(name, nodes = new LL<>()); + } + + add(subscriber, nodes.insert(nodes.new AfterEntry(subscriber, method, annotation.priority()))); + } + + private void register(Object subscriber, Method method, Returning annotation) { + if(annotation == null) return; + + final String name = annotation.value(); + LL nodes = returnings.get(name); + + if(nodes == null) { + returnings.put(name, nodes = new LL<>()); + } + + add(subscriber, nodes.insert(nodes.new AfterEntry(subscriber, method, annotation.priority()))); + } + + private void add(Object subscriber, OrderedLinkedList.Node entry) { + Set set = subscribers.get(subscriber); + + if(set == null) { + subscribers.put(subscriber, set = new HashSet<>()); + } + + set.add(entry); + } + + /*package*/ Object proceed(HookedMethod root) throws Throwable { + return new AroundHookedMethod(new BeforeHookedMethod(new AfterHookedMethod(root))).proceed(); + } + + private class AroundHookedMethod extends HookedMethodDelegate { + + AroundHookedMethod(HookedMethod instance) { + super(instance); + } + + @Override + public Object proceed() throws Throwable { + return proceed(args()); + } + + @Override + public Object proceed(Object... args) throws Throwable { + final Hooked hook = method().getAnnotation(Hooked.class); + notifyCall(hook, args); + + final LL nodes = hooks.get(hook.value()); + if(nodes != null) { + final LL.HookEntry first = nodes.first(); + if(first != null) { + final Object ret = first.proceed(delegate(), args); + notifyReturning(hook, args, ret); + return ret; + } + } + + final Object ret = super.proceed(args); + notifyReturning(hook, args, ret); + return ret; + } + + private void notifyCall(Hooked annotation, Object[] args) throws Throwable { + final LL nodes = calls.get(annotation.value()); + if(nodes == null) return; + for(LL.BeforeEntry entry: nodes) { + entry.invoke(delegate(), args); + } + } + + private void notifyReturning(Hooked annotation, Object[] args, Object ret) throws Throwable { + final LL nodes = returnings.get(annotation.value()); + if(nodes == null) return; + for(LL.AfterEntry entry: nodes) { + entry.invoke(delegate(), args, ret); + } + } + } + + private class BeforeHookedMethod extends HookedMethodDelegate { + + BeforeHookedMethod(HookedMethod instance) { + super(instance); + } + + @Override + public Object proceed() throws Throwable { + return proceed(args()); + } + + @Override + public Object proceed(Object... args) throws Throwable { + final Hooked annotation = method().getAnnotation(Hooked.class); + final LL nodes = befores.get(annotation.value()); + if(nodes != null) { + for(LL.BeforeEntry entry: nodes) { + entry.invoke(delegate(), args); + } + } + return super.proceed(args); + } + } + + private class AfterHookedMethod extends HookedMethodDelegate { + + AfterHookedMethod(HookedMethod instance) { + super(instance); + } + + @Override + public Object proceed() throws Throwable { + return proceed(args()); + } + + @Override + public Object proceed(Object... args) throws Throwable { + final Hooked annotation = method().getAnnotation(Hooked.class); + final LL nodes = afters.get(annotation.value()); + final Object ret = super.proceed(args); + if(nodes != null) { + for(LL.AfterEntry entry : nodes) { + entry.invoke(delegate(), args, ret); + } + } + return ret; + } + } + + @SuppressWarnings("unchecked") + private static class LL extends OrderedLinkedList { + + abstract class Entry extends Node { + + final Object target; + final Method method; + final int priority; + + final Annotation annotations[]; + + protected Entry(Object target, Method method, int priority) { + this.target = target; + this.method = method; + this.priority = priority; + + final Annotation[][] a = method.getParameterAnnotations(); + annotations = new Annotation[a.length]; + + for(int i = 0; i < annotations.length; i++) { + for(Annotation an: a[i]) { + if(isSupported(an, i)) { + annotations[i] = an; + break; + } + } + } + } + + protected abstract boolean isSupported(Annotation annotation, int position); + + Object invoke(Object[] args) throws InvocationTargetException, IllegalAccessException { + + if(!method.isAccessible()) { + method.setAccessible(true); + } + + if(args == null || args.length == 0) + return method.invoke(target); + else + return method.invoke(target, args); + } + + @Override + public int compareTo(Node other) { + return priority - ((Entry)other).priority; + } + } + + class HookEntry extends Entry { + + HookEntry(Object target, Method method, int priority) { + super(target, method, priority); + + final Class[] types = method.getParameterTypes(); + if(types.length == 0 || !HookedMethod.class.isAssignableFrom(types[0])) { + throw new IllegalArgumentException(method+": first argument must be of type "+HookedMethod.class); + } + } + + @Override + protected boolean isSupported(Annotation annotation, int position) { + if(position > 1) { + final Annotation previous = annotations[position - 1]; + if (annotation == null && previous != null || annotation != null && previous == null) + throw new IllegalArgumentException(method + + ": missing annotation on argument " + position + + " (either none or all optional arguments must be annotated)"); + } + + if(annotation instanceof Result) + throw new IllegalArgumentException(Result.class+" annotation can only be used" + +" on methods annotated with @" + After.class + " or @" + Returning.class); + + return annotation instanceof Param || annotation instanceof Target; + } + + Object proceed(final HookedMethod hooked, Object[] args) throws Throwable { + final Object[] invokeArgs = new Object[annotations.length]; + invokeArgs[0] = new ChainedHookedMethod(hooked, args); + + for(int i = 1; i < invokeArgs.length; i++) { + + if(annotations[1] == null) { + invokeArgs[i] = args[i - 1]; + }else { + final Annotation annotation = annotations[i]; + if(annotation instanceof Target) + invokeArgs[i] = target; + else{ + final int pos = hooked.getPosition((Param) annotation); + + if (pos == -1) { + throw new IllegalStateException("can't find " + annotation + " on " + hooked); + } + + invokeArgs[i] = args[pos]; + } + } + } + + return invoke(invokeArgs); + } + + class ChainedHookedMethod extends HookedMethodDelegate { + + private final Object[] args; + + public ChainedHookedMethod(HookedMethod original, Object[] args) { + super(original); + this.args = args; + } + + @Override + public Object proceed() throws Throwable { + return proceed(args()); + } + + @Override + public Object proceed(Object... newArgs) throws Throwable { + + if(newArgs != null) { + System.arraycopy(newArgs, 0, args, 0, Math.min(newArgs.length, args.length)); + } + + final HookEntry n = (HookEntry) next; + if (n != null) { + return n.proceed(delegate(), args); + } + + return super.proceed(args); + } + + @Override + public Object[] args() { + return args; + } + } + } + + class BeforeEntry extends Entry { + + + protected BeforeEntry(Object target, Method method, int priority) { + super(target, method, priority); + + if(method.getReturnType() != void.class) + throw new IllegalArgumentException(method+" must return void"); + } + + @Override + protected boolean isSupported(Annotation annotation, int position) { + if(position > 0) { + final Annotation previous = annotations[position - 1]; + if (annotation == null && previous != null || annotation != null && previous == null) + throw new IllegalArgumentException(method + + ": missing annotation on argument " + position + + " (either none or all arguments must be annotated)"); + } + + if(annotation instanceof Result) + throw new IllegalArgumentException(Result.class+" annotation can only be used" + +" on methods annotated with @" + After.class + " or @" + Returning.class); + + return annotation instanceof Param || annotation instanceof Target; + } + + void invoke(HookedMethod hooked, Object[] args) throws Throwable { + + if(annotations.length == 0) { + // no arguments? + invoke(null); + }else if(annotations[0] == null) { + // no @Params annotation? assume same signature + invoke(args); + }else { + final Object[] invokeArgs = new Object[annotations.length]; + + for (int i = 0; i < invokeArgs.length; i++) { + final Annotation annotation = annotations[i]; + + if(annotation instanceof Target) + invokeArgs[i] = target; + else{ + final int pos = hooked.getPosition((Param) annotation); + + if (pos == -1) { + throw new IllegalStateException("can't find " + annotation + " on " + hooked); + } + + invokeArgs[i] = args[pos]; + } + } + + invoke(invokeArgs); + } + } + } + + class AfterEntry extends Entry { + + protected AfterEntry(Object target, Method method, int priority) { + super(target, method, priority); + + if(method.getReturnType() != void.class) + throw new IllegalArgumentException(method+" must return void"); + } + + @Override + protected boolean isSupported(Annotation annotation, int position) { + if(position > 0) { + final Annotation previous = annotations[position - 1]; + if (annotation == null && previous != null || annotation != null && previous == null) + throw new IllegalArgumentException(method + + ": missing annotation on argument " + position + + " (either none or all arguments must be annotated)"); + } + return annotation instanceof Param || annotation instanceof Target || annotation instanceof Result; + } + + void invoke(HookedMethod hooked, Object[] args, Object result) throws InvocationTargetException, IllegalAccessException { + if(annotations.length == 0) { + // no arguments? + invoke(null); + }else if(annotations[0] == null) { + // no annotations? assume same signature + invoke(args); + }else { + final Object[] invokeArgs = new Object[annotations.length]; + + for (int i = 0; i < invokeArgs.length; i++) { + final Annotation annotation = annotations[i]; + + if(annotation instanceof Target) + invokeArgs[i] = target; + else if(annotation instanceof Result) + invokeArgs[i] = result; + else{ + final int pos = hooked.getPosition((Param) annotation); + + if (pos == -1) { + throw new IllegalStateException("can't find " + annotation + " on " + hooked); + } + + invokeArgs[i] = args[pos]; + } + } + + invoke(invokeArgs); + } + } + } + } +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/After.java b/runtime/src/main/java/com/mypopsy/hook/annotations/After.java new file mode 100644 index 0000000..d0cf3cc --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/After.java @@ -0,0 +1,13 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface After { + String value(); + int priority() default(0); +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Before.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Before.java new file mode 100644 index 0000000..df6c2d6 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Before.java @@ -0,0 +1,13 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Before { + String value(); + int priority() default(0); +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Call.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Call.java new file mode 100644 index 0000000..e6d8c25 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Call.java @@ -0,0 +1,13 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Call { + String value(); + int priority() default(0); +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Hook.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Hook.java new file mode 100644 index 0000000..28b2db2 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Hook.java @@ -0,0 +1,13 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Hook { + String value(); + int priority() default(0); +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Hooked.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Hooked.java new file mode 100644 index 0000000..425a7d8 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Hooked.java @@ -0,0 +1,12 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Hooked { + String value(); +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Param.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Param.java new file mode 100644 index 0000000..9357688 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Param.java @@ -0,0 +1,12 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface Param { + String value(); +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Register.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Register.java new file mode 100644 index 0000000..2278b72 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Register.java @@ -0,0 +1,11 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Register { +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Result.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Result.java new file mode 100644 index 0000000..2f07712 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Result.java @@ -0,0 +1,11 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface Result { +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Returning.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Returning.java new file mode 100644 index 0000000..699b33d --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Returning.java @@ -0,0 +1,13 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Returning { + String value(); + int priority() default(0); +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Target.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Target.java new file mode 100644 index 0000000..dcf7620 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Target.java @@ -0,0 +1,10 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +@java.lang.annotation.Target(ElementType.PARAMETER) +public @interface Target { +} diff --git a/runtime/src/main/java/com/mypopsy/hook/annotations/Unregister.java b/runtime/src/main/java/com/mypopsy/hook/annotations/Unregister.java new file mode 100644 index 0000000..49bbff7 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/annotations/Unregister.java @@ -0,0 +1,11 @@ +package com.mypopsy.hook.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Unregister { +} diff --git a/runtime/src/main/java/com/mypopsy/hook/internal/OrderedLinkedList.java b/runtime/src/main/java/com/mypopsy/hook/internal/OrderedLinkedList.java new file mode 100644 index 0000000..64160a4 --- /dev/null +++ b/runtime/src/main/java/com/mypopsy/hook/internal/OrderedLinkedList.java @@ -0,0 +1,90 @@ +package com.mypopsy.hook.internal; + +import java.util.Iterator; + +public class OrderedLinkedList implements Iterable { + + private T first; + + @SuppressWarnings("unchecked") + public T insert(T newEntry) { + + if (first == null) { + return first = newEntry; + } + + T current = first; + + // Nodes are stored in ascending priority order. + while (newEntry.compareTo(current) < 0) { + // end reached? + if (current.next == null) { + current.next = newEntry; + newEntry.previous = current; + return newEntry; + } + current = (T) current.next; + } + + newEntry.previous = current.previous; + newEntry.next = current; + current.previous = newEntry; + + if (newEntry.previous != null) + newEntry.previous.next = newEntry; + else + first = newEntry; + + return newEntry; + } + + public T first() { + return first; + } + + @Override + public Iterator iterator() { + return new LinkedIterator(first); + } + + public abstract class Node implements Comparable { + + public T previous, next; + + public void remove() { + if (previous != null) + previous.next = next; + else + first = next; + + if (next != null) + next.previous = previous; + } + } + + @SuppressWarnings("unchecked") + private class LinkedIterator implements Iterator { + private T current; + + public LinkedIterator(T item) { + this.current = item; + } + + @Override + public boolean hasNext() { + return current != null; + } + + @Override + public T next() { + T next = current; + current = (T) current.next; + return next; + } + + @Override + public void remove() { + current.remove(); + } + } +} \ No newline at end of file diff --git a/runtime/src/test/java/com/mypopsy/hook/TestHook.java b/runtime/src/test/java/com/mypopsy/hook/TestHook.java new file mode 100644 index 0000000..8aaf77d --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/TestHook.java @@ -0,0 +1,64 @@ +package com.mypopsy.hook; + +import com.mypopsy.hook.scenario.AfterScenario; +import com.mypopsy.hook.scenario.BaseScenario; +import com.mypopsy.hook.scenario.BeforeAfterScenario; +import com.mypopsy.hook.scenario.BeforeScenario; +import com.mypopsy.hook.scenario.CallScenario; +import com.mypopsy.hook.scenario.DoNotProceedScenario; +import com.mypopsy.hook.scenario.ModifyArgsScenario; +import com.mypopsy.hook.scenario.OrderingScenario; +import com.mypopsy.hook.scenario.ProceedScenario; +import com.mypopsy.hook.scenario.ProceedWithArgsScenario; +import com.mypopsy.hook.scenario.ReturningScenario; +import com.mypopsy.hook.scenario.SimpleParamScenario; +import com.mypopsy.hook.scenario.SimpleScenario; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +@RunWith(Parameterized.class) +public class TestHook { + + private final BaseScenario data; + + @Parameterized.Parameters(name = "{0}") + public static Collection configs() { + return Arrays.asList(new Object[][] { + {new SimpleScenario()}, + {new ProceedScenario()}, + {new ProceedWithArgsScenario()}, + {new DoNotProceedScenario()}, + {new OrderingScenario()}, + {new ModifyArgsScenario()}, + {new SimpleParamScenario()}, + {new BeforeScenario()}, + {new CallScenario()}, + {new AfterScenario()}, + {new ReturningScenario()}, + {new BeforeAfterScenario()}, + }); + } + + public TestHook(BaseScenario data) { + this.data = data; + } + + @Test + public void test() { + try { + data.register(); + assertThat(data.result(), is(data.expected())); + }finally { + data.unregister(); + } + } +} + diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/AfterScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/AfterScenario.java new file mode 100644 index 0000000..e441730 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/AfterScenario.java @@ -0,0 +1,67 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.After; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.annotations.Param; +import com.mypopsy.hook.annotations.Result; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class AfterScenario extends BaseScenario { + + private int token; + + @After(value = "test", priority = 0) + void after0() { + assertThat(token, is(9)); + token+=8; + } + + @After(value = "test", priority = 1) + void after1(@Param("int") int i) { + assertThat(i, is(666)); + assertThat(token, is(4)); + token+=5; + } + + @After(value = "test", priority = 2) + void after2(@Param("txt") String text, @Result Integer result) { + assertThat(text, is("foo")); + assertThat(token, is(1)); + assertThat(result, is(17)); + token+=3; + } + + @After(value = "test", priority = 3) + void after3(String a, int b) { + assertThat(a, is("foo")); + assertThat(b, is(666)); + assertThat(token, is(0)); + token+=1; + } + + @Hook("test") + Integer hook(HookedMethod method) throws Throwable { + assertThat(token, is(0)); + return method.proceed("foo", 666); + } + + @Override + public Integer result() { + return call("abc", 42); + } + + @Hooked("test") + private Integer call(@Param("txt") String text, @Param("int") int foo) { + assertThat(token, is(0)); + return 17; + } + + @Override + public Integer expected() { + return token; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/BaseScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/BaseScenario.java new file mode 100644 index 0000000..6894a73 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/BaseScenario.java @@ -0,0 +1,25 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.annotations.Register; +import com.mypopsy.hook.annotations.Unregister; + +public abstract class BaseScenario { + + @Register + public void register() { + System.out.println("register("+getClass()+")"); + } + + @Unregister + public void unregister() { + System.out.println("unregister("+getClass()+")"); + } + + public abstract T result(); + public abstract T expected(); + + @Override + public String toString() { + return getClass().getSimpleName(); + } +} \ No newline at end of file diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/BeforeAfterScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/BeforeAfterScenario.java new file mode 100644 index 0000000..e886688 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/BeforeAfterScenario.java @@ -0,0 +1,53 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.After; +import com.mypopsy.hook.annotations.Before; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.annotations.Param; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class BeforeAfterScenario extends BaseScenario { + + private int token; + + @After("test") + void after(String text, int i) { + assertThat(text, is("foo")); + assertThat(i, is(666)); + assertThat(token, is(5)); + token+=3; + } + + @Before("test") + void before(@Param("int") int i) { + assertThat(i, is(666)); + assertThat(token, is(0)); + token = 5; + } + + @Hook("test") + Integer hook(HookedMethod method) throws Throwable { + assertThat(token, is(0)); + return method.proceed("foo", 666); + } + + @Override + public Integer result() { + return call("abc", 42); + } + + @Hooked("test") + private Integer call(@Param("txt") String text, @Param("int") int foo) { + assertThat(token, is(5)); + return 8; + } + + @Override + public Integer expected() { + return token; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/BeforeScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/BeforeScenario.java new file mode 100644 index 0000000..6222ea9 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/BeforeScenario.java @@ -0,0 +1,64 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Before; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.annotations.Param; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class BeforeScenario extends BaseScenario { + + private int token; + + @Before(value = "test", priority = 0) + void before0() { + assertThat(token, is(9)); + token+=8; + } + + @Before(value = "test", priority = 1) + void before1(@Param("int") int i) { + assertThat(i, is(666)); + assertThat(token, is(4)); + token+=5; + } + + @Before(value = "test", priority = 2) + void before2(@Param("txt") String text) { + assertThat(text, is("foo")); + assertThat(token, is(1)); + token+=3; + } + + @Before(value = "test", priority = 3) + void before3(String a, int b) { + assertThat(a, is("foo")); + assertThat(b, is(666)); + assertThat(token, is(0)); + token = 1; + } + + @Hook("test") + Integer hook(HookedMethod method) throws Throwable { + assertThat(token, is(0)); + return method.proceed("foo", 666); + } + + @Override + public Integer result() { + return call("abc", 42); + } + + @Hooked("test") + private Integer call(@Param("txt") String text, @Param("int") int foo) { + return token; + } + + @Override + public Integer expected() { + return 17; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/CallScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/CallScenario.java new file mode 100644 index 0000000..9c945e2 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/CallScenario.java @@ -0,0 +1,64 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Call; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.annotations.Param; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class CallScenario extends BaseScenario { + + private int token; + + @Call(value = "test", priority = 0) + void call0() { + assertThat(token, is(9)); + token+=8; + } + + @Call(value = "test", priority = 1) + void call1(@Param("int") int i) { + assertThat(i, is(42)); + assertThat(token, is(4)); + token+=5; + } + + @Call(value = "test", priority = 2) + void call2(@Param("txt") String text) { + assertThat(text, is("abc")); + assertThat(token, is(1)); + token+=3; + } + + @Call(value = "test", priority = 3) + void call3(String a, int b) { + assertThat(a, is("abc")); + assertThat(b, is(42)); + assertThat(token, is(0)); + token = 1; + } + + @Hook("test") + Integer hook(HookedMethod method) throws Throwable { + assertThat(token, is(17)); + return method.proceed("foo", 666); + } + + @Override + public Integer result() { + return call("abc", 42); + } + + @Hooked("test") + private Integer call(@Param("txt") String text, @Param("int") int foo) { + return token; + } + + @Override + public Integer expected() { + return 17; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/DoNotProceedScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/DoNotProceedScenario.java new file mode 100644 index 0000000..c231442 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/DoNotProceedScenario.java @@ -0,0 +1,42 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Hooked; + +import static junit.framework.TestCase.assertTrue; + +public class DoNotProceedScenario extends BaseScenario { + + @Hooked("test") + int add(int a, int b) { + return a + b; + } + + @Hook("test") + int hook(HookedMethod method) throws Throwable { + assertTrue("we should not be there!", false); + return 43; + } + + @Hook(value = "test", priority = 1) + int hook3(HookedMethod method) throws Throwable { + assertTrue("we should not be there!", false); + return 44; + } + + @Hook(value = "test", priority = 3) + int hook1(HookedMethod method) throws Throwable { + return 42; + } + + @Override + public Integer result() { + return add(1, 8); + } + + @Override + public Integer expected() { + return 42; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/ModifyArgsScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/ModifyArgsScenario.java new file mode 100644 index 0000000..fb6a4e0 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/ModifyArgsScenario.java @@ -0,0 +1,39 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.HookedMethod; + +public class ModifyArgsScenario extends BaseScenario { + + + @Hook(value = "test", priority = 3) + String hook3(HookedMethod method) throws Throwable { + return method.proceed("foo"); + } + + @Hook(value = "test", priority = 2) + String hook2(HookedMethod method, String string) throws Throwable { + return method.proceed(string.replace("f", "z")); + } + + @Hook(value = "test", priority = 1) + String hook1(HookedMethod method, String string) throws Throwable { + return method.proceed(string.replace("oo", "orro")); + } + + @Override + public String result() { + return call("abc"); + } + + @Hooked("test") + private String call(String text) { + return text.toUpperCase(); + } + + @Override + public String expected() { + return "ZORRO"; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/OrderingScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/OrderingScenario.java new file mode 100644 index 0000000..728b731 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/OrderingScenario.java @@ -0,0 +1,34 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.HookedMethod; + +public class OrderingScenario extends BaseScenario { + + @Hook(value = "test", priority = 3) + String hook3(HookedMethod method) throws Throwable { + return method.proceed()+"f"; + } + + @Hook(value = "test", priority = 2) + String hook2(HookedMethod method) throws Throwable { + return method.proceed()+"e"; + } + + @Hook(value = "test", priority = 1) + String hook1(HookedMethod method) throws Throwable { + return method.proceed()+"d"; + } + + @Override + @Hooked("test") + public String result() { + return "abc"; + } + + @Override + public String expected() { + return "abcdef"; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/ProceedScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/ProceedScenario.java new file mode 100644 index 0000000..fc2c202 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/ProceedScenario.java @@ -0,0 +1,33 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; + +public class ProceedScenario extends BaseScenario { + + @Hooked("add") + int add(int a, int b) { + return a + b; + } + + @Hook("add") + int hook1(HookedMethod method) throws Throwable { + return method.proceed() + 1; + } + + @Hook("add") + int hook2(HookedMethod method) throws Throwable { + return method.proceed() + 1; + } + + @Override + public Integer result() { + return add(1, 8); + } + + @Override + public Integer expected() { + return 11; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/ProceedWithArgsScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/ProceedWithArgsScenario.java new file mode 100644 index 0000000..9805d30 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/ProceedWithArgsScenario.java @@ -0,0 +1,28 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; + +public class ProceedWithArgsScenario extends BaseScenario { + + @Hooked("test") + int add(int a, int b) { + return a + b; + } + + @Hook("test") + int hook(HookedMethod method) throws Throwable { + return method.proceed(1, 1); + } + + @Override + public Integer result() { + return add(1, 8); + } + + @Override + public Integer expected() { + return 2; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/ReturningScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/ReturningScenario.java new file mode 100644 index 0000000..95e48eb --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/ReturningScenario.java @@ -0,0 +1,69 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.annotations.Param; +import com.mypopsy.hook.annotations.Result; +import com.mypopsy.hook.annotations.Returning; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class ReturningScenario extends BaseScenario { + + private int token; + + @Returning(value = "test", priority = 0) + void after0() { + assertThat(token, is(9)); + token+=8; + } + + @Returning(value = "test", priority = 1) + void after1(@Param("int") int i) { + assertThat(i, is(17)); + assertThat(token, is(4)); + token+=5; + } + + @Returning(value = "test", priority = 2) + void after2(@Param("txt") String text, @Result Integer result) { + assertThat(text, is("foo")); + assertThat(token, is(1)); + assertThat(result, is(17)); + token+=3; + } + + @Returning(value = "test", priority = 3) + void after3(String a, int b) { + assertThat(a, is("foo")); + assertThat(b, is(17)); + assertThat(token, is(0)); + token+=1; + } + + @Hook("test") + Integer hook(HookedMethod method) throws Throwable { + assertThat(token, is(0)); + return method.proceed("foo", 17); + } + + @Override + public Integer result() { + return call("abc", 42); + } + + @Hooked("test") + private Integer call(@Param("txt") String text, @Param("int") int i) { + assertThat(text, is("foo")); + assertThat(i, is(17)); + assertThat(token, is(0)); + return i; + } + + @Override + public Integer expected() { + return token; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/SimpleParamScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/SimpleParamScenario.java new file mode 100644 index 0000000..0efe72e --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/SimpleParamScenario.java @@ -0,0 +1,70 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Param; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class SimpleParamScenario extends BaseScenario { + + + + @Override + public Integer result() { + return add(0, 1, 2); + } + + @Hooked("test") + private Integer add(@Param("a") int a, @Param("b") int b, @Param("c") int c) { + return a+b+c; + } + + @Hook("test") + Integer hook0(HookedMethod method, int a, int b, int c) throws Throwable { + assertThat(a, is(15)); + assertThat(b, is(16)); + assertThat(c, is(17)); + return method.proceed(); + } + + @Hook(value = "test", priority = 1) + Integer hook1(HookedMethod method, @Param("a") int a) throws Throwable { + assertThat(a, is(12)); + return method.proceed(15,16,17); + } + + @Hook(value = "test", priority = 2) + Integer hook2(HookedMethod method, @Param("b") int b) throws Throwable { + assertThat(b, is(10)); + return method.proceed(12,13,14); + } + + @Hook(value = "test", priority = 3) + Integer hook3(HookedMethod method, @Param("c") int c) throws Throwable { + assertThat(c, is(8)); + return method.proceed(9,10,11); + } + + @Hook(value = "test", priority = 4) + Integer hook4(HookedMethod method, @Param("b") int b, @Param("a") int a) throws Throwable { + assertThat(a, is(3)); + assertThat(b, is(4)); + return method.proceed(6,7,8); + } + + @Hook(value = "test", priority = 5) + Integer hook5(HookedMethod method, @Param("b") int b, @Param("a") int a, @Param("c") int c) throws Throwable { + assertThat(a, is(0)); + assertThat(b, is(1)); + assertThat(c, is(2)); + return method.proceed(3,4,5); + } + + @Override + public Integer expected() { + return 15+16+17; + } +} diff --git a/runtime/src/test/java/com/mypopsy/hook/scenario/SimpleScenario.java b/runtime/src/test/java/com/mypopsy/hook/scenario/SimpleScenario.java new file mode 100644 index 0000000..6da8aa9 --- /dev/null +++ b/runtime/src/test/java/com/mypopsy/hook/scenario/SimpleScenario.java @@ -0,0 +1,40 @@ +package com.mypopsy.hook.scenario; + +import com.mypopsy.hook.HookedMethod; +import com.mypopsy.hook.annotations.Hook; +import com.mypopsy.hook.annotations.Hooked; +import com.mypopsy.hook.annotations.Target; + +import org.hamcrest.core.Is; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class SimpleScenario extends BaseScenario { + + @Hooked("test") + int add(int a, int b) { + return a + b; + } + + + @Hook("test") + int hook(HookedMethod method, @Target Object target) throws Throwable { + assertThat(method.args().length, is(2)); + assertThat(method.target(), Is.is(this)); + assertThat((Integer)method.args()[0], is(1)); + assertThat((Integer)method.args()[1], is(8)); + assertThat(target, is(method.target())); + return method.proceed() + 1; + } + + @Override + public Integer result() { + return add(1, 8); + } + + @Override + public Integer expected() { + return 9+1; + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..bfae743 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +include ':plugin', ':runtime'