net.bytebuddy.implementation.bytecode.assign.Assigner Java Examples

The following examples show how to use net.bytebuddy.implementation.bytecode.assign.Assigner. 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: InvokeDynamicTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(7)
public void testBootstrapWithFieldExplicitType() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(Class.forName(BOOTSTRAP_CLASS));
    DynamicType.Loaded<Simple> dynamicType = new ByteBuddy()
            .subclass(Simple.class)
            .defineField(FOO, Object.class)
            .method(isDeclaredBy(Simple.class))
            .intercept(InvokeDynamic.bootstrap(typeDescription.getDeclaredMethods().filter(named("bootstrapSimple")).getOnly())
                    .invoke(QUX, String.class)
                    .withField(FOO).as(String.class)
                    .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(dynamicType.getLoaded().getDeclaredFields().length, is(1));
    Simple instance = dynamicType.getLoaded().getDeclaredConstructor().newInstance();
    Field field = dynamicType.getLoaded().getDeclaredField(FOO);
    field.setAccessible(true);
    field.set(instance, FOO);
    assertThat(instance.foo(), is(FOO));
}
 
Example #2
Source File: MethodDelegationBinder.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodBinding bind(Implementation.Target implementationTarget,
                          MethodDescription source,
                          TerminationHandler terminationHandler,
                          MethodInvoker methodInvoker,
                          Assigner assigner) {
    List<MethodBinding> targets = new ArrayList<MethodBinding>();
    for (Record record : records) {
        MethodBinding methodBinding = record.bind(implementationTarget, source, terminationHandler, methodInvoker, assigner);
        if (methodBinding.isValid()) {
            targets.add(methodBinding);
        }
    }
    if (targets.isEmpty()) {
        throw new IllegalArgumentException("None of " + records + " allows for delegation from " + source);
    }
    return bindingResolver.resolve(ambiguityResolver, source, targets);
}
 
Example #3
Source File: PrimitiveTypeAwareAssignerImplicitUnboxingTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testImplicitUnboxingAssignment() {
    StackManipulation stackManipulation = primitiveAssigner.assign(source, target, Assigner.Typing.DYNAMIC);
    assertThat(stackManipulation.isValid(), is(assignable));
    verify(chainedStackManipulation).isValid();
    verifyNoMoreInteractions(chainedStackManipulation);
    verify(source, atLeast(0)).represents(any(Class.class));
    verify(source, atLeast(1)).isPrimitive();
    verify(source).asGenericType();
    verifyNoMoreInteractions(source);
    verify(target, atLeast(0)).represents(any(Class.class));
    verify(target, atLeast(1)).isPrimitive();
    verifyNoMoreInteractions(target);
    verify(chainedAssigner).assign(source, TypeDescription.Generic.OfNonGenericType.ForLoadedType.of(wrapperType), Assigner.Typing.DYNAMIC);
    verifyNoMoreInteractions(chainedAssigner);
}
 
Example #4
Source File: AllArgumentsBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
private void testLegalStrictBinding(Assigner.Typing typing) throws Exception {
    when(annotation.value()).thenReturn(AllArguments.Assignment.STRICT);
    when(stackManipulation.isValid()).thenReturn(true);
    when(source.getParameters()).thenReturn(new ParameterList.Explicit.ForTypes(source, firstSourceType, secondSourceType));
    when(source.isStatic()).thenReturn(false);
    when(targetType.isArray()).thenReturn(true);
    when(targetType.getComponentType()).thenReturn(componentType);
    when(componentType.getStackSize()).thenReturn(StackSize.SINGLE);
    when(target.getType()).thenReturn(targetType);
    MethodDelegationBinder.ParameterBinding<?> parameterBinding = AllArguments.Binder.INSTANCE
            .bind(annotationDescription, source, target, implementationTarget, assigner, typing);
    assertThat(parameterBinding.isValid(), is(true));
    verify(source, atLeast(1)).getParameters();
    verify(source, atLeast(1)).isStatic();
    verify(target, atLeast(1)).getType();
    verify(target, never()).getDeclaredAnnotations();
    verify(assigner).assign(firstSourceType, componentType, typing);
    verify(assigner).assign(secondSourceType, componentType, typing);
    verifyNoMoreInteractions(assigner);
}
 
