Java Code Examples for net.bytebuddy.dynamic.ClassFileLocator

The following examples show how to use net.bytebuddy.dynamic.ClassFileLocator. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: byte-buddy   Author: raphw   File: ClassInjectorUsingReflectionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@ClassReflectionInjectionAvailableRule.Enforce
@JavaVersionRule.Enforce(atMost = 10)
public void testUnsafeInjection() throws Exception {
    ClassInjector.UsingReflection.Dispatcher dispatcher = ClassInjector.UsingReflection.Dispatcher.UsingUnsafeInjection.make().initialize();
    assertThat(dispatcher.getPackage(classLoader, Foo.class.getPackage().getName()), nullValue(Package.class));
    assertThat(dispatcher.definePackage(classLoader,
            Foo.class.getPackage().getName(),
            null,
            null,
            null,
            null,
            null,
            null,
            null), notNullValue(Package.class));
    assertThat(dispatcher.findClass(classLoader, Foo.class.getName()), nullValue(Class.class));
    assertThat(dispatcher.defineClass(classLoader, Foo.class.getName(), ClassFileLocator.ForClassLoader.read(Foo.class), null), notNullValue(Class.class));
    assertThat(classLoader.loadClass(Foo.class.getName()).getClassLoader(), is(classLoader));
}
 
Example #2
Source Project: lams   Author: lamsfoundation   File: EnhancerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs the enhancement.
 *
 * @param className The name of the class whose bytecode is being enhanced.
 * @param originalBytes The class's original (pre-enhancement) byte code
 *
 * @return The enhanced bytecode. Could be the same as the original bytecode if the original was
 * already enhanced or we could not enhance it for some reason.
 *
 * @throws EnhancementException Indicates a problem performing the enhancement
 */
@Override
public synchronized byte[] enhance(String className, byte[] originalBytes) throws EnhancementException {
	//Classpool#describe does not accept '/' in the description name as it expects a class name. See HHH-12545
	final String safeClassName = className.replace( '/', '.' );
	try {
		final TypeDescription typeDescription = typePool.describe( safeClassName ).resolve();

		return byteBuddyState.rewrite( typePool, safeClassName, originalBytes, byteBuddy -> doEnhance(
				byteBuddy.ignore( isDefaultFinalizer() ).redefine( typeDescription, ClassFileLocator.Simple.of( safeClassName, originalBytes ) ),
				typeDescription
		) );
	}
	catch (RuntimeException e) {
		throw new EnhancementException( "Failed to enhance class " + className, e );
	}
}
 
Example #3
Source Project: byte-buddy   Author: raphw   File: ClassInjectorUsingReflectionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@ClassReflectionInjectionAvailableRule.Enforce
public void testUnsafeOverride() throws Exception {
    ClassInjector.UsingReflection.Dispatcher dispatcher = ClassInjector.UsingReflection.Dispatcher.UsingUnsafeOverride.make().initialize();
    assertThat(dispatcher.getPackage(classLoader, Foo.class.getPackage().getName()), nullValue(Package.class));
    assertThat(dispatcher.definePackage(classLoader,
            Foo.class.getPackage().getName(),
            null,
            null,
            null,
            null,
            null,
            null,
            null), notNullValue(Package.class));
    assertThat(dispatcher.findClass(classLoader, Foo.class.getName()), nullValue(Class.class));
    assertThat(dispatcher.defineClass(classLoader, Foo.class.getName(), ClassFileLocator.ForClassLoader.read(Foo.class), null), notNullValue(Class.class));
    assertThat(classLoader.loadClass(Foo.class.getName()).getClassLoader(), is(classLoader));
}
 
Example #4
Source Project: skywalking   Author: apache   File: BootstrapInstrumentBoost.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate the delegator class based on given template class. This is preparation stage level code generation.
 * <p>
 * One key step to avoid class confliction between AppClassLoader and BootstrapClassLoader
 *
 * @param classesTypeMap    hosts injected binary of generated class
 * @param typePool          to generate new class
 * @param templateClassName represents the class as template in this generation process. The templates are
 *                          pre-defined in SkyWalking agent core.
 */
