Java Code Examples for net.bytebuddy.matcher.ElementMatchers

The following examples show how to use net.bytebuddy.matcher.ElementMatchers. 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: alibaba-rsocket-broker   Author: alibaba   File: GrpcServiceRSocketImplBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public T build() throws Exception {
    Class<T> dynamicType = (Class<T>) new ByteBuddy()
            .subclass(serviceStub)
            .name(serviceStub.getSimpleName() + "RSocketImpl")
            .annotateType(AnnotationDescription.Builder.ofType(GRpcService.class).build())
            .method(ElementMatchers.returns(target -> target.isAssignableFrom(Mono.class) || target.isAssignableFrom(Flux.class)))
            .intercept(MethodDelegation.to(interceptor))
            .make()
            .load(getClass().getClassLoader())
            .getLoaded();
    T instance = dynamicType.newInstance();
    if (this.interceptor.getService() == null) {
        this.interceptor.setService(instance.bindService().getServiceDescriptor().getName());
    }
    return instance;
}
 
Example #2
Source Project: sofa-rpc   Author: sofastack   File: BytebuddyProxy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T getProxy(Class<T> interfaceClass, Invoker proxyInvoker) {

    Class<? extends T> cls = PROXY_CLASS_MAP.get(interfaceClass);
    if (cls == null) {
        cls = new ByteBuddy()
            .subclass(interfaceClass)
            .method(
                ElementMatchers.isDeclaredBy(interfaceClass).or(ElementMatchers.isEquals())
                    .or(ElementMatchers.isToString().or(ElementMatchers.isHashCode())))
            .intercept(MethodDelegation.to(new BytebuddyInvocationHandler(proxyInvoker), "handler"))
            .make()
            .load(interfaceClass.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
            .getLoaded();

        PROXY_CLASS_MAP.put(interfaceClass, cls);
    }
    try {
        return cls.newInstance();
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_CONSTRUCT, "bytebuddy"), t);
    }

}
 
Example #3
Source Project: byte-buddy   Author: raphw   File: MethodGraphCompilerDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericVisibilityBridge() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(GenericVisibilityBridgeTarget.class);
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 1));
    MethodDescription methodDescription = typeDescription.getSuperClass()
            .getDeclaredMethods().filter(isMethod().and(ElementMatchers.not(isBridge()))).getOnly();
    MethodDescription.SignatureToken bridgeToken = typeDescription.getSuperClass().getSuperClass()
            .getDeclaredMethods().filter(isMethod()).getOnly().asSignatureToken();
    MethodGraph.Node node = methodGraph.locate(methodDescription.asSignatureToken());
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.VISIBLE));
    assertThat(node, is(methodGraph.locate(bridgeToken)));
    assertThat(node.getMethodTypes().size(), is(2));
    assertThat(node.getMethodTypes().contains(methodDescription.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(methodDescription.asDefined().asTypeToken()), is(true));
    assertThat(node.getRepresentative(), is(methodDescription));
    assertThat(node.getVisibility(), is(methodDescription.getVisibility()));
}
 
Example #4
private ClassFileTransformer installInstrumentation() {
    return new AgentBuilder.Default()
            .disableClassFormatChanges()
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .with(AgentBuilder.RedefinitionStrategy.DiscoveryStrategy.Reiterating.INSTANCE)
            .ignore(none())
            .type(named(Foo.class.getName()), ElementMatchers.is(classLoader))
            .transform(new AgentBuilder.Transformer.ForAdvice()
                    .with(AgentBuilder.LocationStrategy.ForClassLoader.STRONG)
                    .include(FooAdvice.class.getClassLoader())
                    .with(Assigner.DEFAULT)
                    .withExceptionHandler(new Advice.ExceptionHandler.Simple(Removal.SINGLE))
                    .advice(named("createBar"), FooAdvice.class.getName()))
            .type(ElementMatchers.named(Bar.class.getName()), ElementMatchers.is(classLoader))
            .transform(new AgentBuilder.Transformer.ForAdvice()
                    .with(AgentBuilder.LocationStrategy.ForClassLoader.STRONG)
                    .include(BarAdvice.class.getClassLoader())
                    .with(Assigner.DEFAULT)
                    .withExceptionHandler(new Advice.ExceptionHandler.Simple(Removal.SINGLE))
                    .advice(named("toString"), BarAdvice.class.getName()))
            .installOnByteBuddyAgent();
}
 