Example #5
Source File: AllArgumentsBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testIllegalBinding() throws Exception {
    when(target.getIndex()).thenReturn(1);
    when(annotation.value()).thenReturn(AllArguments.Assignment.STRICT);
    when(stackManipulation.isValid()).thenReturn(false);
    when(source.getParameters()).thenReturn(new ParameterList.Explicit.ForTypes(source, firstSourceType, secondSourceType));
    when(source.isStatic()).thenReturn(false);
    when(targetType.isArray()).thenReturn(true);
    when(targetType.getComponentType()).thenReturn(componentType);
    when(componentType.getStackSize()).thenReturn(StackSize.SINGLE);
    when(target.getType()).thenReturn(targetType);
    when(target.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    MethodDelegationBinder.ParameterBinding<?> parameterBinding = AllArguments.Binder.INSTANCE
            .bind(annotationDescription, source, target, implementationTarget, assigner, Assigner.Typing.STATIC);
    assertThat(parameterBinding.isValid(), is(false));
    verify(source, atLeast(1)).getParameters();
    verify(source, atLeast(1)).isStatic();
    verify(target, atLeast(1)).getType();
    verify(target, never()).getDeclaredAnnotations();
    verify(assigner).assign(firstSourceType, componentType, Assigner.Typing.STATIC);
    verifyNoMoreInteractions(assigner);
}
 
Example #6
Source File: PrimitiveUnboxingDelegateDirectTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testImplicitBoxing() throws Exception {
    TypeDescription.Generic referenceTypeDescription = mock(TypeDescription.Generic.class);
    when(referenceTypeDescription.asGenericType()).thenReturn(referenceTypeDescription);
    StackManipulation primitiveStackManipulation = PrimitiveUnboxingDelegate.forReferenceType(referenceTypeDescription)
            .assignUnboxedTo(primitiveTypeDescription, chainedAssigner, Assigner.Typing.DYNAMIC);
    assertThat(primitiveStackManipulation.isValid(), is(true));
    StackManipulation.Size size = primitiveStackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(sizeChange));
    assertThat(size.getMaximalSize(), is(sizeChange));
    verify(methodVisitor).visitMethodInsn(Opcodes.INVOKEVIRTUAL,
            Type.getInternalName(wrapperType),
            unboxingMethodName,
            unboxingMethodDescriptor,
            false);
    verifyNoMoreInteractions(methodVisitor);
    verify(chainedAssigner).assign(referenceTypeDescription, TypeDescription.Generic.OfNonGenericType.ForLoadedType.of(wrapperType), Assigner.Typing.DYNAMIC);
    verifyNoMoreInteractions(chainedAssigner);
    verify(stackManipulation, atLeast(1)).isValid();
    verify(stackManipulation).apply(methodVisitor, implementationContext);
    verifyNoMoreInteractions(stackManipulation);
}
 
Example #7
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot access non-static " + fieldDescription + " from " + instrumentedMethod);
    }
    StackManipulation stackManipulation = new StackManipulation.Compound(
            fieldDescription.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            FieldAccess.forField(fieldDescription).read(),
            assigner.assign(fieldDescription.getType(), target.getType(), typing)
    );
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + fieldDescription + " to " + target);
    }
    return stackManipulation;
}
 