private static void generateDelegator(Map<String, byte[]> classesTypeMap, TypePool typePool,
    String templateClassName, String methodsInterceptor) {
    String internalInterceptorName = internalDelegate(methodsInterceptor);
    try {
        TypeDescription templateTypeDescription = typePool.describe(templateClassName).resolve();

        DynamicType.Unloaded interceptorType = new ByteBuddy().redefine(templateTypeDescription, ClassFileLocator.ForClassLoader
            .of(BootstrapInstrumentBoost.class.getClassLoader()))
                                                              .name(internalInterceptorName)
                                                              .field(named("TARGET_INTERCEPTOR"))
                                                              .value(methodsInterceptor)
                                                              .make();

        classesTypeMap.put(internalInterceptorName, interceptorType.getBytes());

        InstrumentDebuggingClass.INSTANCE.log(interceptorType);
    } catch (Exception e) {
        throw new PluginException("Generate Dynamic plugin failure", e);
    }
}
 
Example #5
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderForInliningTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEnabledAnnotationRetention() throws Exception {
    Class<?> type = create(Annotated.class)
            .field(ElementMatchers.any()).annotateField(new Annotation[0])
            .method(ElementMatchers.any()).intercept(StubMethod.INSTANCE)
            .make()
            .load(new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
                    ClassFileLocator.ForClassLoader.readToNames(SampleAnnotation.class)), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    @SuppressWarnings("unchecked")
    Class<? extends Annotation> sampleAnnotation = (Class<? extends Annotation>) type.getClassLoader().loadClass(SampleAnnotation.class.getName());
    assertThat(type.isAnnotationPresent(sampleAnnotation), is(true));
    assertThat(type.getDeclaredField(FOO).isAnnotationPresent(sampleAnnotation), is(true));
    assertThat(type.getDeclaredMethod(FOO, Void.class).isAnnotationPresent(sampleAnnotation), is(true));
    assertThat(type.getDeclaredMethod(FOO, Void.class).getParameterAnnotations()[0].length, is(1));
    assertThat(type.getDeclaredMethod(FOO, Void.class).getParameterAnnotations()[0][0].annotationType(), is((Object) sampleAnnotation));
}
 
Example #6
Source Project: byte-buddy   Author: raphw   File: PluginEngineDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleTransformationIgnoredByMatcher() throws Exception {
    Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class);
    Plugin plugin = eager
            ? new SimplePlugin()
            : new PreprocessingPlugin(new SimplePlugin());
    Plugin.Engine.Source source = Plugin.Engine.Source.InMemory.ofTypes(Sample.class);
    Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory();
    Plugin.Engine.Summary summary = new Plugin.Engine.Default()
            .with(listener)
            .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader()))
            .with(dispatcherFactory)
            .ignore(ElementMatchers.is(Sample.class))
            .apply(source, target, new Plugin.Factory.Simple(plugin));
    ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, target.toTypeMap());
    Class<?> type = classLoader.loadClass(Sample.class.getName());
    assertThat(type.getDeclaredFields().length, is(0));
    assertThat(summary.getTransformed().size(), is(0));
    assertThat(summary.getFailed().size(), is(0));
    assertThat(summary.getUnresolved().size(), is(0));
    verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST);
    verify(listener).onDiscovery(Sample.class.getName());
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(Sample.class), Collections.singletonList(plugin));
    verify(listener).onComplete(TypeDescription.ForLoadedType.of(Sample.class));
    verifyNoMoreInteractions(listener);
}
 