Example #5
Source Project: byte-buddy   Author: raphw   File: MethodGraphCompilerDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericWithReturnTypeInterfaceMultipleEvolution() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(GenericWithReturnTypeInterfaceBase.Intermediate.Inner.class);
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(1));
    MethodDescription.SignatureToken token = typeDescription.getDeclaredMethods().filter(ElementMatchers.not(isBridge())).getOnly().asSignatureToken();
    MethodGraph.Node node = methodGraph.locate(token);
    MethodDescription.SignatureToken firstBridgeToken = typeDescription.getInterfaces().getOnly()
            .getDeclaredMethods().filter(ElementMatchers.not(isBridge())).getOnly().asDefined().asSignatureToken();
    MethodDescription.SignatureToken secondBridgeToken = typeDescription.getInterfaces().getOnly().getInterfaces().getOnly()
            .getDeclaredMethods().getOnly().asDefined().asSignatureToken();
    assertThat(node, is(methodGraph.locate(firstBridgeToken)));
    assertThat(node, is(methodGraph.locate(secondBridgeToken)));
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
    assertThat(node.getMethodTypes().size(), is(3));
    assertThat(node.getMethodTypes().contains(token.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(firstBridgeToken.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(secondBridgeToken.asTypeToken()), is(true));
    assertThat(node.getVisibility(), is(Visibility.PUBLIC));
}
 
Example #6
Source Project: xmlunit   Author: xmlunit   File: AssertFactoryProvider.java    License: Apache License 2.0 6 votes vote down vote up
private AssertFactory<Node, SingleNodeAssert> createProxyInstance(JAXPXPathEngine engine) {

        try {
            synchronized (AssertFactoryProvider.class) {
                if (assertFactoryClass == null) {
                    assertFactoryClass = new ByteBuddy()
                            .subclass(AssertFactory.class)
                            .name(NodeAssertFactoryDelegate.class.getPackage().getName() + ".XmlUnit$AssertFactory$" + RandomString.make())
                            .method(ElementMatchers.named("createAssert"))
                            .intercept(MethodDelegation.to(new NodeAssertFactoryDelegate(createDefaultInstance(engine))))
                            .make()
                            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                            .getLoaded();
                }
            }

            @SuppressWarnings("unchecked")
            AssertFactory<Node, SingleNodeAssert> instance = (AssertFactory<Node, SingleNodeAssert>) assertFactoryClass.newInstance();
            return instance;

        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }

        return createDefaultInstance(engine);
    }
 
Example #7
Source Project: skywalking   Author: apache   File: SolrClientInstrumentation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {

            @Override
            public String getConstructorInterceptor() {
                return "org.apache.skywalking.apm.plugin.solrj.SolrClientInterceptor";
            }

            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return ElementMatchers.any();
            }
        }
    };
}
 
Example #8
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuperConstructorInvocationWithoutArguments() throws Exception {
    DynamicType.Loaded<Object> loaded = new ByteBuddy()
            .subclass(Object.class)
            .constructor(ElementMatchers.any())
            .intercept(MethodCall.invoke(Object.class.getDeclaredConstructor()).onSuper())
            .make()
            .load(Object.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(0));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    Object instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(Object.class)));
    assertThat(instance, instanceOf(Object.class));
}
 
Example #9
Source Project: skywalking   Author: apache   File: GenericRequestorInstrumentation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return ElementMatchers.any();
            }

            @Override
            public String getConstructorInterceptor() {
                return INTERCEPTOR_CLASS;
            }
        }
    };
}
 
Example #10
Source Project: skywalking   Author: apache   File: GenericRequestorInstrumentation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return ElementMatchers.named("request");
            }

            @Override
            public String getMethodsInterceptor() {
                return INTERCEPTOR_CLASS;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #11
Source Project: skywalking   Author: apache   File: ResponderInstrumentation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return ElementMatchers.any();
            }

            @Override
            public String getConstructorInterceptor() {
                return INTERCEPTOR_CLASS;
            }
        }
    };
}
 
