org.hibernate.internal.util.ReflectHelper Java Examples

The following examples show how to use org.hibernate.internal.util.ReflectHelper. 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: RootClass.java    From lams with 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 File: AbstractAttribute.java    From lams with 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 File: ComponentTuplizerFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #4
Source File: SerializableToBlobType.java    From lams with 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 #5
Source File: TypeFactory.java    From lams with 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 #6
Source File: LiteralProcessor.java    From lams with 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 #7
Source File: JavassistProxyFactory.java    From lams with 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 #8
Source File: ByteBuddyProxyFactory.java    From lams with 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 #9
Source File: OracleTypesHelper.java    From lams with 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 #10
Source File: PojoInstantiator.java    From lams with 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 #11
Source File: EntityTuplizerFactory.java    From lams with 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 #12
Source File: PropertyFactory.java    From lams with 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 #13
Source File: ToOne.java    From lams with 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 File: PersistenceUtilHelper.java    From lams with 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 #15
Source File: PersistenceUtilHelper.java    From lams with 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 #16
Source File: ByteBuddyProxyHelper.java    From lams with 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 #17
Source File: ByteBuddyInterceptor.java    From lams with 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 #18
Source File: SQLExceptionConverterFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #19
Source File: DerbyDialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void determineDriverVersion() {
	try {
		// locate the derby sysinfo class and query its version info
		final Class sysinfoClass = ReflectHelper.classForName( "org.apache.derby.tools.sysinfo", this.getClass() );
		final Method majorVersionGetter = sysinfoClass.getMethod( "getMajorVersion", ReflectHelper.NO_PARAM_SIGNATURE );
		final Method minorVersionGetter = sysinfoClass.getMethod( "getMinorVersion", ReflectHelper.NO_PARAM_SIGNATURE );
		driverVersionMajor = (Integer) majorVersionGetter.invoke( null, ReflectHelper.NO_PARAMS );
		driverVersionMinor = (Integer) minorVersionGetter.invoke( null, ReflectHelper.NO_PARAMS );
	}
	catch ( Exception e ) {
		LOG.unableToLoadDerbyDriver( e.getMessage() );
		driverVersionMajor = -1;
		driverVersionMinor = -1;
	}
}
 
Example #20
Source File: Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static Dialect instantiateDialect(String dialectName) throws HibernateException {
	if ( dialectName == null ) {
		throw new HibernateException( "The dialect was not set. Set the property hibernate.dialect." );
	}
	try {
		return (Dialect) ReflectHelper.classForName( dialectName ).newInstance();
	}
	catch ( ClassNotFoundException cnfe ) {
		throw new HibernateException( "Dialect class not found: " + dialectName );
	}
	catch ( Exception e ) {
		throw new HibernateException( "Could not instantiate given dialect class: " + dialectName, e );
	}
}
 
Example #21
Source File: JavaConstantNode.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setText(String s) {
	// for some reason the antlr.CommonAST initialization routines force
	// this method to get called twice.  The first time with an empty string
	if ( StringHelper.isNotEmpty( s ) ) {
		constantExpression = s;
		constantValue = ReflectHelper.getConstantValue( s, factory );
		heuristicType = factory.getTypeResolver().heuristicType( constantValue.getClass().getName() );
		super.setText( s );
	}
}
 
Example #22
Source File: QueryTranslatorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void handleDotStructure(AST dotStructureRoot) {
	final String expression = ASTUtil.getPathText( dotStructureRoot );
	final Object constant = ReflectHelper.getConstantValue( expression, factory );
	if ( constant != null ) {
		dotStructureRoot.setFirstChild( null );
		dotStructureRoot.setType( HqlTokenTypes.JAVA_CONSTANT );
		dotStructureRoot.setText( expression );
	}
}
 
Example #23
Source File: ClassTypeDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public Class fromString(String string) {
	if ( string == null ) {
		return null;
	}

	try {
		return ReflectHelper.classForName( string );
	}
	catch ( ClassNotFoundException e ) {
		throw new HibernateException( "Unable to locate named class " + string );
	}
}
 
Example #24
Source File: EntityType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Class determineAssociatedEntityClass() {
	final String entityName = getAssociatedEntityName();
	try {
		return ReflectHelper.classForName( entityName );
	}
	catch (ClassNotFoundException cnfe) {
		return this.scope.getTypeConfiguration().getSessionFactory().getMetamodel().entityPersister( entityName ).
				getEntityTuplizer().getMappedClass();
	}
}
 
Example #25
Source File: JSONType.java    From spring-data-jpa-extra with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void setParameterValues(Properties parameters) {
    try {
        Class eClass = ReflectHelper.classForName(parameters.getProperty(DynamicParameterizedType.ENTITY));
        Field field = ReflectionUtils.findField(eClass, parameters.getProperty(DynamicParameterizedType.PROPERTY));
        Type fieldType = field.getGenericType();
        if (fieldType instanceof Class || fieldType instanceof ParameterizedType) {
            type = fieldType;
        }
        parseSqlType(field.getAnnotations());
        return;
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }
    final DynamicParameterizedType.ParameterType reader = (DynamicParameterizedType.ParameterType) parameters.get(
            DynamicParameterizedType.PARAMETER_TYPE);
    if (reader != null) {
        type = reader.getReturnedClass();
        parseSqlType(reader.getAnnotationsMethod());
    } else {
        try {
            type = ReflectHelper.classForName((String) parameters.get(CLASS_NAME));
        } catch (ClassNotFoundException exception) {
            throw new HibernateException("class not found", exception);
        }
    }
}
 
Example #26
Source File: AbstractFieldSerialForm.java    From lams with 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 #27
Source File: ProxyDefinitions.java    From quarkus with 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 #28
Source File: SimpleValue.java    From lams with 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 #29
Source File: SetterMethodImpl.java    From lams with 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 #30
Source File: GetterFieldImpl.java    From lams with 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 );
}