net.bytebuddy.matcher.ElementMatchers Java Examples

The following examples show how to use net.bytebuddy.matcher.ElementMatchers. 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 File: SpecificRequestorInstrumentation.java    From skywalking with 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 #2
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with 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 #3
Source File: MethodGraphCompilerDefaultTest.java    From byte-buddy with 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 #4
Source File: ByteBuddyStageClassCreator.java    From JGiven with 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 #5
Source File: BufferAlignmentAgent.java    From agrona with 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 #6
Source File: InfluxDBInstrumentation.java    From skywalking with 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 #7
Source File: GrpcServiceRSocketImplBuilder.java    From alibaba-rsocket-broker with 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 #8
Source File: MongoDBOperationExecutorInstrumentation.java    From skywalking with 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 #9
Source File: ReferenceCodec.java    From morphia with 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 #10
Source File: ResponderInstrumentation.java    From skywalking with 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 #11
Source File: GenericRequestorInstrumentation.java    From skywalking with 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 #12
Source File: GenericRequestorInstrumentation.java    From skywalking with 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 #13
Source File: MethodCallTest.java    From byte-buddy with 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 #14
Source File: SolrClientInstrumentation.java    From skywalking with 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 #15
Source File: BytebuddyProxy.java    From sofa-rpc with 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 #16
Source File: AssertFactoryProvider.java    From xmlunit with 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 #17
Source File: MethodGraphCompilerDefaultTest.java    From byte-buddy with 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 #18
Source File: AgentBuilderDefaultApplicationRedefinitionReiterationTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
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 #19
Source File: MethodGraphCompilerDefaultTest.java    From byte-buddy with 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 #20
Source File: MethodGraphCompilerDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericClassSingleEvolution() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(GenericClassBase.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().asDefined().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 #21
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testMatchedCallAmbiguous() throws Exception {
    new ByteBuddy()
            .subclass(InstanceMethod.class)
            .method(named(FOO))
            .intercept(MethodCall.invoke(ElementMatchers.any()))
            .make();
}
 
Example #22
Source File: RedissonLiveObjectService.java    From redisson with Apache License 2.0 5 votes vote down vote up
private <T> void validateClass(Class<T> entityClass) {
    if (entityClass.isAnonymousClass() || entityClass.isLocalClass()) {
        throw new IllegalArgumentException(entityClass.getName() + " is not publically accessable.");
    }
    if (!ClassUtils.isAnnotationPresent(entityClass, REntity.class)) {
        throw new IllegalArgumentException("REntity annotation is missing from class type declaration.");
    }

    FieldList<FieldDescription.InDefinedShape> fields = Introspectior.getFieldsWithAnnotation(entityClass, RIndex.class);
    fields = fields.filter(ElementMatchers.fieldType(ElementMatchers.hasSuperType(
                            ElementMatchers.anyOf(Map.class, Collection.class, RObject.class))));
    for (InDefinedShape field : fields) {
        throw new IllegalArgumentException("RIndex annotation couldn't be defined for field '" + field.getName() + "' with type '" + field.getType() + "'");
    }
    
    FieldList<FieldDescription.InDefinedShape> fieldsWithRIdAnnotation
            = Introspectior.getFieldsWithAnnotation(entityClass, RId.class);
    if (fieldsWithRIdAnnotation.size() == 0) {
        throw new IllegalArgumentException("RId annotation is missing from class field declaration.");
    }
    if (fieldsWithRIdAnnotation.size() > 1) {
        throw new IllegalArgumentException("Only one field with RId annotation is allowed in class field declaration.");
    }
    FieldDescription.InDefinedShape idFieldDescription = fieldsWithRIdAnnotation.getOnly();
    String idFieldName = idFieldDescription.getName();
    Field idField = null;
    try {
        idField = ClassUtils.getDeclaredField(entityClass, idFieldName);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    if (ClassUtils.isAnnotationPresent(idField.getType(), REntity.class)) {
        throw new IllegalArgumentException("Field with RId annotation cannot be a type of which class is annotated with REntity.");
    }
    if (idField.getType().isAssignableFrom(RObject.class)) {
        throw new IllegalArgumentException("Field with RId annotation cannot be a type of RObject");
    }
}
 
Example #23
Source File: ControllerInstrumentationTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetConstructorsInterceptPoints() throws Throwable {
    ConstructorInterceptPoint[] cips = controllerInstrumentation.getConstructorsInterceptPoints();
    Assert.assertEquals(cips.length, 1);
    ConstructorInterceptPoint cip = cips[0];
    Assert.assertNotNull(cip);

    Assert.assertEquals(cip.getConstructorInterceptor(), "org.apache.skywalking.apm.plugin.spring.mvc.v4.ControllerConstructorInterceptor");
    Assert.assertTrue(cip.getConstructorMatcher().equals(ElementMatchers.any()));
}
 
Example #24
Source File: Introspectior.java    From redisson with Apache License 2.0 5 votes vote down vote up
public static MethodDescription getMethodDescription(Class<?> c, String method) {
    if (method == null || method.isEmpty()) {
        return null;
    }
    return getTypeDescription(c)
            .getDeclaredMethods()
            .filter(ElementMatchers.hasMethodName(method))
            .getOnly();
}
 
Example #25
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulWithoutExistingClassConjunction() throws Exception {
    when(dynamicType.getBytes()).thenReturn(BAZ);
    when(resolution.resolve()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED));
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), null, REDEFINED.getProtectionDomain()))
            .thenReturn(true);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(ElementMatchers.any()).and(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    assertThat(transform(classFileTransformer, JavaModule.ofType(REDEFINED), REDEFINED.getClassLoader(), REDEFINED.getName(), null, REDEFINED.getProtectionDomain(), QUX), is(BAZ));
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), false);
    verify(listener).onTransformation(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), false, dynamicType);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), false);
    verifyNoMoreInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verifyNoMoreInteractions(instrumentation);
    verify(initializationStrategy).dispatcher();
    verifyNoMoreInteractions(initializationStrategy);
    verify(dispatcher).apply(builder);
    verify(dispatcher).register(eq(dynamicType),
            eq(REDEFINED.getClassLoader()),
            eq(REDEFINED.getProtectionDomain()),
            eq(AgentBuilder.InjectionStrategy.UsingReflection.INSTANCE));
    verifyNoMoreInteractions(dispatcher);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #26