Example #12
Source Project: morphia   Author: MorphiaOrg   File: ReferenceCodec.java    License: Apache License 2.0 6 votes vote down vote up
private <T> T createProxy(final MorphiaReference reference) {
    ReferenceProxy referenceProxy = new ReferenceProxy(reference);
    try {
        Class<?> type = getField().getType();
        String name = (type.getPackageName().startsWith("java") ? type.getSimpleName() : type.getName()) + "$$Proxy";
        return ((Loaded<T>) new ByteBuddy()
                                .subclass(type)
                                .implement(MorphiaProxy.class)
                                .name(name)

                                .invokable(ElementMatchers.isDeclaredBy(type))
                                .intercept(InvocationHandlerAdapter.of(referenceProxy))

                                .method(ElementMatchers.isDeclaredBy(MorphiaProxy.class))
                                .intercept(InvocationHandlerAdapter.of(referenceProxy))

                                .make()
                                .load(Thread.currentThread().getContextClassLoader(), Default.WRAPPER))
                   .getLoaded()
                   .getDeclaredConstructor()
                   .newInstance();
    } catch (ReflectiveOperationException | IllegalArgumentException e) {
        throw new MappingException(e.getMessage(), e);
    }
}
 
Example #13
Source Project: skywalking   Author: apache   File: SpecificRequestorInstrumentation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return ElementMatchers.named("invoke");
            }

            @Override
            public String getMethodsInterceptor() {
                return INTERCEPTOR_CLASS;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #14
Source Project: skywalking   Author: apache   File: MongoDBOperationExecutorInstrumentation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
    return new InstanceMethodsInterceptPoint[] {
        new InstanceMethodsInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getMethodsMatcher() {
                return ElementMatchers
                    // 3.6.x
                    .named(METHOD_NAME);
            }

            @Override
            public String getMethodsInterceptor() {
                return INTERCEPTOR_CLASS;
            }

            @Override
            public boolean isOverrideArgs() {
                return false;
            }
        }
    };
}
 
Example #15
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 #16
Source Project: skywalking   Author: apache   File: InfluxDBInstrumentation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
    return new ConstructorInterceptPoint[] {
        new ConstructorInterceptPoint() {
            @Override
            public ElementMatcher<MethodDescription> getConstructorMatcher() {
                return ElementMatchers.takesArgument(0, String.class);
            }

            @Override
            public String getConstructorInterceptor() {
                return INTERCEPTOR_CLASS;
            }
        }
    };
}
 
Example #17
Source Project: agrona   Author: real-logic   File: BufferAlignmentAgent.java    License: Apache License 2.0 6 votes vote down vote up
private static synchronized void agent(final boolean shouldRedefine, final Instrumentation instrumentation)
{
    BufferAlignmentAgent.instrumentation = instrumentation;
    // all Int methods, and all String method other than
    // XXXStringWithoutLengthXXX or getStringXXX(int, int)
    final Junction<MethodDescription> intVerifierMatcher = nameContains("Int")
        .or(nameMatches(".*String[^W].*").and(not(ElementMatchers.takesArguments(int.class, int.class))));

    alignmentTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED))
        .with(new AgentBuilderListener())
        .disableClassFormatChanges()
        .with(shouldRedefine ?
            AgentBuilder.RedefinitionStrategy.RETRANSFORMATION : AgentBuilder.RedefinitionStrategy.DISABLED)
        .type(isSubTypeOf(DirectBuffer.class).and(not(isInterface())))
        .transform((builder, typeDescription, classLoader, module) -> builder
            .visit(to(LongVerifier.class).on(nameContains("Long")))
            .visit(to(DoubleVerifier.class).on(nameContains("Double")))
            .visit(to(IntVerifier.class).on(intVerifierMatcher))
            .visit(to(FloatVerifier.class).on(nameContains("Float")))
            .visit(to(ShortVerifier.class).on(nameContains("Short")))
            .visit(to(CharVerifier.class).on(nameContains("Char"))))
        .installOn(instrumentation);
}
 
