net.bytebuddy.implementation.FieldAccessor Java Examples

The following examples show how to use net.bytebuddy.implementation.FieldAccessor. 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: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Implementation fieldWriter(FieldDescription enhancedField) {
	Implementation implementation;
	if ( !enhancementContext.hasLazyLoadableAttributes( managedCtClass ) || !enhancementContext.isLazyLoadable( enhancedField ) ) {
		if ( enhancedField.getDeclaringType().asErasure().equals( managedCtClass ) ) {
			implementation = FieldAccessor.ofField( enhancedField.getName() ).in( enhancedField.getDeclaringType().asErasure() );
		}
		else {
			implementation = new Implementation.Simple( new FieldMethodWriter( managedCtClass, enhancedField ) );
		}
	}
	else {
		implementation = new Implementation.Simple( FieldWriterAppender.of( managedCtClass, enhancedField ) );
	}
	implementation = InlineDirtyCheckingHandler.wrap( managedCtClass, enhancementContext, enhancedField, implementation );
	return BiDirectionalAssociationHandler.wrap( managedCtClass, enhancementContext, enhancedField, implementation );
}
 
Example #2
Source File: ByteBuddyProcessFunctionInvoker.java    From da-streamingledger with Apache License 2.0 5 votes vote down vote up
private static Builder<?> configureByteBuddyBuilder(
        PackageLocalNamingStrategy generatedTypeName,
        TypeDefinition generatedType,
        TypeDefinition processFunctionType,
        ForLoadedConstructor superTypeConstructor,
        MethodDescription processMethodType,
        int numberOfStateBindings) {

    return new ByteBuddy()
            // final class <Name> extends <ProcessFunctionInvoker> {
            .with(generatedTypeName)
            .subclass(generatedType, ConstructorStrategy.Default.NO_CONSTRUCTORS).modifiers(Modifier.FINAL)
            // private final <processFunction class> delegate;
            .defineField("delegate", processFunctionType, Visibility.PRIVATE, FieldManifestation.FINAL)
            // public <Name>(<processFunction class> delegate) {
            //     super();
            //     this.delegate = delegate;
            // }
            .defineConstructor(Modifier.PUBLIC)
            .withParameters(processFunctionType)
            .intercept(MethodCall.invoke(superTypeConstructor)
                    .andThen(FieldAccessor.ofField("delegate").setsArgumentAt(0))
            )
            // invoke(input, context, StateAccess[] arguments) {
            //      this.delegate.invoke(input, context, arguments[0], arguments[1], .. arguments[n - 1]);
            // }
            .method(ElementMatchers.named("invoke"))
            .intercept(MethodCall.invoke(processMethodType)
                    .onField("delegate")
                    .withArgument(0, 1) // event & context
                    .withArgumentArrayElements(2, numberOfStateBindings) // StateAccess
                    .withAssigner(Assigner.DEFAULT, Typing.STATIC)
            );
}
 
Example #3
Source File: EnhancerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static DynamicType.Builder<?> addFieldWithGetterAndSetter(
		DynamicType.Builder<?> builder,
		Class<?> type,
		String fieldName,
		String getterName,
		String setterName) {
	return builder
			.defineField( fieldName, type, Visibility.PRIVATE, FieldPersistence.TRANSIENT )
					.annotateField( AnnotationDescription.Builder.ofType( Transient.class ).build() )
			.defineMethod( getterName, type, Visibility.PUBLIC )
					.intercept( FieldAccessor.ofField( fieldName ) )
			.defineMethod( setterName, void.class, Visibility.PUBLIC )
					.withParameters( type )
					.intercept( FieldAccessor.ofField( fieldName ) );
}
 
Example #4
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Implementation fieldReader(FieldDescription enhancedField) {
	if ( !enhancementContext.hasLazyLoadableAttributes( managedCtClass ) || !enhancementContext.isLazyLoadable( enhancedField ) ) {
		if ( enhancedField.getDeclaringType().asErasure().equals( managedCtClass ) ) {
			return FieldAccessor.ofField( enhancedField.getName() ).in( enhancedField.getDeclaringType().asErasure() );
		}
		else {
			return new Implementation.Simple( new FieldMethodReader( managedCtClass, enhancedField ) );
		}
	}
	else {
		return new Implementation.Simple( FieldReaderAppender.of( managedCtClass, enhancedField ) );
	}
}
 
