Java Code Examples for org.hibernate.internal.util.ReflectHelper

The following examples show how to use org.hibernate.internal.util.ReflectHelper. 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: lams   Source File: RootClass.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void checkCompositeIdentifier() {
	if ( getIdentifier() instanceof Component ) {
		Component id = (Component) getIdentifier();
		if ( !id.isDynamic() ) {
			final Class idClass = id.getComponentClass();
			if ( idClass != null ) {
				final String idComponentClassName = idClass.getName();
				if ( !ReflectHelper.overridesEquals( idClass ) ) {
					LOG.compositeIdClassDoesNotOverrideEquals( idComponentClassName );
				}
				if ( !ReflectHelper.overridesHashCode( idClass ) ) {
					LOG.compositeIdClassDoesNotOverrideHashCode( idComponentClassName );
				}
				if ( !Serializable.class.isAssignableFrom( idClass ) ) {
					throw new MappingException(
							"Composite-id class must implement Serializable: " + idComponentClassName
					);
				}
			}
		}
	}
}
 
Example 2
Source Project: lams   Source File: AbstractAttribute.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Used by JDK serialization...
 *
 * @param ois The input stream from which we are being read...
 * @throws java.io.IOException Indicates a general IO stream exception
 * @throws ClassNotFoundException Indicates a class resolution issue
 */
protected void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
	ois.defaultReadObject();
	final String memberDeclaringClassName = ( String ) ois.readObject();
	final String memberName = ( String ) ois.readObject();
	final String memberType = ( String ) ois.readObject();

	final Class memberDeclaringClass = Class.forName(
			memberDeclaringClassName,
			false,
			declaringType.getJavaType().getClassLoader()
	);
	try {
		this.member = "method".equals( memberType )
				? memberDeclaringClass.getMethod( memberName, ReflectHelper.NO_PARAM_SIGNATURE )
				: memberDeclaringClass.getField( memberName );
	}
	catch ( Exception e ) {
		throw new IllegalStateException(
				"Unable to locate member [" + memberDeclaringClassName + "#"
						+ memberName + "]"
		);
	}
}
 
Example 3
Source Project: lams   Source File: EntityTuplizerFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Constructor<? extends EntityTuplizer> getProperConstructor(
		Class<? extends EntityTuplizer> clazz,
		Class[] constructorArgs) {
	Constructor<? extends EntityTuplizer> constructor = null;
	try {
		constructor = clazz.getDeclaredConstructor( constructorArgs );
		try {
			ReflectHelper.ensureAccessibility( constructor );
		}
		catch ( SecurityException e ) {
			constructor = null;
		}
	}
	catch ( NoSuchMethodException ignore ) {
	}

	return constructor;
}
 
Example 4
Source Project: lams   Source File: PojoInstantiator.java    License: GNU General Public License v2.0 6 votes vote down vote up
public PojoInstantiator(
		Class mappedClass,
		ReflectionOptimizer.InstantiationOptimizer optimizer,
		boolean embeddedIdentifier) {
	this.mappedClass = mappedClass;
	this.optimizer = optimizer;
	this.embeddedIdentifier = embeddedIdentifier;
	this.isAbstract = ReflectHelper.isAbstractClass( mappedClass );

	try {
		constructor = ReflectHelper.getDefaultConstructor(mappedClass);
	}
	catch ( PropertyNotFoundException pnfe ) {
		LOG.noDefaultConstructor( mappedClass.getName() );
		constructor = null;
	}
}
 
Example 5
@SuppressWarnings("unchecked")
private Constructor<? extends ComponentTuplizer> getProperConstructor(Class<? extends ComponentTuplizer> clazz) {
	Constructor<? extends ComponentTuplizer> constructor = null;
	try {
		constructor = clazz.getDeclaredConstructor( COMPONENT_TUP_CTOR_SIG );
		try {
			ReflectHelper.ensureAccessibility( constructor );
		}
		catch ( SecurityException e ) {
			constructor = null;
		}
	}
	catch ( NoSuchMethodException ignore ) {
	}

	return constructor;
}
 
Example 6
Source Project: lams   Source File: JavassistProxyFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void postInstantiate(
		final String entityName,
		final Class persistentClass,
		final Set<Class> interfaces,
		final Method getIdentifierMethod,
		final Method setIdentifierMethod,
		CompositeType componentIdType) throws HibernateException {
	this.entityName = entityName;
	this.persistentClass = persistentClass;
	this.interfaces = toArray( interfaces );
	this.getIdentifierMethod = getIdentifierMethod;
	this.setIdentifierMethod = setIdentifierMethod;
	this.componentIdType = componentIdType;
	this.overridesEquals = ReflectHelper.overridesEquals( persistentClass );

	this.proxyClass = buildJavassistProxyFactory().createClass();
}
 