Example #18
Source Project: byte-buddy   Author: raphw   File: MethodGraphCompilerDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericClassMultipleEvolution() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(GenericClassBase.Intermediate.Inner.class);
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 1));
    MethodDescription.SignatureToken token = typeDescription.getDeclaredMethods().filter(isMethod().and(ElementMatchers.not(isBridge()))).getOnly().asSignatureToken();
    MethodGraph.Node node = methodGraph.locate(token);
    MethodDescription.SignatureToken firstBridgeToken = typeDescription.getSuperClass().getDeclaredMethods()
            .filter(isMethod().and(ElementMatchers.not(isBridge()))).getOnly().asDefined().asSignatureToken();
    MethodDescription.SignatureToken secondBridgeToken = typeDescription.getSuperClass().getSuperClass().getDeclaredMethods()
            .filter(isMethod()).getOnly().asDefined().asSignatureToken();
    assertThat(node, is(methodGraph.locate(firstBridgeToken)));
    assertThat(node, is(methodGraph.locate(secondBridgeToken)));
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
    assertThat(node.getMethodTypes().size(), is(3));
    assertThat(node.getMethodTypes().contains(token.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(firstBridgeToken.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(secondBridgeToken.asTypeToken()), is(true));
    assertThat(node.getVisibility(), is(Visibility.PUBLIC));
}
 
Example #19
Source Project: JGiven   Author: TNG   File: ByteBuddyStageClassCreator.java    License: Apache License 2.0 6 votes vote down vote up
public <T> Class<? extends T> createStageClass( Class<T> stageClass ) {
    return new ByteBuddy()
        .subclass( stageClass, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING )
        .implement( StageInterceptorInternal.class )
        .defineField( INTERCEPTOR_FIELD_NAME, StepInterceptor.class )
        .method( named(SETTER_NAME) )
            .intercept(
                MethodDelegation.withDefaultConfiguration()
                    .withBinders( FieldProxy.Binder.install(
                            StepInterceptorGetterSetter.class ))
            .to(new StepInterceptorSetter() ))
        .method( not( named( SETTER_NAME )
                .or(ElementMatchers.isDeclaredBy(Object.class))))
        .intercept(
                MethodDelegation.withDefaultConfiguration()
                .withBinders(FieldProxy.Binder.install(
                        StepInterceptorGetterSetter.class ))
            .to( new ByteBuddyMethodInterceptor() ))
        .make()
        .load( getClassLoader(stageClass),
            getClassLoadingStrategy( stageClass ) )
        .getLoaded();
}
 
Example #20
Source Project: byte-buddy   Author: raphw   File: ToStringPlugin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassFileLocator classFileLocator) {
    Enhance enhance = typeDescription.getDeclaredAnnotations().ofType(Enhance.class).load();
    if (typeDescription.getDeclaredMethods().filter(isToString()).isEmpty()) {
        builder = builder.method(isToString()).intercept(ToStringMethod.prefixedBy(enhance.prefix().getPrefixResolver())
                .withIgnoredFields(enhance.includeSyntheticFields()
                        ? ElementMatchers.<FieldDescription>none()
                        : ElementMatchers.<FieldDescription>isSynthetic())
                .withIgnoredFields(isAnnotatedWith(Exclude.class)));
    }
    return builder;
}
 
Example #21
@Test
@SuppressWarnings("unchecked")
public void testRange() throws Exception {
    Iterator<? extends List<Class<?>>> batches = new AgentBuilder.RedefinitionStrategy.BatchAllocator.ForMatchedGrouping(ElementMatchers.is(Object.class)
            .or(ElementMatchers.is(Void.class))).withinRange(1, 1).batch(Arrays.<Class<?>>asList(Object.class, Void.class, String.class)).iterator();
    assertThat(batches.hasNext(), is(true));
    assertThat(batches.next(), is(Collections.<Class<?>>singletonList(Object.class)));
    assertThat(batches.hasNext(), is(true));
    assertThat(batches.next(), is(Collections.<Class<?>>singletonList(Void.class)));
    assertThat(batches.hasNext(), is(true));
    assertThat(batches.next(), is(Collections.<Class<?>>singletonList(String.class)));
    assertThat(batches.hasNext(), is(false));
}
 