Example #8
Source File: FieldValueBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetterNameDiscovery() throws Exception {
    doReturn(void.class).when(annotation).declaringType();
    when(annotation.value()).thenReturn(FieldValue.Binder.Delegate.BEAN_PROPERTY);
    when(instrumentedType.getDeclaredFields()).thenReturn(new FieldList.Explicit<FieldDescription.InDefinedShape>(fieldDescription));
    when(fieldDescription.getActualName()).thenReturn(FOO);
    when(fieldDescription.isVisibleTo(instrumentedType)).thenReturn(true);
    when(target.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(stackManipulation.isValid()).thenReturn(true);
    when(source.getInternalName()).thenReturn("getFoo");
    when(source.getActualName()).thenReturn("getFoo");
    when(source.getReturnType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(source.getParameters()).thenReturn(new ParameterList.Empty<ParameterDescription.InDefinedShape>());
    MethodDelegationBinder.ParameterBinding<?> binding = FieldValue.Binder.INSTANCE.bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC);
    assertThat(binding.isValid(), is(true));
}
 
Example #9
Source File: FieldProxyBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetterForImplicitNamedFieldInHierarchy() throws Exception {
    when(target.getType()).thenReturn(genericSetterType);
    doReturn(void.class).when(annotation).declaringType();
    when(annotation.value()).thenReturn(FieldProxy.Binder.BEAN_PROPERTY);
    when(fieldDescription.getActualName()).thenReturn(FOO);
    when(source.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(source.getParameters()).thenReturn(new ParameterList.Explicit.ForTypes(source, fieldType));
    when(source.getActualName()).thenReturn("setFoo");
    when(source.getInternalName()).thenReturn("setFoo");
    when(fieldDescription.isVisibleTo(instrumentedType)).thenReturn(true);
    MethodDelegationBinder.ParameterBinding<?> binding = new FieldProxy.Binder(getterMethod, setterMethod).bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC);
    assertThat(binding.isValid(), is(true));
}
 
Example #10
Source File: FieldProxyBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetterForImplicitNamedFieldInHierarchy() throws Exception {
    when(target.getType()).thenReturn(genericGetterType);
    doReturn(void.class).when(annotation).declaringType();
    when(annotation.value()).thenReturn(FieldProxy.Binder.BEAN_PROPERTY);
    when(fieldDescription.getActualName()).thenReturn(FOO);
    when(source.getReturnType()).thenReturn(genericFieldType);
    when(source.getParameters()).thenReturn(new ParameterList.Empty<ParameterDescription.InDefinedShape>());
    when(source.getName()).thenReturn("getFoo");
    when(source.getActualName()).thenReturn("getFoo");
    when(source.getInternalName()).thenReturn("getFoo");
    when(fieldDescription.isVisibleTo(instrumentedType)).thenReturn(true);
    MethodDelegationBinder.ParameterBinding<?> binding = new FieldProxy.Binder(getterMethod, setterMethod).bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC);
    assertThat(binding.isValid(), is(true));
}
 
Example #11
Source File: FieldProxyBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetterForExplicitNamedFieldInNamedType() throws Exception {
    when(target.getType()).thenReturn(genericSetterType);
    doReturn(Foo.class).when(annotation).declaringType();
    when(instrumentedType.isAssignableTo(TypeDescription.ForLoadedType.of(Foo.class))).thenReturn(true);
    when(annotation.value()).thenReturn(FOO);
    when(fieldDescription.getActualName()).thenReturn(FOO);
    when(source.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(source.getParameters()).thenReturn(new ParameterList.Explicit.ForTypes(source, fieldType));
    when(source.getName()).thenReturn("setFoo");
    when(source.getInternalName()).thenReturn("setFoo");
    when(fieldDescription.isVisibleTo(instrumentedType)).thenReturn(true);
    MethodDelegationBinder.ParameterBinding<?> binding = new FieldProxy.Binder(getterMethod, setterMethod).bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC);
    assertThat(binding.isValid(), is(true));
}
 