Example 7
Source Project: lams   Source File: ByteBuddyProxyFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void postInstantiate(
		String entityName,
		Class persistentClass,
		Set<Class> interfaces,
		Method getIdentifierMethod,
		Method setIdentifierMethod,
		CompositeType componentIdType) throws HibernateException {
	this.entityName = entityName;
	this.persistentClass = persistentClass;
	this.interfaces = toArray( interfaces );
	this.getIdentifierMethod = getIdentifierMethod;
	this.setIdentifierMethod = setIdentifierMethod;
	this.componentIdType = componentIdType;
	this.overridesEquals = ReflectHelper.overridesEquals( persistentClass );

	this.proxyClass = byteBuddyProxyHelper.buildProxy( persistentClass, this.interfaces );
}
 
Example 8
Source Project: lams   Source File: OracleTypesHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Class locateOracleTypesClass() {
	try {
		return ReflectHelper.classForName( ORACLE_TYPES_CLASS_NAME );
	}
	catch (ClassNotFoundException e) {
		try {
			return ReflectHelper.classForName( DEPRECATED_ORACLE_TYPES_CLASS_NAME );
		}
		catch (ClassNotFoundException e2) {
			throw new HibernateException(
					String.format(
							"Unable to locate OracleTypes class using either known FQN [%s, %s]",
							ORACLE_TYPES_CLASS_NAME,
							DEPRECATED_ORACLE_TYPES_CLASS_NAME
					),
					e
			);
		}
	}
}
 
Example 9
Source Project: lams   Source File: LiteralProcessor.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void lookupConstant(DotNode node) throws SemanticException {
	String text = ASTUtil.getPathText( node );
	Queryable persister = walker.getSessionFactoryHelper().findQueryableUsingImports( text );
	if ( persister != null ) {
		// the name of an entity class
		final String discrim = persister.getDiscriminatorSQLValue();
		node.setDataType( persister.getDiscriminatorType() );
		if ( InFragment.NULL.equals( discrim ) || InFragment.NOT_NULL.equals( discrim ) ) {
			throw new InvalidPathException(
					"subclass test not allowed for null or not null discriminator: '" + text + "'"
			);
		}
		// the class discriminator value
		setSQLValue( node, text, discrim );
	}
	else {
		Object value = ReflectHelper.getConstantValue( text, walker.getSessionFactoryHelper().getFactory() );
		if ( value == null ) {
			throw new InvalidPathException( "Invalid path: '" + text + "'" );
		}
		setConstantValue( node, text, value );
	}
}
 
Example 10
Source Project: lams   Source File: TypeFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
public CollectionType customCollection(
		String typeName,
		Properties typeParameters,
		String role,
		String propertyRef) {
	Class typeClass;
	try {
		typeClass = ReflectHelper.classForName( typeName );
	}
	catch (ClassNotFoundException cnfe) {
		throw new MappingException( "user collection type class not found: " + typeName, cnfe );
	}
	CustomCollectionType result = new CustomCollectionType( typeScope, typeClass, role, propertyRef );
	if ( typeParameters != null ) {
		injectParameters( result.getUserType(), typeParameters );
	}
	return result;
}
 
Example 11
Source Project: lams   Source File: SerializableToBlobType.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void setParameterValues(Properties parameters) {
	ParameterType reader = (ParameterType) parameters.get( PARAMETER_TYPE );
	if ( reader != null ) {
		setJavaTypeDescriptor( new SerializableTypeDescriptor<T>( reader.getReturnedClass() ) );
	}
	else {
		String className = parameters.getProperty( CLASS_NAME );
		if ( className == null ) {
			throw new MappingException( "No class name defined for type: " + SerializableToBlobType.class.getName() );
		}
		try {
			setJavaTypeDescriptor( new SerializableTypeDescriptor<T>( ReflectHelper.classForName( className ) ) );
		}
		catch ( ClassNotFoundException e ) {
			throw new MappingException( "Unable to load class from " + CLASS_NAME + " parameter", e );
		}
	}
}
 