Example #5
Source File: ByteBuddyState.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ProxyDefinitionHelpers() {
	this.groovyGetMetaClassFilter = isSynthetic().and( named( "getMetaClass" )
			.and( returns( td -> "groovy.lang.MetaClass".equals( td.getName() ) ) ) );
	this.virtualNotFinalizerFilter = isVirtual().and( not( isFinalizer() ) );
	this.hibernateGeneratedMethodFilter = nameStartsWith( "$$_hibernate_" ).and( isVirtual() );

	PrivilegedAction<MethodDelegation> delegateToInterceptorDispatcherMethodDelegationPrivilegedAction =
			new PrivilegedAction<MethodDelegation>() {

		@Override
		public MethodDelegation run() {
			return MethodDelegation.to( ProxyConfiguration.InterceptorDispatcher.class );
		}
	};

	this.delegateToInterceptorDispatcherMethodDelegation = System.getSecurityManager() != null
			? AccessController.doPrivileged( delegateToInterceptorDispatcherMethodDelegationPrivilegedAction )
			: delegateToInterceptorDispatcherMethodDelegationPrivilegedAction.run();

	PrivilegedAction<FieldAccessor.PropertyConfigurable> interceptorFieldAccessorPrivilegedAction =
			new PrivilegedAction<FieldAccessor.PropertyConfigurable>() {

		@Override
		public FieldAccessor.PropertyConfigurable run() {
			return FieldAccessor.ofField( ProxyConfiguration.INTERCEPTOR_FIELD_NAME )
					.withAssigner( Assigner.DEFAULT, Assigner.Typing.DYNAMIC );
		}
	};

	this.interceptorFieldAccessor = System.getSecurityManager() != null
			? AccessController.doPrivileged( interceptorFieldAccessorPrivilegedAction )
			: interceptorFieldAccessorPrivilegedAction.run();
}
 
Example #6
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 #7
Source File: BeanBuilder.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private DynamicType.Builder<?> createGetter(DynamicType.Builder<?> builder,
                                            POJOProperty property,
                                            TypeDefinition typeDefinition)
{
    final String methodName = property.getGetter() != null
            ? property.getGetter().getName() //if the getter exists, use it's name because it could be like 'isXXX'
            : buildGetterName(property.getName());
    return builder
                .defineMethod(methodName, typeDefinition)
                .intercept(FieldAccessor.ofBeanProperty());
}
 
Example #8
Source File: BeanBuilder.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private DynamicType.Builder<?> createSetter(DynamicType.Builder<?> builder,
                                            POJOProperty property,
                                            TypeDefinition typeDefinition)
{
    return builder
            .defineMethod(buildSetterName(property.getName()), Void.TYPE, Visibility.PUBLIC)
            .withParameters(typeDefinition)
            .intercept(FieldAccessor.ofBeanProperty());
}
 