Example #12
Source File: MethodCallProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor,
                  Context implementationContext,
                  MethodDescription instrumentedMethod) {
    FieldList<?> fieldList = instrumentedType.getDeclaredFields();
    List<StackManipulation> fieldLoadings = new ArrayList<StackManipulation>(fieldList.size());
    for (FieldDescription fieldDescription : fieldList) {
        fieldLoadings.add(new StackManipulation.Compound(MethodVariableAccess.loadThis(), FieldAccess.forField(fieldDescription).read()));
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            new StackManipulation.Compound(fieldLoadings),
            MethodInvocation.invoke(accessorMethod),
            assigner.assign(accessorMethod.getReturnType(), instrumentedMethod.getReturnType(), Assigner.Typing.DYNAMIC),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #13
Source File: ReferenceTypeAwareAssignerTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSourceToTargetAssignable() throws Exception {
    defineAssignability(true, false);
    StackManipulation stackManipulation = ReferenceTypeAwareAssigner.INSTANCE.assign(source, target, Assigner.Typing.STATIC);
    assertThat(stackManipulation.isValid(), is(true));
    StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(0));
    assertThat(size.getMaximalSize(), is(0));
    verifyZeroInteractions(methodVisitor);
}
 
Example #14
Source File: SuperCallBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidSuperMethodCall() throws Exception {
    when(targetParameterType.represents(any(Class.class))).thenReturn(true);
    when(specialMethodInvocation.isValid()).thenReturn(true);
    MethodDelegationBinder.ParameterBinding<?> parameterBinding = SuperCall.Binder.INSTANCE
            .bind(annotationDescription, source, target, implementationTarget, assigner, Assigner.Typing.STATIC);
    verify(implementationTarget).invokeSuper(sourceToken);
    verifyNoMoreInteractions(implementationTarget);
    assertThat(parameterBinding.isValid(), is(true));
}
 
Example #15
Source File: MethodDelegationBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnored() throws Exception {
    assertThat(MethodDelegationBinder.Record.Illegal.INSTANCE.bind(mock(Implementation.Target.class),
            mock(MethodDescription.class),
            mock(MethodDelegationBinder.TerminationHandler.class),
            mock(MethodDelegationBinder.MethodInvoker.class),
            mock(Assigner.class)).isValid(), is(false));
}
 
Example #16
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public MethodDelegationBinder.ParameterBinding<?> bind(AnnotationDescription.Loadable<StringValue> annotation,
                                                       MethodDescription source,
                                                       ParameterDescription target,
                                                       Implementation.Target implementationTarget,
                                                       Assigner assigner,
                                                       Assigner.Typing typing) {
    if (!target.getType().asErasure().represents(String.class)) {
        throw new IllegalStateException(target + " makes wrong use of StringValue");
    }
    StackManipulation constant = new TextConstant(annotation.load().value());
    return new MethodDelegationBinder.ParameterBinding.Anonymous(constant);
}
 
Example #17
Source File: PrimitiveUnboxingDelegateDirectTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(primitiveTypeDescription.isPrimitive()).thenReturn(true);
    when(primitiveTypeDescription.represents(primitiveType)).thenReturn(true);
    when(primitiveTypeDescription.asErasure()).thenReturn(rawPrimitiveTypeDescription);
    when(rawPrimitiveTypeDescription.getInternalName()).thenReturn(Type.getInternalName(primitiveType));
    when(wrapperTypeDescription.isPrimitive()).thenReturn(false);
    when(wrapperTypeDescription.represents(wrapperType)).thenReturn(true);
    when(wrapperTypeDescription.asErasure()).thenReturn(rawWrapperTypeDescription);
    when(rawWrapperTypeDescription.getInternalName()).thenReturn(Type.getInternalName(wrapperType));
    when(chainedAssigner.assign(any(TypeDescription.Generic.class), any(TypeDescription.Generic.class), any(Assigner.Typing.class))).thenReturn(stackManipulation);
    when(stackManipulation.isValid()).thenReturn(true);
    when(stackManipulation.apply(any(MethodVisitor.class), any(Implementation.Context.class))).thenReturn(StackSize.ZERO.toIncreasingSize());
}
 
Example #18
Source File: BytecodeProviderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		MethodDescription instrumentedMethod) {
	methodVisitor.visitLdcInsn( getters.length );
	methodVisitor.visitTypeInsn( Opcodes.ANEWARRAY, Type.getInternalName( Object.class ) );
	int index = 0;
	for ( Method getter : getters ) {
		methodVisitor.visitInsn( Opcodes.DUP );
		methodVisitor.visitLdcInsn( index++ );
		methodVisitor.visitVarInsn( Opcodes.ALOAD, 1 );
		methodVisitor.visitTypeInsn( Opcodes.CHECKCAST, Type.getInternalName( clazz ) );
		methodVisitor.visitMethodInsn(
				Opcodes.INVOKEVIRTUAL,
				Type.getInternalName( clazz ),
				getter.getName(),
				Type.getMethodDescriptor( getter ),
				false
		);
		if ( getter.getReturnType().isPrimitive() ) {
			PrimitiveBoxingDelegate.forPrimitive( new TypeDescription.ForLoadedType( getter.getReturnType() ) )
					.assignBoxedTo(
							TypeDescription.Generic.OBJECT,
							ReferenceTypeAwareAssigner.INSTANCE,
							Assigner.Typing.STATIC
					)
					.apply( methodVisitor, implementationContext );
		}
		methodVisitor.visitInsn( Opcodes.AASTORE );
	}
	methodVisitor.visitInsn( Opcodes.ARETURN );
	return new Size( 6, instrumentedMethod.getStackSize() );
}
 
