Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Proxy
A small yet powerful interception library that lets you manipulate existing objects and classes behavior runtime,
It's achieving this by using [javassist](http://jboss-javassist.github.io/javassist/) to do bytecode manipulation,
It's achieving this by using [javassist](http://jboss-javassist.github.io/javassist/) or [Byte Buddy](https://bytebuddy.net/)
to do bytecode manipulation (see [Bytecode engines](#bytecode-engines)),
Proxy has a [fluent](http://en.wikipedia.org/wiki/Fluent_interface) interception API:

```java
Expand Down Expand Up @@ -106,6 +107,44 @@ Proxy is a great building block for creating other innovative solutions.
* It does bytecode manipulation with cglib similarly to how Proxy does the same with Javassist
* It is missing features like: __recursive interception__ and __delegation__ and **object interception**

## Bytecode engines

Proxy ships with two interchangeable bytecode manipulation engines. They implement the same behavior, so the engine is
purely an implementation detail: no code that uses `Proxy` has to change when you switch.

| Engine | Name | Notes |
|---|---|---|
| [Javassist](http://jboss-javassist.github.io/javassist/) | `javassist` | The default, used by Proxy since its first release |
| [Byte Buddy](https://bytebuddy.net/) | `bytebuddy` | Alternative engine, useful if your application already depends on Byte Buddy or you hit a Javassist limitation |

Select the engine for the whole JVM with a system property:

```bash
java -Dproxy.engine=bytebuddy your.Application
```

Or at runtime, which affects every proxy created afterwards:

```java
import com.ericsson.commonlibrary.proxy.ProxyConfiguration;
import com.ericsson.commonlibrary.proxy.ProxyConfiguration.Engine;

ProxyConfiguration.setEngine(Engine.BYTEBUDDY);
ProxyConfiguration.reset(); // back to -Dproxy.engine, or javassist when that is unset
```

Or for a single call only, without affecting other threads:

```java
SomeImpl obj = ProxyConfiguration.callWithEngine(Engine.BYTEBUDDY,
() -> Proxy.with(SomeImpl.class).interceptAll(i -> i.invoke()).get());
```

Proxies from both engines can be mixed freely in the same JVM, and a proxy created by one engine can be proxied again by
the other. Already created proxies keep the engine they were created with.

The whole test suite is executed twice by the build, once per engine, so both engines are verified to behave the same.

## User Guide
**Under Construction**: https://ericsson.github.io/proxy

Expand Down
46 changes: 42 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ericsson.commonlibrary</groupId>
<artifactId>proxy</artifactId>
<version>1.2.29-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Proxy</name>
<description>A small yet powerful interception library that lets you manipulate existing objects and classes behavior runtime, It's achieving this by using javassist to do bytecode manipulation</description>
<description>A small yet powerful interception library that lets you manipulate existing objects and classes behavior runtime, It's achieving this by using javassist or Byte Buddy to do bytecode manipulation</description>
<url>${scm.repo.url.web}</url>
<organization>
<name>Ericsson</name>
Expand All @@ -51,13 +52,16 @@ SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<log4j2.version>2.25.3</log4j2.version>
<objenesis.version>3.4</objenesis.version>
<javassist.version>3.30.2-GA</javassist.version>
<bytebuddy.version>1.18.12</bytebuddy.version>

<!-- Plugin versions -->
<maven.deploy.plugin.version>3.1.4</maven.deploy.plugin.version>
<maven.source.plugin.version>3.3.1</maven.source.plugin.version>
<maven.jar.plugin.version>3.5.0</maven.jar.plugin.version>
<maven.release.plugin.version>3.2.0</maven.release.plugin.version>
<maven.surefire.plugin.version>3.5.4</maven.surefire.plugin.version>
<!-- Set to true to skip the second test run that executes the whole suite on the byte-buddy engine -->
<skip.bytebuddy.tests>false</skip.bytebuddy.tests>
<maven.compiler.plugin.version>3.14.1</maven.compiler.plugin.version>
<maven.enforcer.plugin.version>3.6.2</maven.enforcer.plugin.version>
<maven.enforcer.plugin.disabled>false</maven.enforcer.plugin.disabled>
Expand Down Expand Up @@ -88,6 +92,11 @@ SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${bytebuddy.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
Expand Down Expand Up @@ -175,6 +184,35 @@ SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</excludes>
<skip>false</skip>
</configuration>
<executions>
<execution>
<!-- The whole suite on the default (javassist) proxy engine -->
<id>default-test</id>
<goals>
<goal>test</goal>
</goals>
<configuration>
<systemPropertyVariables>
<proxy.engine>javassist</proxy.engine>
</systemPropertyVariables>
</configuration>
</execution>
<execution>
<!-- The exact same suite on the byte-buddy proxy engine -->
<id>bytebuddy-test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<skip>${skip.bytebuddy.tests}</skip>
<systemPropertyVariables>
<proxy.engine>bytebuddy</proxy.engine>
</systemPropertyVariables>
<reportsDirectory>${project.build.directory}/surefire-reports-bytebuddy</reportsDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand All @@ -186,8 +224,8 @@ SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<requireReleaseVersion />
<dependencyConvergence />
<requireMavenVersion>
<version>[3.8.1,4.0.0)</version>
</requireMavenVersion>
<version>[3.8.1,4.0.0)</version>
</requireMavenVersion>
</rules>
<fail>true</fail>
<skip>${maven.enforcer.plugin.disabled}</skip>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
Copyright (c) 2018 Ericsson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.ericsson.commonlibrary.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayDeque;

/**
* Holds the interceptor stack of one byte-buddy generated proxy instance. This is the byte-buddy counterpart of
* javassist's {@code MethodHandler}.
*/
final class ByteBuddyInterceptorDispatcher {

private final ArrayDeque<Interceptor> interceptorStack = new ArrayDeque<>();

/**
* @param dispatcher
* the dispatcher field value of the proxy, {@code null} while a super constructor is still running
* @param self
* the proxy instance
* @param method
* the method that was called
* @param superMethod
* accessor for the real implementation, {@code null} when there is none
* @param arguments
* the arguments of the call
*
* @return whatever the interceptor chain or the real implementation returns
*
* @throws Throwable
* anything the interceptor chain or the real implementation throws
*/
static Object dispatch(Object dispatcher, Object self, Method method, Method superMethod, Object[] arguments)
throws Throwable {
Method accessibleSuperMethod = makeAccessible(superMethod);
if (dispatcher == null) {
// A super constructor is calling an overridable method before the proxy is fully wired up. Javassist
// behaves the same way and simply runs the real implementation.
return invokeSuper(self, accessibleSuperMethod, method, arguments);
}
return ((ByteBuddyInterceptorDispatcher) dispatcher).dispatch(self, method, accessibleSuperMethod, arguments);
}

private Object dispatch(Object self, Method method, Method superMethod, Object[] arguments) throws Throwable {
Object handled = InterceptableProxyInvoker.handleInterceptableProxyMethod(interceptorStack, method, arguments);
if (handled != InterceptableProxyInvoker.NOT_HANDLED) {
return handled;
}
return new Invocation(self, method, superMethod, arguments, interceptorStack.clone()).invoke();
}

private static Object invokeSuper(Object self, Method superMethod, Method method, Object[] arguments)
throws Throwable {
if (superMethod == null) {
throw new UnsupportedOperationException(
"There exist's no implementation of method: " + method.getName() + "(...) to delegate to.");
}
try {
return superMethod.invoke(self, arguments);
} catch (InvocationTargetException e) {
Util.filterExceptionAndRethrowCorrect(e);
throw ProxyException.returnThisShouldNeverHappen("Failed to re-throw real exception: ", e);
}
}

@SuppressWarnings({ "deprecation", "squid:S3011" })
private static Method makeAccessible(Method superMethod) {
if (superMethod != null && !superMethod.isAccessible()) {
superMethod.setAccessible(true);
}
return superMethod;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
Copyright (c) 2018 Ericsson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.ericsson.commonlibrary.proxy;

import java.lang.reflect.Method;

import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.FieldValue;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperMethod;
import net.bytebuddy.implementation.bind.annotation.This;

/**
* Every method of a byte-buddy generated proxy is compiled into a call to {@link #dispatch}. The class therefore has to
* be public, because a generated proxy class is placed in the package of the type it proxies, which is normally not the
* package of this library.
* <p>
* <b>This class is an implementation detail and is not part of the supported API. Never call it directly.</b>
*/
public final class ByteBuddyProxyDispatcher {

/**
* Name of the synthetic field that holds the interceptor state of a single proxy instance.
*/
public static final String DISPATCHER_FIELD = "proxy$interceptorDispatcher";

private ByteBuddyProxyDispatcher() {
// hidden
}

/**
* Called by every method of a byte-buddy generated proxy.
*
* @param self
* the proxy instance
* @param dispatcher
* value of the {@value #DISPATCHER_FIELD} field, {@code null} while a super constructor is still running
* @param method
* the method that was called
* @param superMethod
* an accessor for the real implementation, {@code null} when there is none
* @param arguments
* the arguments of the call
*
* @return whatever the interceptor chain or the real implementation returns
*
* @throws Throwable
* anything the interceptor chain or the real implementation throws
*/
@RuntimeType
public static Object dispatch(@This Object self, @FieldValue(DISPATCHER_FIELD) Object dispatcher,
@Origin Method method, @SuperMethod(nullIfImpossible = true) Method superMethod,
@AllArguments Object[] arguments) throws Throwable {
return ByteBuddyInterceptorDispatcher.dispatch(dispatcher, self, method, superMethod, arguments);
}
}
Loading
Loading