Example #7
Source Project: byte-buddy   Author: raphw   File: PluginEngineDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleTransformationIgnoredByPlugin() throws Exception {
    Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class);
    Plugin plugin = eager
            ? new IgnoringPlugin()
            : new PreprocessingPlugin(new IgnoringPlugin());
    Plugin.Engine.Source source = Plugin.Engine.Source.InMemory.ofTypes(Sample.class);
    Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory();
    Plugin.Engine.Summary summary = new Plugin.Engine.Default()
            .with(listener)
            .with(ClassFileLocator.ForClassLoader.of(IgnoringPlugin.class.getClassLoader()))
            .with(dispatcherFactory)
            .apply(source, target, new Plugin.Factory.Simple(plugin));
    ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, target.toTypeMap());
    Class<?> type = classLoader.loadClass(Sample.class.getName());
    assertThat(type.getDeclaredFields().length, is(0));
    assertThat(summary.getTransformed().size(), is(0));
    assertThat(summary.getFailed().size(), is(0));
    assertThat(summary.getUnresolved().size(), is(0));
    verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST);
    verify(listener).onDiscovery(Sample.class.getName());
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(Sample.class), plugin);
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(Sample.class), Collections.singletonList(plugin));
    verify(listener).onComplete(TypeDescription.ForLoadedType.of(Sample.class));
    verifyNoMoreInteractions(listener);
}
 
Example #8
Source Project: byte-buddy   Author: raphw   File: RebaseDynamicTypeBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPackageRebasement() throws Exception {
    Class<?> packageType = new ByteBuddy()
            .rebase(Sample.class.getPackage(), ClassFileLocator.ForClassLoader.of(getClass().getClassLoader()))
            .annotateType(AnnotationDescription.Builder.ofType(Baz.class).build())
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertThat(packageType.getSimpleName(), CoreMatchers.is(PackageDescription.PACKAGE_CLASS_NAME));
    assertThat(packageType.getName(), CoreMatchers.is(Sample.class.getPackage().getName() + "." + PackageDescription.PACKAGE_CLASS_NAME));
    assertThat(packageType.getModifiers(), CoreMatchers.is(PackageDescription.PACKAGE_MODIFIERS));
    assertThat(packageType.getDeclaredFields().length, CoreMatchers.is(0));
    assertThat(packageType.getDeclaredMethods().length, CoreMatchers.is(0));
    assertThat(packageType.getDeclaredAnnotations().length, CoreMatchers.is(2));
    assertThat(packageType.getAnnotation(PackageAnnotation.class), notNullValue(PackageAnnotation.class));
    assertThat(packageType.getAnnotation(Baz.class), notNullValue(Baz.class));
}
 
Example #9
Source Project: byte-buddy   Author: raphw   File: PluginEngineSourceInMemoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOfTypes() throws Exception {
    Plugin.Engine.Source.Origin origin = Plugin.Engine.Source.InMemory.ofTypes(Foo.class).read();
    try {
        assertThat(origin.getClassFileLocator().locate(Foo.class.getName()).isResolved(), is(true));
        assertThat(origin.getClassFileLocator().locate(Foo.class.getName()).resolve(), is(ClassFileLocator.ForClassLoader.read(Foo.class)));
        assertThat(origin.getClassFileLocator().locate("qux.Baz").isResolved(), is(false));
        assertThat(origin.getManifest(), nullValue(Manifest.class));
        Iterator<Plugin.Engine.Source.Element> iterator = origin.iterator();
        assertThat(iterator.hasNext(), is(true));
        Plugin.Engine.Source.Element element = iterator.next();
        assertThat(element.getName(), is(Foo.class.getName().replace('.', '/') + ".class"));
        assertThat(element.resolveAs(Object.class), nullValue(Object.class));
        assertThat(StreamDrainer.DEFAULT.drain(element.getInputStream()), is(ClassFileLocator.ForClassLoader.read(Foo.class)));
        assertThat(iterator.hasNext(), is(false));
    } finally {
        origin.close();
    }
}
 
Example #10
Source Project: byte-buddy   Author: raphw   File: Plugin.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new default plugin engine.
 *
 * @param byteBuddy          The Byte Buddy instance to use.
 * @param typeStrategy       The type strategy to use.
 * @param poolStrategy       The pool strategy to use.
 * @param classFileLocator   The class file locator to use.
 * @param listener           The listener to use.
 * @param errorHandler       The error handler to use.
 * @param dispatcherFactory  The dispatcher factory to use.
 * @param ignoredTypeMatcher A matcher for types to exclude from transformation.
 */