Example #19
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Creates a new {@link Enum} type.
 * </p>
 * <p>
 * <b>Note</b>: Byte Buddy does not cache previous subclasses but will attempt the generation of a new subclass. For caching
 * types, a external cache or {@link TypeCache} should be used.
 * </p>
 *
 * @param values The names of the type's enumeration constants
 * @return A type builder for creating an enumeration type.
 */
public DynamicType.Builder<? extends Enum<?>> makeEnumeration(Collection<? extends String> values) {
    if (values.isEmpty()) {
        throw new IllegalArgumentException("Require at least one enumeration constant");
    }
    TypeDescription.Generic enumType = TypeDescription.Generic.Builder.parameterizedType(Enum.class, TargetType.class).build();
    return new SubclassDynamicTypeBuilder<Enum<?>>(instrumentedTypeFactory.subclass(namingStrategy.subclass(enumType),
            ModifierContributor.Resolver.of(Visibility.PUBLIC, TypeManifestation.FINAL, EnumerationState.ENUMERATION).resolve(),
            enumType),
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            classWriterStrategy,
            ignoredMethods,
            ConstructorStrategy.Default.NO_CONSTRUCTORS)
            .defineConstructor(Visibility.PRIVATE).withParameters(String.class, int.class)
            .intercept(SuperMethodCall.INSTANCE)
            .defineMethod(EnumerationImplementation.ENUM_VALUE_OF_METHOD_NAME,
                    TargetType.class,
                    Visibility.PUBLIC, Ownership.STATIC).withParameters(String.class)
            .intercept(MethodCall.invoke(enumType.getDeclaredMethods()
                    .filter(named(EnumerationImplementation.ENUM_VALUE_OF_METHOD_NAME).and(takesArguments(Class.class, String.class))).getOnly())
                    .withOwnType().withArgument(0)
                    .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC))
            .defineMethod(EnumerationImplementation.ENUM_VALUES_METHOD_NAME,
                    TargetType[].class,
                    Visibility.PUBLIC, Ownership.STATIC)
            .intercept(new EnumerationImplementation(new ArrayList<String>(values)));
}
 
Example #20
Source File: FieldProxyBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testIllegalType() throws Exception {
    doReturn(Foo.class).when(annotation).declaringType();
    when(annotation.value()).thenReturn(FOO);
    TypeDescription targetType = mock(TypeDescription.class);
    TypeDescription.Generic genericTargetType = mock(TypeDescription.Generic.class);
    when(genericTargetType.asErasure()).thenReturn(targetType);
    when(target.getType()).thenReturn(genericTargetType);
    when(instrumentedType.isAssignableTo(TypeDescription.ForLoadedType.of(Foo.class))).thenReturn(true);
    new FieldProxy.Binder(getterMethod, setterMethod).bind(annotationDescription, source, target, implementationTarget, assigner, Assigner.Typing.STATIC);
}
 
Example #21
Source File: StubValueBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonVoidAssignableReturnType() throws Exception {
    when(target.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(source.getReturnType()).thenReturn(genericType);
    when(stackManipulation.isValid()).thenReturn(true);
    assertThat(StubValue.Binder.INSTANCE.bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC).isValid(), is(true));
}
 
Example #22
Source File: MethodDelegationBinder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodBinding bind(Implementation.Target implementationTarget,
                          MethodDescription source,
                          TerminationHandler terminationHandler,
                          MethodInvoker methodInvoker,
                          Assigner assigner) {
    return MethodBinding.Illegal.INSTANCE;
}
 
Example #23
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    StackManipulation stackManipulation = new StackManipulation.Compound(
            appender.toStackManipulation(instrumentedMethod, methodDescription, targetHandler),
            assigner.assign(methodDescription.isConstructor()
                    ? methodDescription.getDeclaringType().asGenericType()
                    : methodDescription.getReturnType(), target.getType(), typing)
    );
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign return type of " + methodDescription + " to " + target);
    }
    return stackManipulation;
}
 