Example 12
Source Project: quarkus   Source File: ProxyDefinitions.java    License: Apache License 2.0 5 votes vote down vote up
public static ProxyDefinitions createFromMetadata(Metadata storeableMetadata, PreGeneratedProxies preGeneratedProxies) {
    //Check upfront for any need across all metadata: would be nice to avoid initializing the Bytecode provider.
    LazyBytecode lazyBytecode = new LazyBytecode();
    if (needAnyProxyDefinitions(storeableMetadata)) {
        final HashMap<Class<?>, ProxyClassDetailsHolder> proxyDefinitionMap = new HashMap<>();
        try {
            for (PersistentClass persistentClass : storeableMetadata.getEntityBindings()) {
                if (needsProxyGeneration(persistentClass)) {
                    final Class mappedClass = persistentClass.getMappedClass();
                    final Class proxyClassDefinition = generateProxyClass(persistentClass, lazyBytecode,
                            preGeneratedProxies);
                    if (proxyClassDefinition == null) {
                        continue;
                    }
                    final boolean overridesEquals = ReflectHelper.overridesEquals(mappedClass);
                    try {
                        proxyDefinitionMap.put(mappedClass,
                                new ProxyClassDetailsHolder(overridesEquals, proxyClassDefinition.getConstructor()));
                    } catch (NoSuchMethodException e) {
                        throw new HibernateException(
                                "Failed to generate Enhanced Proxy: default constructor is missing for entity '"
                                        + mappedClass.getName() + "'. Please add a default constructor explicitly.");
                    }
                }
            }
        } finally {
            lazyBytecode.close();
        }
        return new ProxyDefinitions(proxyDefinitionMap);
    } else {
        return new ProxyDefinitions(Collections.emptyMap());
    }
}
 
Example 13
Source Project: lams   Source File: ToOne.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setTypeUsingReflection(String className, String propertyName) throws MappingException {
	if (referencedEntityName == null) {
		final ClassLoaderService cls = getMetadata().getMetadataBuildingOptions()
				.getServiceRegistry()
				.getService( ClassLoaderService.class );
		referencedEntityName = ReflectHelper.reflectedPropertyClass( className, propertyName, cls ).getName();
	}
}
 
Example 14
Source Project: lams   Source File: SimpleValue.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setTypeUsingReflection(String className, String propertyName) throws MappingException {
	// NOTE : this is called as the last piece in setting SimpleValue type information, and implementations
	// rely on that fact, using it as a signal that all information it is going to get is defined at this point...

	if ( typeName != null ) {
		// assume either (a) explicit type was specified or (b) determine was already performed
		return;
	}

	if ( type != null ) {
		return;
	}

	if ( attributeConverterDescriptor == null ) {
		// this is here to work like legacy.  This should change when we integrate with metamodel to
		// look for SqlTypeDescriptor and JavaTypeDescriptor individually and create the BasicType (well, really
		// keep a registry of [SqlTypeDescriptor,JavaTypeDescriptor] -> BasicType...)
		if ( className == null ) {
			throw new MappingException( "Attribute types for a dynamic entity must be explicitly specified: " + propertyName );
		}
		typeName = ReflectHelper.reflectedPropertyClass(
				className,
				propertyName,
				getMetadata()
						.getMetadataBuildingOptions()
						.getServiceRegistry()
						.getService( ClassLoaderService.class )
		).getName();
		// todo : to fully support isNationalized here we need do the process hinted at above
		// 		essentially, much of the logic from #buildAttributeConverterTypeAdapter wrt resolving
		//		a (1) SqlTypeDescriptor, a (2) JavaTypeDescriptor and dynamically building a BasicType
		// 		combining them.
		return;
	}

	// we had an AttributeConverter...
	type = buildAttributeConverterTypeAdapter();
}
 
Example 15
Source Project: lams   Source File: SetterMethodImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Method resolveMethod() {
	try {
		final Method method = declaringClass.getDeclaredMethod( methodName, argumentType );
		ReflectHelper.ensureAccessibility( method );
		return method;
	}
	catch (NoSuchMethodException e) {
		throw new PropertyAccessSerializationException(
				"Unable to resolve setter method on deserialization : " + declaringClass.getName() + "#"
						+ methodName + "(" + argumentType.getName() + ")"
		);
	}
}
 
Example 16
Source Project: lams   Source File: GetterFieldImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public GetterFieldImpl(Class containerClass, String propertyName, Field field) {
	this.containerClass = containerClass;
	this.propertyName = propertyName;
	this.field = field;

	this.getterMethod = ReflectHelper.findGetterMethodForFieldAccess( field, propertyName );
}
 