protected Default(ByteBuddy byteBuddy,
                  TypeStrategy typeStrategy,
                  PoolStrategy poolStrategy,
                  ClassFileLocator classFileLocator,
                  Listener listener,
                  ErrorHandler errorHandler,
                  Dispatcher.Factory dispatcherFactory,
                  ElementMatcher.Junction<? super TypeDescription> ignoredTypeMatcher) {
    this.byteBuddy = byteBuddy;
    this.typeStrategy = typeStrategy;
    this.poolStrategy = poolStrategy;
    this.classFileLocator = classFileLocator;
    this.listener = listener;
    this.errorHandler = errorHandler;
    this.dispatcherFactory = dispatcherFactory;
    this.ignoredTypeMatcher = ignoredTypeMatcher;
}
 
Example #11
Source Project: byte-buddy   Author: raphw   File: PluginEngineDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testResource() throws Exception {
    Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class);
    Plugin.Engine.Source source = new Plugin.Engine.Source.InMemory(Collections.singletonMap(FOO, new byte[]{1, 2, 3}));
    Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory();
    Plugin.Engine.Summary summary = new Plugin.Engine.Default()
            .with(listener)
            .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader()))
            .with(dispatcherFactory)
            .apply(source, target, new Plugin.Factory.Simple(eager
                    ? new SimplePlugin()
                    : new PreprocessingPlugin(new SimplePlugin())));
    assertThat(summary.getTransformed().size(), is(0));
    assertThat(summary.getFailed().size(), is(0));
    assertThat(summary.getUnresolved().size(), is(0));
    verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST);
    verify(listener).onResource(FOO);
    verifyNoMoreInteractions(listener);
}
 
Example #12
Source Project: byte-buddy   Author: raphw   File: PluginEngineDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleTransformation() throws Exception {
    Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class);
    Plugin plugin = eager
            ? new SimplePlugin()
            : new PreprocessingPlugin(new SimplePlugin());
    Plugin.Engine.Source source = Plugin.Engine.Source.InMemory.ofTypes(Sample.class);
    Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory();
    Plugin.Engine.Summary summary = new Plugin.Engine.Default()
            .with(listener)
            .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader()))
            .with(dispatcherFactory)
            .apply(source, target, new Plugin.Factory.Simple(plugin));
    ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, target.toTypeMap());
    Class<?> type = classLoader.loadClass(Sample.class.getName());
    assertThat(type.getDeclaredField(FOO).getType(), is((Object) Void.class));
    assertThat(summary.getTransformed(), hasItems(TypeDescription.ForLoadedType.of(Sample.class)));
    assertThat(summary.getFailed().size(), is(0));
    assertThat(summary.getUnresolved().size(), is(0));
    verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST);
    verify(listener).onDiscovery(Sample.class.getName());
    verify(listener).onTransformation(TypeDescription.ForLoadedType.of(Sample.class), plugin);
    verify(listener).onTransformation(TypeDescription.ForLoadedType.of(Sample.class), Collections.singletonList(plugin));
    verify(listener).onComplete(TypeDescription.ForLoadedType.of(Sample.class));
    verifyNoMoreInteractions(listener);
}
 
Example #13
Source Project: byte-buddy   Author: raphw   File: AgentBuilderDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(builder.make(TypeResolutionStrategy.Disabled.INSTANCE, typePool)).thenReturn((DynamicType.Unloaded) dynamicType);
    when(dynamicType.getTypeDescription()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED));
    when(typeStrategy.builder(any(TypeDescription.class),
            eq(byteBuddy),
            any(ClassFileLocator.class),
            any(MethodNameTransformer.class),
            Mockito.<ClassLoader>any(),
            Mockito.<JavaModule>any(),
            Mockito.<ProtectionDomain>any())).thenReturn((DynamicType.Builder) builder);
    Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>();
    loadedTypeInitializers.put(TypeDescription.ForLoadedType.of(REDEFINED), loadedTypeInitializer);
    when(dynamicType.getLoadedTypeInitializers()).thenReturn(loadedTypeInitializers);
    when(dynamicType.getBytes()).thenReturn(BAZ);
    when(transformer.transform(builder, TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED)))
            .thenReturn((DynamicType.Builder) builder);
    when(poolStrategy.typePool(any(ClassFileLocator.class), any(ClassLoader.class))).thenReturn(typePool);
    when(typePool.describe(REDEFINED.getName())).thenReturn(resolution);
    when(instrumentation.getAllLoadedClasses()).thenReturn(new Class<?>[]{REDEFINED});
    when(initializationStrategy.dispatcher()).thenReturn(dispatcher);
    when(dispatcher.apply(builder)).thenReturn((DynamicType.Builder) builder);
}
 