Example #24
Source File: ApmSpanBuilderInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class)
public static void createSpan(@Advice.Argument(value = 0, typing = Assigner.Typing.DYNAMIC) @Nullable AbstractSpan<?> parentContext,
                              @Advice.Origin Class<?> spanBuilderClass,
                              @Advice.FieldValue(value = "tags") Map<String, Object> tags,
                              @Advice.FieldValue(value = "operationName") String operationName,
                              @Advice.FieldValue(value = "microseconds") long microseconds,
                              @Advice.Argument(1) @Nullable Iterable<Map.Entry<String, String>> baggage,
                              @Advice.Return(readOnly = false) Object span) {
    span = doCreateTransactionOrSpan(parentContext, tags, operationName, microseconds, baggage, spanBuilderClass.getClassLoader());
}
 
Example #25
Source File: SpanContextInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class)
public static void toTraceId(@Advice.FieldValue(value = "traceContext", typing = Assigner.Typing.DYNAMIC) @Nullable AbstractSpan<?> traceContext,
                             @Advice.Return(readOnly = false) String spanId) {
    if (traceContext != null) {
        spanId = traceContext.getTraceContext().getId().toString();
    }
}
 
Example #26
Source File: OriginBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassBinding() throws Exception {
    when(targetType.getInternalName()).thenReturn(FOO);
    when(targetType.represents(Class.class)).thenReturn(true);
    MethodDelegationBinder.ParameterBinding<?> parameterBinding = Origin.Binder.INSTANCE
            .bind(annotationDescription, source, target, implementationTarget, assigner, Assigner.Typing.STATIC);
    assertThat(parameterBinding.isValid(), is(true));
    verify(implementationTarget).getOriginType();
}
 
Example #27
Source File: SpanContextInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class)
public static void baggageItems(@Advice.FieldValue(value = "traceContext", typing = Assigner.Typing.DYNAMIC) @Nullable AbstractSpan<?> traceContext,
                                @Advice.Return(readOnly = false) Iterable<Map.Entry<String, String>> baggage) {
    if (traceContext != null) {
        baggage = doGetBaggage(traceContext);
    } else {
        logger.info("The traceContext is null");
    }
}
 
Example #28
Source File: PipeBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testCannotPipeStaticMethod() throws Exception {
    when(target.getType()).thenReturn(genericTargetMethodType);
    when(source.isStatic()).thenReturn(true);
    MethodDelegationBinder.ParameterBinding<?> parameterBinding = binder.bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC);
    assertThat(parameterBinding.isValid(), is(false));
}
 
Example #29
Source File: ReferenceTypeAwareAssignerTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMutualAssignable() throws Exception {
    defineAssignability(true, true);
    StackManipulation stackManipulation = ReferenceTypeAwareAssigner.INSTANCE.assign(source, target, Assigner.Typing.STATIC);
    assertThat(stackManipulation.isValid(), is(true));
    StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(0));
    assertThat(size.getMaximalSize(), is(0));
    verifyZeroInteractions(methodVisitor);
}
 
Example #30
Source File: OkHttpClientAsyncInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onBeforeEnqueue(@Advice.Origin Class<? extends Call> clazz,
                                    @Advice.FieldValue(value = "originalRequest", typing = Assigner.Typing.DYNAMIC, readOnly = false) @Nullable Request originalRequest,
                                    @Advice.Argument(value = 0, readOnly = false) @Nullable Callback callback,
                                    @Advice.Local("span") Span span) {
    if (tracer == null || tracer.getActive() == null || callbackWrapperCreator == null) {
        return;
    }

    final WrapperCreator<Callback> wrapperCreator = callbackWrapperCreator.getForClassLoaderOfClass(clazz);
    if (originalRequest == null || callback == null || wrapperCreator == null) {
        return;
    }

    final AbstractSpan<?> parent = tracer.getActive();

    Request request = originalRequest;
    URL url = request.url();
    span = HttpClientHelper.startHttpClientSpan(parent, request.method(), url.toString(), url.getProtocol(),
        OkHttpClientHelper.computeHostName(url.getHost()), url.getPort());
    if (span != null) {
        span.activate();
        if (headerSetterHelperManager != null) {
            TextHeaderSetter<Request.Builder> headerSetter = headerSetterHelperManager.getForClassLoaderOfClass(Request.class);
            if (headerSetter != null) {
                Request.Builder builder = originalRequest.newBuilder();
                span.propagateTraceContext(builder, headerSetter);
                originalRequest = builder.build();
            }
        }
        callback = wrapperCreator.wrap(callback, span);
    }
}