Example #22
@Test
public void testAttachment() throws Exception {
    TypeDescription.Generic original = TypeDefinition.Sort.describe(Foo.Inner.class.getDeclaredField(FOO).getGenericType());
    TypeDescription.Generic detached = original.accept(new TypeDescription.Generic.Visitor.Substitutor.ForDetachment(ElementMatchers.is(Foo.Inner.class)));
    TypeDescription target = TypeDescription.ForLoadedType.of(Bar.class);
    TypeDescription.Generic attached = detached.accept(new TypeDescription.Generic.Visitor.Substitutor.ForAttachment(target.asGenericType(), target));
    assertThat(attached.getSort(), is(TypeDefinition.Sort.PARAMETERIZED));
    assertThat(attached.asErasure(), is(target));
    assertThat(attached.getTypeArguments().size(), is(4));
    assertThat(attached.getTypeArguments().get(0).getSort(), is(TypeDefinition.Sort.VARIABLE));
    assertThat(attached.getTypeArguments().get(0).getSymbol(), is("T"));
    assertThat(attached.getTypeArguments().get(0), is(target.getTypeVariables().filter(named("T")).getOnly()));
    assertThat(attached.getTypeArguments().get(1).getSort(), is(TypeDefinition.Sort.NON_GENERIC));
    assertThat(attached.getTypeArguments().get(1).asErasure().represents(String.class), is(true));
    assertThat(attached.getTypeArguments().get(2).getSort(), is(TypeDefinition.Sort.VARIABLE));
    assertThat(attached.getTypeArguments().get(2).getSymbol(), is("U"));
    assertThat(attached.getTypeArguments().get(2), is(target.getTypeVariables().filter(named("U")).getOnly()));
    assertThat(attached.getTypeArguments().get(3).getSort(), is(TypeDefinition.Sort.PARAMETERIZED));
    assertThat(attached.getTypeArguments().get(3).asErasure().represents(List.class), is(true));
    assertThat(attached.getTypeArguments().get(3).getTypeArguments().size(), is(1));
    assertThat(attached.getTypeArguments().get(3).getTypeArguments().getOnly(), is(target.getTypeVariables().filter(named("S")).getOnly()));
    assertThat(attached.getOwnerType(), notNullValue(TypeDescription.Generic.class));
    assertThat(attached.getOwnerType().getSort(), is(TypeDefinition.Sort.PARAMETERIZED));
    assertThat(attached.getOwnerType().getTypeArguments().size(), is(1));
    assertThat(attached.getOwnerType().getTypeArguments().getOnly().getSort(), is(TypeDefinition.Sort.VARIABLE));
    assertThat(attached.getOwnerType().getTypeArguments().getOnly().getSymbol(), is("T"));
    assertThat(attached.getOwnerType().getTypeArguments().getOnly(), is(target.getTypeVariables().filter(named("T")).getOnly()));
}
 
Example #23
Source Project: byte-buddy   Author: raphw   File: RebaseDynamicTypeBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRebaseOfRenamedType() throws Exception {
    Class<?> rebased = new ByteBuddy()
            .rebase(Sample.class)
            .name(Sample.class.getName() + FOO)
            .constructor(ElementMatchers.any())
            .intercept(SuperMethodCall.INSTANCE)
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(rebased.getName(), is(Sample.class.getName() + FOO));
    assertThat(rebased.getDeclaredConstructors().length, is(2));
}
 
Example #24
@Test(expected = UnsupportedOperationException.class)
@SuppressWarnings("unchecked")
public void testMinimumCannotRemove() throws Exception {
    new AgentBuilder.RedefinitionStrategy.BatchAllocator.ForMatchedGrouping(ElementMatchers.is(Object.class))
            .withMinimum(2)
            .batch(Collections.<Class<?>>singletonList(Object.class))
            .iterator()
            .remove();
}
 