Example #14
Source Project: byte-buddy   Author: raphw   File: PluginEngineDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testManifest() throws Exception {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    manifest.write(outputStream);
    Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class);
    Plugin.Engine.Source source = new Plugin.Engine.Source.InMemory(Collections.singletonMap(JarFile.MANIFEST_NAME, outputStream.toByteArray()));
    Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory();
    Plugin.Engine.Summary summary = new Plugin.Engine.Default()
            .with(listener)
            .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader()))
            .with(dispatcherFactory)
            .apply(source, target, new Plugin.Factory.Simple(eager
                    ? new SimplePlugin()
                    : new PreprocessingPlugin(new SimplePlugin())));
    assertThat(summary.getTransformed().size(), is(0));
    assertThat(summary.getFailed().size(), is(0));
    assertThat(summary.getUnresolved().size(), is(0));
    verify(listener).onManifest(manifest);
    verifyNoMoreInteractions(listener);
}
 
Example #15
@Test
public void testNonGenericSuperClassNavigatedHierarchyResolutionIsLazy() throws Exception {
    ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader());
    assertThat(describe(NonGenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getSuperClass().getSuperClass().asErasure(),
            CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SuperClass.class)));
    verify(classFileLocator).locate(NonGenericType.class.getName());
    verify(classFileLocator).locate(SampleClass.class.getName());
    verifyNoMoreInteractions(classFileLocator);
}
 
Example #16
Source Project: byte-buddy   Author: raphw   File: ToStringPluginTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPluginEnhance() throws Exception {
    Class<?> type = new ToStringPlugin()
            .apply(new ByteBuddy().redefine(SimpleSample.class), TypeDescription.ForLoadedType.of(SimpleSample.class), ClassFileLocator.ForClassLoader.of(SimpleSample.class.getClassLoader()))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Object instance = type.getDeclaredConstructor().newInstance();
    type.getDeclaredField(FOO).set(instance, FOO);
    assertThat(instance.toString(), is("SimpleSample{foo=foo}"));
}
 
Example #17
Source Project: byte-buddy   Author: raphw   File: VirtualMachineAttachmentTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    agent = File.createTempFile("testagent", ".jar");
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue("Agent-Class", SampleAgent.class.getName());
    JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(agent), manifest);
    try {
        outputStream.putNextEntry(new JarEntry(SampleAgent.class.getName().replace('.', '/') + ".class"));
        outputStream.write(ClassFileLocator.ForClassLoader.read(SampleAgent.class));
        outputStream.closeEntry();
    } finally {
        outputStream.close();
    }
}
 
Example #18
Source Project: byte-buddy   Author: raphw   File: ClassLoadingStrategyDefaultTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    classLoader = new URLClassLoader(new URL[0], null);
    binaryRepresentations = new LinkedHashMap<TypeDescription, byte[]>();
    typeDescription = TypeDescription.ForLoadedType.of(Foo.class);
    binaryRepresentations.put(typeDescription, ClassFileLocator.ForClassLoader.read(Foo.class));
    protectionDomain = getClass().getProtectionDomain();
    when(packageDefinitionStrategy.define(any(ClassLoader.class), any(String.class), any(String.class)))
            .thenReturn(PackageDefinitionStrategy.Definition.Undefined.INSTANCE);
}
 