Source File: InliningImplementationMatcher.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a matcher where only overridable or declared methods are matched unless those are ignored. Methods that
 * are declared by the target type are only matched if they are not ignored. Declared methods that are not found on the
 * target type are always matched.
 *
 * @param ignoredMethods A method matcher that matches any ignored method.
 * @param originalType   The original type of the instrumentation before adding any user methods.
 * @return A latent method matcher that identifies any method to instrument for a rebasement or redefinition.
 */
protected static LatentMatcher<MethodDescription> of(LatentMatcher<? super MethodDescription> ignoredMethods, TypeDescription originalType) {
    ElementMatcher.Junction<MethodDescription> predefinedMethodSignatures = none();
    for (MethodDescription methodDescription : originalType.getDeclaredMethods()) {
        ElementMatcher.Junction<MethodDescription> signature = methodDescription.isConstructor()
                ? isConstructor()
                : ElementMatchers.<MethodDescription>named(methodDescription.getName());
        signature = signature.and(returns(methodDescription.getReturnType().asErasure()));
        signature = signature.and(takesArguments(methodDescription.getParameters().asTypeList().asErasures()));
        predefinedMethodSignatures = predefinedMethodSignatures.or(signature);
    }
    return new InliningImplementationMatcher(ignoredMethods, predefinedMethodSignatures);
}
 
Example #27
Source File: ToStringPlugin.java    From byte-buddy with 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 #28
Source File: ImmutableProxy.java    From reflection-util with Apache License 2.0 5 votes vote down vote up
private static boolean hasMethodAnnotatedWith(SignatureToken methodSignature, TypeDefinition type, Class<? extends Annotation> annotation) {
	return !type.getDeclaredMethods()
		.filter(hasMethodName(methodSignature.getName())
			.and(takesArguments(methodSignature.getParameterTypes()))
			.and(ElementMatchers.isAnnotatedWith(annotation)))
		.isEmpty();
}
 
Example #29
Source File: ThrowableSanitiser.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Wrap a {@link Throwable} in a dynamic proxy that sanitizes its message to hide sensitive cookie
 * information. The supplied Throwable must be non-final, and must have a no-args constructor. If the proxy
 * cannot be created for any reason (including that it is proxying a final class, or one without a no-args constructor),
 * then a warning is logged and the unproxied Throwable is returned back to the caller.
 * @param original the Throwable to be proxied
 * @param formatter hides the sensitive cookies.
 * @return the proxied Throwable, or the original throwable if it cannot be proxied.
 */
public Throwable sanitise(Throwable original, SanitisedHttpHeaderFormatter formatter) {

    Class<?> clazz = original.getClass();
    try {
        Constructor<?> defaultConstructor = clazz.getConstructor();

        Class<?> proxyClass = typeCache.findOrInsert(getClass().getClassLoader(), clazz.getName(), () ->
                new ByteBuddy()
                        .subclass(clazz)
                        .defineField("methodInterceptor", Interceptor.class, Visibility.PRIVATE)
                        .defineConstructor(Visibility.PUBLIC)
                        .withParameters(Interceptor.class)
                        .intercept(FieldAccessor.ofField("methodInterceptor").setsArgumentAt(0)
                                .andThen(MethodCall.invoke(defaultConstructor)))
                        .method(ElementMatchers.any())
                        .intercept(MethodDelegation.toField("methodInterceptor"))
                        .make()
                        .load(getClass().getClassLoader())
                        .getLoaded());

        return (Throwable) proxyClass
                .getConstructor(Interceptor.class)
                .newInstance(new Interceptor(original, formatter));
    } catch (Exception e) {
        LOG.warn("Unable to proxy throwable class {} - {}", clazz, e.toString()); // No need to log stack trace here
    }
    return original;
}
 
Example #30
Source File: AgentBuilderRedefinitionStrategyBatchAllocatorTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMinimumChunked() throws Exception {
    Iterator<? extends List<Class<?>>> batches = new AgentBuilder.RedefinitionStrategy.BatchAllocator.ForMatchedGrouping(ElementMatchers.is(Object.class),
            ElementMatchers.is(Void.class)).withMinimum(2).batch(Arrays.<Class<?>>asList(Object.class, Void.class, String.class)).iterator();
    assertThat(batches.hasNext(), is(true));
    assertThat(batches.next(), is(Arrays.<Class<?>>asList(Object.class, Void.class)));
    assertThat(batches.hasNext(), is(true));
    assertThat(batches.next(), is(Collections.<Class<?>>singletonList(String.class)));
    assertThat(batches.hasNext(), is(false));
}