Example #25
Source Project: byte-buddy   Author: raphw   File: MethodGraphCompilerDefaultTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReturnTypeClassSingleEvolution() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(ReturnTypeClassBase.Inner.class);
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(TypeDescription.OBJECT.getDeclaredMethods().filter(isVirtual()).size() + 1));
    MethodDescription.SignatureToken token = typeDescription.getDeclaredMethods().filter(isMethod().and(ElementMatchers.not(isBridge()))).getOnly().asSignatureToken();
    MethodGraph.Node node = methodGraph.locate(token);
    MethodDescription.SignatureToken bridgeToken = typeDescription.getSuperClass().getDeclaredMethods().filter(isMethod()).getOnly().asSignatureToken();
    assertThat(node, is(methodGraph.locate(bridgeToken)));
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
    assertThat(node.getMethodTypes().size(), is(2));
    assertThat(node.getMethodTypes().contains(token.asTypeToken()), is(true));
    assertThat(node.getMethodTypes().contains(bridgeToken.asTypeToken()), is(true));
    assertThat(node.getVisibility(), is(Visibility.PUBLIC));
}
 
Example #26
Source Project: apm-agent-java   Author: elastic   File: JaxRsTransactionNameInstrumentation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ElementMatcher<? super MethodDescription> getMethodMatcher() {
    // quote from JAX-RS 2.0 spec (section 3.6 Annotation Inheritance)
    // "JAX-RS annotations may be used on the methods and method parameters of a super-class or an implemented interface."
    return overridesOrImplementsMethodThat(
        isAnnotatedWith(
            named("javax.ws.rs.GET")
                .or(named("javax.ws.rs.POST"))
                .or(named("javax.ws.rs.PUT"))
                .or(named("javax.ws.rs.DELETE"))
                .or(named("javax.ws.rs.HEAD"))
                .or(named("javax.ws.rs.OPTIONS"))))
        .onSuperClassesThat(isInAnyPackage(applicationPackages, ElementMatchers.<NamedElement>any()));
}
 
Example #27
Source Project: apm-agent-java   Author: elastic   File: JaxWsTransactionNameInstrumentation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ElementMatcher<? super MethodDescription> getMethodMatcher() {
    return overridesOrImplementsMethodThat(
        isAnnotatedWith(
            named("javax.jws.WebMethod")))
        .onSuperClassesThat(isInAnyPackage(applicationPackages, ElementMatchers.<NamedElement>any()));
}
 
Example #28
Source Project: apm-agent-java   Author: elastic   File: JobTransactionNameInstrumentation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ElementMatcher<? super TypeDescription> getTypeMatcher() {
    return isInAnyPackage(applicationPackages, ElementMatchers.<NamedElement>none())
        .or(nameStartsWith("org.quartz.job"))
        .and(hasSuperType(named("org.quartz.Job")))
        .and(declaresMethod(getMethodMatcher()));
}
 
Example #29
Source Project: byte-buddy   Author: raphw   File: MethodGraphCompilerDefaultTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInterfaceDuplicateInHierarchyImplementation() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(InterfaceBase.InterfaceDuplicate.class);
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(1));
    MethodDescription method = typeDescription.getInterfaces().filter(ElementMatchers.is(InterfaceBase.class)).getOnly().getDeclaredMethods().getOnly();
    MethodGraph.Node node = methodGraph.locate(method.asSignatureToken());
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
    assertThat(node.getMethodTypes().size(), is(1));
    assertThat(node.getMethodTypes().contains(method.asTypeToken()), is(true));
    assertThat(node.getRepresentative(), is(method));
    assertThat(node.getVisibility(), is(method.getVisibility()));
    assertThat(methodGraph.listNodes().contains(node), is(true));
}
 
Example #30
Source Project: byte-buddy   Author: raphw   File: MethodCallTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldSettingLastChained() throws Exception {
    DynamicType.Loaded<FieldSetting> loaded = new ByteBuddy()
            .subclass(FieldSetting.class)
            .method(named(QUX))
            .intercept(MethodCall.invoke(FieldSetting.class.getMethod(BAR))
                    .setsField(ElementMatchers.is(FieldSetting.class.getField(FOO)))
                    .andThen(StubMethod.INSTANCE))
            .make()
            .load(FieldSetting.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    FieldSetting instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.qux(), nullValue(Object.class));
    assertThat(instance.foo, is((Object) instance.bar()));
}