Example #19
@Test
public void testTypeIsCached() throws Exception {
    ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader());
    TypePool typePool = TypePool.Default.WithLazyResolution.of(classFileLocator);
    TypePool.Resolution resolution = typePool.describe(Object.class.getName());
    assertThat(resolution.resolve().getModifiers(), CoreMatchers.is(TypeDescription.OBJECT.getModifiers()));
    assertThat(resolution.resolve().getInterfaces(), CoreMatchers.is(TypeDescription.OBJECT.getInterfaces()));
    assertThat(typePool.describe(Object.class.getName()).resolve(), CoreMatchers.is(resolution.resolve()));
    verify(classFileLocator).locate(Object.class.getName());
    verifyNoMoreInteractions(classFileLocator);
}
 
Example #20
Source Project: byte-buddy   Author: raphw   File: AgentBuilderClassFileBufferStrategyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRetainingClassFileBufferStrategy() throws Exception {
    ClassFileLocator classFileLocator = AgentBuilder.ClassFileBufferStrategy.Default.RETAINING.resolve("foo",
            new byte[]{123},
            mock(ClassLoader.class),
            mock(JavaModule.class),
            mock(ProtectionDomain.class));

    assertThat(classFileLocator.locate("foo").isResolved(), is(true));
    assertThat(classFileLocator.locate("bar").isResolved(), is(false));
}
 
Example #21
Source Project: byte-buddy   Author: raphw   File: SubclassDynamicTypeBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDoesNotOverrideMethodWithPackagePrivateArgumentType() throws Exception {
    Class<?> type = new ByteBuddy()
            .subclass(PackagePrivateArgumentType.class)
            .name("net.bytebuddy.test.generated." + FOO)
            .method(isDeclaredBy(PackagePrivateArgumentType.class))
            .intercept(StubMethod.INSTANCE)
            .make()
            .load(new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileLocator.ForClassLoader.readToNames(PackagePrivateArgumentType.class,
                    PackagePrivateArgumentType.Argument.class)), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethods().length, is(0));
}
 
Example #22
Source Project: byte-buddy   Author: raphw   File: ClassReloadingStrategyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testResetEmptyNoEffect() throws Exception {
    Instrumentation instrumentation = mock(Instrumentation.class);
    ClassFileLocator classFileLocator = mock(ClassFileLocator.class);
    when(instrumentation.isRetransformClassesSupported()).thenReturn(true);
    ClassReloadingStrategy.of(instrumentation).reset(classFileLocator);
    verify(instrumentation, times(2)).isRetransformClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verifyZeroInteractions(classFileLocator);
}
 
Example #23
Source Project: byte-buddy   Author: raphw   File: SubclassDynamicTypeBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDoesNotOverrideMethodWithPackagePrivateReturnType() throws Exception {
    Class<?> type = new ByteBuddy()
            .subclass(PackagePrivateReturnType.class)
            .name("net.bytebuddy.test.generated." + FOO)
            .method(isDeclaredBy(PackagePrivateReturnType.class))
            .intercept(StubMethod.INSTANCE)
            .make()
            .load(new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileLocator.ForClassLoader.readToNames(PackagePrivateReturnType.class,
                    PackagePrivateReturnType.Argument.class)), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethods().length, is(0));
}
 
Example #24
@Test
public void testGenericSuperInterfaceNavigatedHierarchyResolutionIsLazy() throws Exception {
    ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader());
    assertThat(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getInterfaces().getOnly()
            .getInterfaces().getOnly().asErasure(), CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SuperInterface.class)));
    verify(classFileLocator).locate(GenericType.class.getName());
    verify(classFileLocator).locate(SampleGenericInterface.class.getName());
    verifyNoMoreInteractions(classFileLocator);
}
 
Example #25
Source Project: byte-buddy   Author: raphw   File: AgentBuilderDefaultApplicationRedefineTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    simpleTypeLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
            ClassFileLocator.ForClassLoader.readToNames(SimpleType.class),
            ByteArrayClassLoader.PersistenceHandler.MANIFEST);
    optionalTypeLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
            ClassFileLocator.ForClassLoader.readToNames(SimpleOptionalType.class),
            ByteArrayClassLoader.PersistenceHandler.MANIFEST);
}
 