Example #9
Source File: TemplateModelProxyHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private static BiFunction<StateNode, BeanModelType<?>, Object> createProxyConstructor(
        ClassLoader classLoader, Builder<?> proxyBuilder, String classFqn) {
    String proxyClassName = generateProxyClassName(classFqn, classLoader);
    Class<?> proxyType = proxyBuilder

            // Handle bean methods (and abstract methods for error handling)
            .method(method -> isAccessor(method) || method.isAbstract())
            .intercept(MethodDelegation.to(proxyHandler))

            // Handle internal $stateNode methods
            .defineField("$stateNode", StateNode.class)
            .method(method -> "$stateNode".equals(method.getName()))
            .intercept(FieldAccessor.ofField("$stateNode"))

            // Handle internal $modelType methods
            .defineField("$modelType", BeanModelType.class)
            .method(method -> "$modelType".equals(method.getName()))
            .intercept(FieldAccessor.ofField("$modelType"))

            // Create the class
            .name(proxyClassName).make()
            .load(classLoader, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();

    return (node, modelType) -> {
        Object instance = ReflectTools.createProxyInstance(proxyType,
                modelType.getProxyType());
        ModelProxy modelProxy = (ModelProxy) instance;
        modelProxy.$stateNode(node);
        modelProxy.$modelType(modelType);

        modelType.createInitialValues(node);
        return instance;
    };
}
 
Example #10
Source File: RobustElementFactory.java    From Selenium-Foundation with Apache License 2.0 4 votes vote down vote up
/**
 * Get robust web element factory for this context.
 * 
 * @param context target context
 * @return robust web element factory
 */
private static synchronized InstanceCreator getCreator(final WrapsContext context) {
    WebDriver driver = context.getWrappedDriver();
    String driverName = driver.getClass().getName();
    if (creatorMap.containsKey(driverName)) {
        return creatorMap.get(driverName);
    }
    
    WebElement reference = driver.findElement(By.cssSelector("*"));
    Class<? extends WebElement> refClass = reference.getClass();
    
    Class<? extends WebElement> wrapperClass = new ByteBuddy()
                    .subclass(refClass)
                    .name(refClass.getPackage().getName() + ".Robust" + refClass.getSimpleName())
                    .method(not(isDeclaredBy(Object.class)))
                    .intercept(MethodDelegation.withEmptyConfiguration()
                            .withBinders(TargetMethodAnnotationDrivenBinder.ParameterBinder.DEFAULTS)
                            .withResolvers(MethodNameEqualityResolver.INSTANCE, BindingPriority.Resolver.INSTANCE)
                            .filter(not(isDeclaredBy(Object.class)))
                            .toField("interceptor"))
                    .implement(RobustWebElement.class)
                    .defineField("interceptor", RobustElementWrapper.class, Visibility.PRIVATE)
                    .implement(InterceptionAccessor.class).intercept(FieldAccessor.ofBeanProperty())
                    .make()
                    .load(refClass.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                    .getLoaded();
    
    InstanceCreator creator;
    
    try {
        creator = new ByteBuddy()
                        .subclass(InstanceCreator.class)
                        .method(not(isDeclaredBy(Object.class)))
                        .intercept(MethodDelegation.toConstructor(wrapperClass))
                        .make()
                        .load(wrapperClass.getClassLoader())
                        .getLoaded().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw UncheckedThrow.throwUnchecked(e);
    }
    
    creatorMap.put(driverName, creator);
    return creator;
}
 
Example #11
Source File: JackpotTrees.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static <T> T createInstance(Context ctx, Class<T> clazz, Name ident, JCIdent jcIdent, Class<?>[] requiredConstructor, Object[] params) {
    try {
        Class<?> fake = baseClass2Impl.get(clazz);

        if (fake == null) {
            Method visitIdent = Visitor.class.getDeclaredMethod("visitIdent", JCIdent.class);
            Method visitIdentifier = TreeVisitor.class.getDeclaredMethod("visitIdentifier", IdentifierTree.class, Object.class);
            Method toString = Object.class.getDeclaredMethod("toString");
            fake = Utilities.load(new ByteBuddy()
                    .subclass(clazz)
                    .implement(IdentifierTree.class)
                    .defineField("ident", Name.class, Visibility.PUBLIC)
                    .defineField("jcIdent", JCIdent.class, Visibility.PUBLIC)
                    .method(ElementMatchers.named("getName")).intercept(FieldAccessor.ofField("ident"))
                    .method(ElementMatchers.named("getKind")).intercept(FixedValue.value(Kind.IDENTIFIER))
                    .method(ElementMatchers.named("accept").and(ElementMatchers.takesArguments(Visitor.class))).intercept(MethodCall.invoke(visitIdent).onArgument(0).withField("jcIdent"))
                    .method(ElementMatchers.named("accept").and(ElementMatchers.takesArgument(0, TreeVisitor.class))).intercept(MethodCall.invoke(visitIdentifier).onArgument(0).withThis().withArgument(1))
                    .method(ElementMatchers.named("toString")).intercept(MethodCall.invoke(toString).onField("ident"))
                    .name(JackpotTrees.class.getCanonicalName() + "$" + clazz.getCanonicalName().replace('.', '$'))
                    .make())
                    .getLoaded();
            baseClass2Impl.put(clazz, fake);
        }

        NEXT: for (Constructor c : fake.getDeclaredConstructors()) {
            if (c.getParameterCount() < requiredConstructor.length)
                continue;
            for (int e = 0; e < requiredConstructor.length; e++) {
                if (!c.getParameterTypes()[e].equals(requiredConstructor[e])) {
                    continue NEXT;
                }
            }
            java.util.List<Object> instances = new ArrayList<>();
            instances.addAll(Arrays.asList(params));
            for (int i = instances.size(); i < c.getParameterCount(); i++) {
                instances.add(null);
            }

            JCTree tree = (JCTree) c.newInstance(instances.toArray(new Object[0]));

            Field identField = fake.getDeclaredField("ident");

            identField.set(tree, ident);

            Field jcIdentField = fake.getDeclaredField("jcIdent");

            jcIdentField.set(tree, jcIdent);

            return clazz.cast(tree);
        }

        throw new IllegalStateException(Arrays.asList(fake.getDeclaredConstructors()).toString());
    } catch (IllegalAccessException | IllegalArgumentException | IllegalStateException | InstantiationException | NoSuchFieldException | NoSuchMethodException | SecurityException | InvocationTargetException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #12
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
DynamicType.Builder<?> applyTo(DynamicType.Builder<?> builder, boolean accessor) {
	boolean compositeOwner = false;

	builder = builder.visit( new AsmVisitorWrapper.ForDeclaredMethods().method( not( nameStartsWith( "$$_hibernate_" ) ), this ) );
	for ( FieldDescription enhancedField : enhancedFields ) {
		builder = builder
				.defineMethod(
						EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + enhancedField.getName(),
						enhancedField.getType().asErasure(),
						Visibility.PUBLIC
				)
				.intercept(
						accessor
								? FieldAccessor.ofField( enhancedField.getName() ).in( enhancedField.getDeclaringType().asErasure() )
								: fieldReader( enhancedField )
				)
				.defineMethod(
						EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + enhancedField.getName(),
						TypeDescription.VOID,
						Visibility.PUBLIC
				)
				.withParameters( enhancedField.getType().asErasure() )
				.intercept( accessor
									? FieldAccessor.ofField( enhancedField.getName() ).in( enhancedField.getDeclaringType().asErasure() )
									: fieldWriter( enhancedField ) );

		if ( !compositeOwner
				&& !accessor
				&& EnhancerImpl.isAnnotationPresent( enhancedField, Embedded.class )
				&& enhancementContext.isCompositeClass( enhancedField.getType().asErasure() )
				&& enhancementContext.doDirtyCheckingInline( managedCtClass ) ) {
			compositeOwner = true;
		}
	}

	if ( compositeOwner ) {
		builder = builder.implement( CompositeOwner.class );

		if ( enhancementContext.isCompositeClass( managedCtClass ) ) {
			builder = builder.defineMethod( EnhancerConstants.TRACKER_CHANGER_NAME, void.class, Visibility.PUBLIC )
					.withParameters( String.class )
					.intercept( Advice.to( CodeTemplates.CompositeOwnerDirtyCheckingHandler.class ).wrap( StubMethod.INSTANCE ) );
		}
	}

	if ( enhancementContext.doExtendedEnhancement( managedCtClass ) ) {
		builder = applyExtended( builder );
	}

	return builder;
}
 
Example #13
Source File: ByteBuddyState.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public FieldAccessor.PropertyConfigurable getInterceptorFieldAccessor() {
	return interceptorFieldAccessor;
}
 
Example #14
Source File: AbstractAnnotationFrameFactory.java    From Ferma with Apache License 2.0 4 votes vote down vote up
private <E> Class<? extends E> constructClass(final Element element, final Class<E> clazz) {
    Class constructedClass = constructedClassCache.get(clazz);
    if (constructedClass != null)
        return constructedClass;

    DynamicType.Builder<? extends E> classBuilder;
    if (clazz.isInterface())
        if (element instanceof Vertex)
            classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(AbstractVertexFrame.class).implement(clazz);
        else if (element instanceof Edge)
            classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(AbstractEdgeFrame.class).implement(clazz);
        else
            throw new IllegalStateException("class is neither an Edge or a vertex!");
    else {
        if( !(element instanceof Vertex || element instanceof Edge) )
            throw new IllegalStateException("element is neither an edge nor a vertex");
        else if (element instanceof Vertex && !VertexFrame.class.isAssignableFrom(clazz))
            throw new IllegalStateException(clazz.getName() + " Class is not a type of VertexFrame");
        else if (element instanceof Edge && !EdgeFrame.class.isAssignableFrom(clazz))
            throw new IllegalStateException(clazz.getName() + " Class is not a type of EdgeFrame");
        classBuilder = new ByteBuddy().subclass(clazz);
    }

    classBuilder = classBuilder.defineField("reflectionCache", ReflectionCache.class, Visibility.PRIVATE, FieldManifestation.PLAIN).implement(CachesReflection.class).intercept(FieldAccessor.
          ofBeanProperty());

    //try and construct any abstract methods that are left
    for (final Method method : clazz.getMethods())
        if (isAbstract(method))
            annotation_loop:
            for (final Annotation annotation : method.getAnnotations()) {
                final MethodHandler handler = methodHandlers.get(annotation.annotationType());
                if (handler != null) {
                    classBuilder = handler.processMethod(classBuilder, method, annotation);
                    break;
                }
            }

    constructedClass = classBuilder.make().load(AnnotationFrameFactory.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    this.constructedClassCache.put(clazz, constructedClass);
    return constructedClass;
}
 
Example #15
Source File: AbstractAnnotationFrameFactory.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private <E> Class<? extends E> constructClass(final Element element, final Class<E> clazz)
{
    Class constructedClass = constructedClassCache.get(clazz);
    if (constructedClass != null)
        return constructedClass;

    DynamicType.Builder<? extends E> classBuilder;
    if (clazz.isInterface())
    {
        if (element instanceof Vertex)
            classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(AbstractVertexFrame.class);
        else if (element instanceof Edge)
            classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(AbstractEdgeFrame.class);
        else
            throw new IllegalStateException("class is neither an Edge or a vertex!");

        if (clazz.getCanonicalName().contains("ByteBuddy"))
        {
            // if the input class is itself a bytebuddy class, only take its interfaces
            classBuilder = classBuilder.implement(clazz.getInterfaces());
        }
        else
        {
            classBuilder = classBuilder.implement(clazz);
        }
    }
    else
    {
        if (!(element instanceof Vertex || element instanceof Edge))
            throw new IllegalStateException("element is neither an edge nor a vertex");
        else if (element instanceof Vertex && !VertexFrame.class.isAssignableFrom(clazz))
            throw new IllegalStateException(clazz.getName() + " Class is not a type of VertexFrame");
        else if (element instanceof Edge && !EdgeFrame.class.isAssignableFrom(clazz))
            throw new IllegalStateException(clazz.getName() + " Class is not a type of EdgeFrame");
        classBuilder = new ByteBuddy().subclass(clazz);
    }

    classBuilder = classBuilder.defineField("reflectionCache", ReflectionCache.class, Visibility.PRIVATE, FieldManifestation.PLAIN)
                .implement(CachesReflection.class).intercept(FieldAccessor.ofBeanProperty());

    /*
     * Just a hack so that our generified frame types can work.
     *
     * This information will not really be used by the generated class.
     */
    classBuilder = classBuilder.typeVariable("T");

    // try and construct any abstract methods that are left
    for (final Method method : clazz.getMethods())
        if (isAbstract(method))
            annotation_loop: for (final Annotation annotation : method.getAnnotations())
            {
                final MethodHandler handler = methodHandlers.get(annotation.annotationType());
                if (handler != null)
                {
                    classBuilder = handler.processMethod(classBuilder, method, annotation);
                    break;
                }
            }

    DynamicType.Unloaded unloadedClass = classBuilder.make();
    constructedClass = unloadedClass.load(this.classLoader, ClassLoadingStrategy.Default.WRAPPER).getLoaded();
    this.constructedClassCache.put(clazz, constructedClass);
    return constructedClass;
}