Example 17
Source Project: lams   Source File: GetterMethodImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Method resolveMethod() {
	try {
		final Method method = declaringClass.getDeclaredMethod( methodName );
		ReflectHelper.ensureAccessibility( method );
		return method;
	}
	catch (NoSuchMethodException e) {
		throw new PropertyAccessSerializationException(
				"Unable to resolve getter method on deserialization : " + declaringClass.getName() + "#" + methodName
		);
	}
}
 
Example 18
Source Project: lams   Source File: PropertyAccessMixedImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected static Field fieldOrNull(Class containerJavaType, String propertyName) {
	try {
		return ReflectHelper.findField( containerJavaType, propertyName );
	}
	catch (PropertyNotFoundException e) {
		return null;
	}
}
 
Example 19
Source Project: lams   Source File: PropertyAccessFieldImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public PropertyAccessFieldImpl(
		PropertyAccessStrategyFieldImpl strategy,
		Class containerJavaType,
		final String propertyName) {
	this.strategy = strategy;

	final Field field = ReflectHelper.findField( containerJavaType, propertyName );
	this.getter = new GetterFieldImpl( containerJavaType, propertyName, field );
	this.setter = new SetterFieldImpl( containerJavaType, propertyName, field );
}
 
Example 20
Source Project: lams   Source File: AbstractFieldSerialForm.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected Field resolveField() {
	try {
		final Field field = declaringClass.getDeclaredField( fieldName );
		ReflectHelper.ensureAccessibility( field );
		return field;
	}
	catch (NoSuchFieldException e) {
		throw new PropertyAccessSerializationException(
				"Unable to resolve field on deserialization : " + declaringClass.getName() + "#" + fieldName
		);
	}
}
 
Example 21
Source Project: lams   Source File: PropertyAccessBasicImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public PropertyAccessBasicImpl(
		PropertyAccessStrategyBasicImpl strategy,
		Class containerJavaType,
		final String propertyName) {
	this.strategy = strategy;

	final Method getterMethod = ReflectHelper.findGetterMethod( containerJavaType, propertyName );
	this.getter = new GetterMethodImpl( containerJavaType, propertyName, getterMethod );

	final Method setterMethod = ReflectHelper.findSetterMethod( containerJavaType, propertyName, getterMethod.getReturnType() );
	this.setter = new SetterMethodImpl( containerJavaType, propertyName, setterMethod );
}
 