Example #26
Source Project: byte-buddy   Author: raphw   File: PluginEngineDefaultTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUnresolved() throws Exception {
    Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class);
    Plugin plugin = eager
            ? new SimplePlugin()
            : new PreprocessingPlugin(new SimplePlugin());
    Plugin.Engine.Source source = new Plugin.Engine.Source.InMemory(Collections.singletonMap(
            Sample.class.getName().replace('.', '/') + ".class",
            ClassFileLocator.ForClassLoader.read(Sample.class))) {
        @Override
        public ClassFileLocator getClassFileLocator() {
            return ClassFileLocator.NoOp.INSTANCE;
        }
    };
    Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory();
    Plugin.Engine.Summary summary = new Plugin.Engine.Default()
            .with(listener)
            .withoutErrorHandlers()
            .with(dispatcherFactory)
            .apply(source, target, new Plugin.Factory.Simple(plugin));
    ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, target.toTypeMap());
    Class<?> type = classLoader.loadClass(Sample.class.getName());
    assertThat(type.getDeclaredFields().length, is(0));
    assertThat(summary.getTransformed().size(), is(0));
    assertThat(summary.getFailed().size(), is(0));
    assertThat(summary.getUnresolved().size(), is(1));
    assertThat(summary.getUnresolved().contains(Sample.class.getName()), is(true));
    verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST);
    verify(listener).onDiscovery(Sample.class.getName());
    verify(listener).onUnresolved(Sample.class.getName());
    verifyNoMoreInteractions(listener);
}
 
Example #27
Source Project: byte-buddy   Author: raphw   File: PluginEngineDefaultTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testSimpleTransformationError() throws Exception {
    Plugin.Engine.Source source = Plugin.Engine.Source.InMemory.ofTypes(Sample.class);
    Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory();
    new Plugin.Engine.Default()
            .with(ClassFileLocator.ForClassLoader.of(FailingPlugin.class.getClassLoader()))
            .with(dispatcherFactory)
            .apply(source, target, new Plugin.Factory.Simple(eager
                    ? new FailingPlugin(new RuntimeException())
                    : new PreprocessingPlugin(new FailingPlugin(new RuntimeException()))));
}
 
Example #28
@Test
public void testGenericSuperClassHierarchyResolutionIsLazy() throws Exception {
    ClassFileLocator classFileLocator = spy(ClassFileLocator.ForClassLoader.ofSystemLoader());
    assertThat(describe(GenericType.class, classFileLocator, new TypePool.CacheProvider.Simple()).getSuperClass().asErasure(),
            CoreMatchers.is((TypeDescription) TypeDescription.ForLoadedType.of(SampleGenericClass.class)));
    verify(classFileLocator).locate(GenericType.class.getName());
    verifyNoMoreInteractions(classFileLocator);
}
 
Example #29
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderForInliningTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoVisibilityBridgeForNonPublicType() throws Exception {
    InjectionClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
            false,
            ClassFileLocator.ForClassLoader.readToNames(PackagePrivateVisibilityBridgeExtension.class, VisibilityBridge.class, FooBar.class));
    Class<?> type = create(PackagePrivateVisibilityBridgeExtension.class)
            .modifiers(0)
            .make()
            .load(classLoader, InjectionClassLoader.Strategy.INSTANCE)
            .getLoaded();
    assertThat(type.getDeclaredConstructors().length, is(1));
    assertThat(type.getDeclaredMethods().length, is(0));
}
 
Example #30
Source Project: byte-buddy   Author: raphw   File: ClassInjectorUsingReflectionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@ClassReflectionInjectionAvailableRule.Enforce
public void testInjectionOrderNoPrematureAuxiliaryInjection() throws Exception {
    ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
            ClassFileLocator.ForClassLoader.readToNames(Bar.class, Interceptor.class));
    Class<?> type = new ByteBuddy()
            .rebase(Bar.class)
            .method(named(BAR))
            .intercept(MethodDelegation.to(Interceptor.class)).make()
            .load(classLoader, ClassLoadingStrategy.Default.INJECTION)
            .getLoaded();
    assertThat(type.getDeclaredMethod(BAR, String.class).invoke(type.getDeclaredConstructor().newInstance(), FOO), is((Object) BAR));
}