Example 22
Source Project: lams   Source File: EntityTuplizerFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct an instance of the given tuplizer class.
 *
 * @param tuplizerClassName The name of the tuplizer class to instantiate
 * @param metamodel The metadata for the entity.
 * @param persistentClass The mapping info for the entity.
 *
 * @return The instantiated tuplizer
 *
 * @throws HibernateException If class name cannot be resolved to a class reference, or if the
 * {@link Constructor#newInstance} call fails.
 */
@SuppressWarnings({ "unchecked" })
public EntityTuplizer constructTuplizer(
		String tuplizerClassName,
		EntityMetamodel metamodel,
		PersistentClass persistentClass) {
	try {
		Class<? extends EntityTuplizer> tuplizerClass = ReflectHelper.classForName( tuplizerClassName );
		return constructTuplizer( tuplizerClass, metamodel, persistentClass );
	}
	catch ( ClassNotFoundException e ) {
		throw new HibernateException( "Could not locate specified tuplizer class [" + tuplizerClassName + "]" );
	}
}
 
Example 23
Source Project: lams   Source File: PojoInstantiator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public PojoInstantiator(Class componentClass, ReflectionOptimizer.InstantiationOptimizer optimizer) {
	this.mappedClass = componentClass;
	this.isAbstract = ReflectHelper.isAbstractClass( mappedClass );
	this.optimizer = optimizer;

	this.embeddedIdentifier = false;

	try {
		constructor = ReflectHelper.getDefaultConstructor(mappedClass);
	}
	catch ( PropertyNotFoundException pnfe ) {
		LOG.noDefaultConstructor(mappedClass.getName());
		constructor = null;
	}
}
 
Example 24
Source Project: lams   Source File: PojoComponentTuplizer.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected Instantiator buildInstantiator(Component component) {
	if ( component.isEmbedded() && ReflectHelper.isAbstractClass( this.componentClass ) ) {
		return new ProxiedInstantiator( this.componentClass );
	}
	if ( optimizer == null ) {
		return new PojoInstantiator( this.componentClass, null );
	}
	else {
		return new PojoInstantiator( this.componentClass, optimizer.getInstantiationOptimizer() );
	}
}
 
Example 25
Source Project: lams   Source File: PropertyFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Constructor getConstructor(PersistentClass persistentClass) {
	if ( persistentClass == null || !persistentClass.hasPojoRepresentation() ) {
		return null;
	}

	try {
		return ReflectHelper.getDefaultConstructor( persistentClass.getMappedClass() );
	}
	catch (Throwable t) {
		return null;
	}
}
 
Example 26
Source Project: lams   Source File: PersistenceUtilHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public FieldAttributeAccess(Field field) {
	this.name = field.getName();
	try {
		ReflectHelper.ensureAccessibility( field );
	}
	catch (Exception e) {
		this.field = null;
		return;
	}
	this.field = field;
}
 
Example 27
Source Project: lams   Source File: PersistenceUtilHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public MethodAttributeAccess(String attributeName, Method method) {
	this.name = attributeName;
	try {
		ReflectHelper.ensureAccessibility( method );
	}
	catch (Exception e) {
		this.method = null;
		return;
	}
	this.method = method;
}
 
Example 28
Source Project: lams   Source File: ByteBuddyProxyHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public HibernateProxy deserializeProxy(SerializableProxy serializableProxy) {
	final ByteBuddyInterceptor interceptor = new ByteBuddyInterceptor(
			serializableProxy.getEntityName(),
			serializableProxy.getPersistentClass(),
			serializableProxy.getInterfaces(),
			serializableProxy.getId(),
			resolveIdGetterMethod( serializableProxy ),
			resolveIdSetterMethod( serializableProxy ),
			serializableProxy.getComponentIdType(),
			null,
			ReflectHelper.overridesEquals( serializableProxy.getPersistentClass() )
	);

	// note: interface is assumed to already contain HibernateProxy.class
	try {
		final Class proxyClass = buildProxy(
				serializableProxy.getPersistentClass(),
				serializableProxy.getInterfaces()
		);
		final HibernateProxy proxy = (HibernateProxy) proxyClass.newInstance();
		( (ProxyConfiguration) proxy ).$$_hibernate_set_interceptor( interceptor );
		return proxy;
	}
	catch (Throwable t) {
		final String message = LOG.bytecodeEnhancementFailed( serializableProxy.getEntityName() );
		LOG.error( message, t );
		throw new HibernateException( message, t );
	}
}
 
Example 29
Source Project: lams   Source File: ByteBuddyInterceptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object intercept(Object proxy, Method thisMethod, Object[] args) throws Throwable {
	Object result = this.invoke( thisMethod, args, proxy );
	if ( result == INVOKE_IMPLEMENTATION ) {
		Object target = getImplementation();
		final Object returnValue;
		try {
			if ( ReflectHelper.isPublic( persistentClass, thisMethod ) ) {
				if ( !thisMethod.getDeclaringClass().isInstance( target ) ) {
					throw new ClassCastException(
							target.getClass().getName()
									+ " incompatible with "
									+ thisMethod.getDeclaringClass().getName()
					);
				}
				returnValue = thisMethod.invoke( target, args );
			}
			else {
				thisMethod.setAccessible( true );
				returnValue = thisMethod.invoke( target, args );
			}

			if ( returnValue == target ) {
				if ( returnValue.getClass().isInstance( proxy ) ) {
					return proxy;
				}
				else {
					LOG.narrowingProxy( returnValue.getClass() );
				}
			}
			return returnValue;
		}
		catch (InvocationTargetException ite) {
			throw ite.getTargetException();
		}
	}
	else {
		return result;
	}
}
 
Example 30
private static SQLExceptionConverter constructConverter(String converterClassName, ViolatedConstraintNameExtracter violatedConstraintNameExtracter) {
	try {
		LOG.tracev( "Attempting to construct instance of specified SQLExceptionConverter [{0}]", converterClassName );
		final Class converterClass = ReflectHelper.classForName( converterClassName );

		// First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param...
		final Constructor[] ctors = converterClass.getDeclaredConstructors();
		for ( Constructor ctor : ctors ) {
			if ( ctor.getParameterTypes() != null && ctor.getParameterCount() == 1 ) {
				if ( ViolatedConstraintNameExtracter.class.isAssignableFrom( ctor.getParameterTypes()[0] ) ) {
					try {
						return (SQLExceptionConverter) ctor.newInstance( violatedConstraintNameExtracter );
					}
					catch (Throwable ignore) {
						// eat it and try next
					}
				}
			}
		}

		// Otherwise, try to use the no-arg constructor
		return (SQLExceptionConverter) converterClass.newInstance();

	}
	catch (Throwable t) {
		LOG.unableToConstructSqlExceptionConverter( t );
	}

	return null;
}