break hibernate-commons-annotations back out into separate project

git-svn-id: https://svn.jboss.org/repos/hibernate/core/trunk@17310 1b8cb986-b30d-0410-93ca-fae66ebed9b2
This commit is contained in:
Steve Ebersole 2009-08-15 17:25:34 +00:00
parent c317edd28f
commit 59ec451c28
75 changed files with 0 additions and 5154 deletions

View File

@ -1,54 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* Indicates failure of an assertion: a possible bug in Hibernate.
* <p/>
* TODO : Copy from Hibernate Core, do some mutualization here?
*
* @author Gavin King
* @auhor Emmanuel Bernard
*/
public class AssertionFailure extends RuntimeException {
private static final Logger log = LoggerFactory.getLogger(AssertionFailure.class);
private static final String MESSAGE = "an assertion failure occured (this may indicate a bug in Hibernate)";
public AssertionFailure(String s) {
super(s);
log.error(MESSAGE, this);
}
public AssertionFailure(String s, Throwable t) {
super(s, t);
log.error(MESSAGE, t);
}
}

View File

@ -1,42 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Emmanuel Bernard
*/
public class Version {
public static final String VERSION = "3.2.0-SNAPSHOT";
private static Logger log = LoggerFactory.getLogger( Version.class );
static {
log.info( "Hibernate Commons Annotations {}", VERSION );
}
public static void touch() {
}
}

View File

@ -1,70 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.annotationfactory;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
/**
* Encapsulates the data you need to create an annotation. In
* particular, it stores the type of an <code>Annotation</code> instance
* and the values of its elements.
* The "elements" we're talking about are the annotation attributes,
* not its targets (the term "element" is used ambiguously
* in Java's annotations documentation).
*
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
public class AnnotationDescriptor {
private final Class<? extends Annotation> type;
private final Map<String, Object> elements = new HashMap<String, Object>();
public AnnotationDescriptor(Class<? extends Annotation> annotationType) {
type = annotationType;
}
public void setValue(String elementName, Object value) {
elements.put( elementName, value );
}
public Object valueOf(String elementName) {
return elements.get( elementName );
}
public boolean containsElement(String elementName) {
return elements.containsKey( elementName );
}
public int numberOfElements() {
return elements.size();
}
public Class<? extends Annotation> type() {
return type;
}
}

View File

@ -1,65 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.annotationfactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
/**
* Creates live annotations (actually <code>AnnotationProxies</code>) from <code>AnnotationDescriptors</code>.
*
* @author Paolo Perrotta
* @author Davide Marchignoli
* @see AnnotationProxy
*/
public class AnnotationFactory {
@SuppressWarnings("unchecked")
public static <T extends Annotation> T create(AnnotationDescriptor descriptor) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//TODO round 34ms to generate the proxy, hug! is Javassist Faster?
//TODO prebuild the javax.persistence and org.hibernate.annotations classes?
Class<T> proxyClass = (Class<T>) Proxy.getProxyClass( classLoader, descriptor.type() );
InvocationHandler handler = new AnnotationProxy( descriptor );
try {
return getProxyInstance( proxyClass, handler );
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException( e );
}
}
private static <T extends Annotation> T getProxyInstance(Class<T> proxyClass, InvocationHandler handler) throws
SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
Constructor<T> constructor = proxyClass.getConstructor( new Class[]{InvocationHandler.class} );
return constructor.newInstance( new Object[]{handler} );
}
}

View File

@ -1,134 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.annotationfactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* A concrete implementation of <code>Annotation</code> that pretends it is a
* "real" source code annotation. It's also an <code>InvocationHandler</code>.
* <p/>
* When you create an <code>AnnotationProxy</code>, you must initialize it
* with an <code>AnnotationDescriptor</code>.
* The adapter checks that the provided elements are the same elements defined
* in the annotation interface. However, it does <i>not</i> check that their
* values are the right type. If you omit an element, the adapter will use the
* default value for that element from the annotation interface, if it exists.
* If no default exists, it will throw an exception.
* <p/>
* Warning: this class does not implement <code>hashCode()</code> and
* <code>equals()</code> - it just uses the ones it inherits from <code>Object</code>.
* This means that an <code>AnnotationProxy</code> does <i>not</i> follow the
* recommendations of the <code>Annotation</code> javadoc about these two
* methods. That's why you should never mix <code>AnnotationProxies</code>
* with "real" annotations. For example, don't put them into the same
* <code>Collection</code>.
*
* @author Paolo Perrotta
* @author Davide Marchignoli
* @see java.lang.annotation.Annotation
*/
public class AnnotationProxy implements Annotation, InvocationHandler {
private final Class<? extends Annotation> annotationType;
//FIXME it's probably better to use String as a key rather than Method
// to speed up and avoid any fancy permsize/GC issue
// I'd better check the litterature on the subject
private final Map<Method, Object> values;
public AnnotationProxy(AnnotationDescriptor descriptor) {
this.annotationType = descriptor.type();
values = getAnnotationValues( descriptor );
}
private Map<Method, Object> getAnnotationValues(AnnotationDescriptor descriptor) {
Map<Method, Object> result = new HashMap<Method, Object>();
int processedValuesFromDescriptor = 0;
for ( Method m : annotationType.getDeclaredMethods() ) {
if ( descriptor.containsElement( m.getName() ) ) {
result.put( m, descriptor.valueOf( m.getName() ) );
processedValuesFromDescriptor++;
}
else if ( m.getDefaultValue() != null ) {
result.put( m, m.getDefaultValue() );
}
else {
throw new IllegalArgumentException( "No value provided for " + m.getName() );
}
}
if ( processedValuesFromDescriptor != descriptor.numberOfElements() ) {
throw new RuntimeException( "Trying to instanciate " + annotationType + " with unknown elements" );
}
return result;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ( values.containsKey( method ) ) {
return values.get( method );
}
return method.invoke( this, args );
}
public Class<? extends Annotation> annotationType() {
return annotationType;
}
public String toString() {
StringBuilder result = new StringBuilder();
result.append( '@' ).append( annotationType().getName() ).append( '(' );
for ( Method m : getRegisteredMethodsInAlphabeticalOrder() ) {
result.append( m.getName() ).append( '=' ).append( values.get( m ) ).append( ", " );
}
// remove last separator:
if ( values.size() > 0 ) {
result.delete( result.length() - 2, result.length() );
result.append( ")" );
}
else {
result.delete( result.length() - 1, result.length() );
}
return result.toString();
}
private SortedSet<Method> getRegisteredMethodsInAlphabeticalOrder() {
SortedSet<Method> result = new TreeSet<Method>(
new Comparator<Method>() {
public int compare(Method o1, Method o2) {
return o1.getName().compareTo( o2.getName() );
}
}
);
//List<Method> result = new LinkedList<Method>();
result.addAll( values.keySet() );
return result;
}
}

View File

@ -1,38 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
import java.lang.annotation.Annotation;
/**
* @author Paolo Perrotta
*/
public interface AnnotationReader {
public <T extends Annotation> T getAnnotation(Class<T> annotationType);
public <T extends Annotation> boolean isAnnotationPresent(Class<T> annotationType);
public Annotation[] getAnnotations();
}

View File

@ -1,35 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
/**
* Filter properties
*
* @author Emmanuel Bernard
*/
public interface Filter {
boolean returnStatic();
boolean returnTransient();
}

View File

@ -1,22 +0,0 @@
package org.hibernate.annotations.common.reflection;
import java.util.Map;
import java.lang.reflect.AnnotatedElement;
/**
* Provides metadata
*
* @author Emmanuel Bernard
*/
public interface MetadataProvider {
/**
* provide default metadata
*/
Map<Object, Object> getDefaults();
/**
* provide metadata for a gien annotated element
*/
AnnotationReader getAnnotationReader(AnnotatedElement annotatedElement);
}

View File

@ -1,15 +0,0 @@
package org.hibernate.annotations.common.reflection;
/**
* Offers access to and the ability to change the metadata provider
*
* @author Emmanuel Bernard
*/
public interface MetadataProviderInjector {
MetadataProvider getMetadataProvider();
/**
* Defines the metadata provider for a given Reflection Manager
*/
void setMetadataProvider(MetadataProvider metadataProvider);
}

View File

@ -1,53 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.Map;
/**
* The entry point to the reflection layer (a.k.a. the X* layer).
*
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
public interface ReflectionManager {
public <T> XClass toXClass(Class<T> clazz);
public Class toClass(XClass xClazz);
public Method toMethod(XMethod method);
public <T> XClass classForName(String name, Class<T> caller) throws ClassNotFoundException;
public XPackage packageForName(String packageName) throws ClassNotFoundException;
public <T> boolean equals(XClass class1, Class<T> class2);
public AnnotationReader buildAnnotationReader(AnnotatedElement annotatedElement);
public Map getDefaults();
}

View File

@ -1,59 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import org.hibernate.annotations.common.reflection.java.generics.TypeUtils;
/**
* @author Paolo Perrotta
*/
public class ReflectionUtil {
public static boolean isProperty(Method m, Type boundType, Filter filter) {
return ReflectionUtil.isPropertyType( boundType )
&& !m.isSynthetic()
&& !m.isBridge()
&& ( filter.returnStatic() || !Modifier.isStatic( m.getModifiers() ) )
&& m.getParameterTypes().length == 0
&& ( m.getName().startsWith( "get" ) || m.getName().startsWith( "is" ) );
// TODO should we use stronger checking on the naming of getters/setters, or just leave this to the validator?
}
public static boolean isProperty(Field f, Type boundType, Filter filter) {
return ( filter.returnStatic() || ! Modifier.isStatic( f.getModifiers() ) )
&& ( filter.returnTransient() || ! Modifier.isTransient( f.getModifiers() ) )
&& !f.isSynthetic()
&& ReflectionUtil.isPropertyType( boundType );
}
private static boolean isPropertyType(Type type) {
// return TypeUtils.isArray( type ) || TypeUtils.isCollection( type ) || ( TypeUtils.isBase( type ) && ! TypeUtils.isVoid( type ) );
return !TypeUtils.isVoid( type );
}
}

View File

@ -1,45 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
import java.lang.annotation.Annotation;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
public interface XAnnotatedElement {
<T extends Annotation> T getAnnotation(Class<T> annotationType);
<T extends Annotation> boolean isAnnotationPresent(Class<T> annotationType);
Annotation[] getAnnotations();
/**
* Returns true if the underlying artefact
* is the same
*/
boolean equals(Object x);
}

View File

@ -1,81 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
import java.util.List;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
public interface XClass extends XAnnotatedElement {
public static final String ACCESS_PROPERTY = "property";
public static final String ACCESS_FIELD = "field";
static final Filter DEFAULT_FILTER = new Filter() {
public boolean returnStatic() {
return false;
}
public boolean returnTransient() {
return false;
}
};
String getName();
/**
* @see Class#getSuperclass()
*/
XClass getSuperclass();
/**
* @see Class#getInterfaces()
*/
XClass[] getInterfaces();
/**
* see Class#isInterface()
*/
boolean isInterface();
boolean isAbstract();
boolean isPrimitive();
boolean isEnum();
boolean isAssignableFrom(XClass c);
List<XProperty> getDeclaredProperties(String accessType);
List<XProperty> getDeclaredProperties(String accessType, Filter filter);
/**
* Returns the <tt>Method</tt>s defined by this class.
*/
List<XMethod> getDeclaredMethods();
}

View File

@ -1,78 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
import java.util.Collection;
/**
* @author Emmanuel Bernard
*/
public abstract interface XMember extends XAnnotatedElement {
String getName();
boolean isCollection();
boolean isArray();
/**
* The collection class for collections, null for others.
*/
Class<? extends Collection> getCollectionClass();
// TODO We should probably try to reduce the following three methods to two.
// the last one is particularly offensive
/**
* This property's XClass.
*/
XClass getType();
/**
* This property's type for simple properties, the type of its elements for arrays and collections.
*/
XClass getElementClass();
/**
* The type of this property's elements for arrays, the type of the property itself for everything else.
*/
XClass getClassOrElementClass();
/**
* The type of this map's key, or null for anything that is not a map.
*/
XClass getMapKey();
/**
* Same modifiers as java.lang.Member#getModifiers()
*/
int getModifiers();
//this breaks the Java reflect hierarchy, since accessible belongs to AccessibleObject
void setAccessible(boolean accessible);
public Object invoke(Object target, Object... parameters);
boolean isTypeResolved();
}

View File

@ -1,36 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
/**
* Represent an invokable method
* <p/>
* The underlying layer does not guaranty that xProperty == xMethod
* if the underlying artefact is the same
* However xProperty.equals(xMethod) is supposed to return true
*
* @author Emmanuel Bernard
*/
public interface XMethod extends XMember {
}

View File

@ -1,33 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
public interface XPackage extends XAnnotatedElement {
String getName();
}

View File

@ -1,44 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection;
/**
* A member which actually is a property (as per the JavaBean spec)
* Note that the same underlying artefact can be represented as both
* XProperty and XMethod
* The underlying layer does not guaranty that xProperty == xMethod
* if the underlying artefact is the same
* However xProperty.equals(xMethod) is supposed to return true
*
* @author Paolo Perrotta
* @author Davide Marchignoli
* @author Emmanuel Bernard
*/
public interface XProperty extends XMember {
/**
* Unqualify the getter name
*/
String getName();
}

View File

@ -1,56 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import org.hibernate.annotations.common.reflection.AnnotationReader;
/**
* Reads standard Java annotations.
*
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
class JavaAnnotationReader implements AnnotationReader {
protected final AnnotatedElement element;
public JavaAnnotationReader(AnnotatedElement el) {
this.element = el;
}
public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
return element.getAnnotation( annotationType );
}
public <T extends Annotation> boolean isAnnotationPresent(Class<T> annotationType) {
return element.isAnnotationPresent( annotationType );
}
public Annotation[] getAnnotations() {
return element.getAnnotations();
}
}

View File

@ -1,22 +0,0 @@
package org.hibernate.annotations.common.reflection.java;
import java.util.Map;
import java.util.Collections;
import java.lang.reflect.AnnotatedElement;
import org.hibernate.annotations.common.reflection.MetadataProvider;
import org.hibernate.annotations.common.reflection.AnnotationReader;
/**
* @author Emmanuel Bernard
*/
public class JavaMetadataProvider implements MetadataProvider {
public Map<Object, Object> getDefaults() {
return Collections.emptyMap();
}
public AnnotationReader getAnnotationReader(AnnotatedElement annotatedElement) {
return new JavaAnnotationReader(annotatedElement);
}
}

View File

@ -1,229 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.annotations.common.reflection.AnnotationReader;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XMethod;
import org.hibernate.annotations.common.reflection.XPackage;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.annotations.common.reflection.MetadataProviderInjector;
import org.hibernate.annotations.common.reflection.MetadataProvider;
import org.hibernate.annotations.common.reflection.java.generics.IdentityTypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironmentFactory;
import org.hibernate.annotations.common.reflection.java.generics.TypeSwitch;
import org.hibernate.annotations.common.reflection.java.generics.TypeUtils;
import org.hibernate.annotations.common.Version;
import org.hibernate.annotations.common.util.ReflectHelper;
/**
* The factory for all the objects in this package.
*
* @author Paolo Perrotta
* @author Davide Marchignoli
* @author Emmanuel Bernard
*/
public class JavaReflectionManager implements ReflectionManager, MetadataProviderInjector {
private MetadataProvider metadataProvider;
public MetadataProvider getMetadataProvider() {
if (metadataProvider == null) {
setMetadataProvider( new JavaMetadataProvider() );
}
return metadataProvider;
}
public void setMetadataProvider(MetadataProvider metadataProvider) {
this.metadataProvider = metadataProvider;
}
static {
Version.touch();
}
private static class TypeKey extends Pair<Type, TypeEnvironment> {
TypeKey(Type t, TypeEnvironment context) {
super( t, context );
}
}
private static class MemberKey extends Pair<Member, TypeEnvironment> {
MemberKey(Member member, TypeEnvironment context) {
super( member, context );
}
}
private final Map<TypeKey, JavaXClass> xClasses = new HashMap<TypeKey, JavaXClass>();
private final Map<Package, JavaXPackage> packagesToXPackages = new HashMap<Package, JavaXPackage>();
private final Map<MemberKey, JavaXProperty> xProperties = new HashMap<MemberKey, JavaXProperty>();
private final Map<MemberKey, JavaXMethod> xMethods = new HashMap<MemberKey, JavaXMethod>();
private final TypeEnvironmentFactory typeEnvs = new TypeEnvironmentFactory();
public XClass toXClass(Class clazz) {
return toXClass( clazz, IdentityTypeEnvironment.INSTANCE );
}
public Class toClass(XClass xClazz) {
if ( ! ( xClazz instanceof JavaXClass ) ) {
throw new IllegalArgumentException( "XClass not coming from this ReflectionManager implementation" );
}
return (Class) ( (JavaXClass) xClazz ).toAnnotatedElement();
}
public Method toMethod(XMethod xMethod) {
if ( ! ( xMethod instanceof JavaXMethod ) ) {
throw new IllegalArgumentException( "XMethod not coming from this ReflectionManager implementation" );
}
return (Method) ( (JavaXAnnotatedElement) xMethod ).toAnnotatedElement();
}
public XClass classForName(String name, Class caller) throws ClassNotFoundException {
return toXClass( ReflectHelper.classForName( name, caller ) );
}
public XPackage packageForName(String packageName) throws ClassNotFoundException {
return getXAnnotatedElement( ReflectHelper.classForName( packageName + ".package-info" ).getPackage() );
}
XClass toXClass(Type t, final TypeEnvironment context) {
return new TypeSwitch<XClass>() {
@Override
public XClass caseClass(Class classType) {
TypeKey key = new TypeKey( classType, context );
JavaXClass result = xClasses.get( key );
if ( result == null ) {
result = new JavaXClass( classType, context, JavaReflectionManager.this );
xClasses.put( key, result );
}
return result;
}
@Override
public XClass caseParameterizedType(ParameterizedType parameterizedType) {
return toXClass( parameterizedType.getRawType(),
typeEnvs.getEnvironment( parameterizedType, context )
);
}
}.doSwitch( context.bind( t ) );
}
XPackage getXAnnotatedElement(Package pkg) {
JavaXPackage xPackage = packagesToXPackages.get( pkg );
if ( xPackage == null ) {
xPackage = new JavaXPackage( pkg, this );
packagesToXPackages.put( pkg, xPackage );
}
return xPackage;
}
XProperty getXProperty(Member member, TypeEnvironment context) {
MemberKey key = new MemberKey( member, context );
//FIXME get is as expensive as create most time spent in hashCode and equals
JavaXProperty xProperty = xProperties.get( key );
if ( xProperty == null ) {
xProperty = JavaXProperty.create( member, context, this );
xProperties.put( key, xProperty );
}
return xProperty;
}
XMethod getXMethod(Member member, TypeEnvironment context) {
MemberKey key = new MemberKey( member, context );
//FIXME get is as expensive as create most time spent in hashCode and equals
JavaXMethod xMethod = xMethods.get( key );
if ( xMethod == null ) {
xMethod = JavaXMethod.create( member, context, this );
xMethods.put( key, xMethod );
}
return xMethod;
}
TypeEnvironment getTypeEnvironment(final Type t) {
return new TypeSwitch<TypeEnvironment>() {
@Override
public TypeEnvironment caseClass(Class classType) {
return typeEnvs.getEnvironment( classType );
}
@Override
public TypeEnvironment caseParameterizedType(ParameterizedType parameterizedType) {
return typeEnvs.getEnvironment( parameterizedType );
}
@Override
public TypeEnvironment defaultCase(Type type) {
return IdentityTypeEnvironment.INSTANCE;
}
}.doSwitch( t );
}
public JavaXType toXType(TypeEnvironment context, Type propType) {
Type boundType = toApproximatingEnvironment( context ).bind( propType );
if ( TypeUtils.isArray( boundType ) ) {
return new JavaXArrayType( propType, context, this );
}
if ( TypeUtils.isCollection( boundType ) ) {
return new JavaXCollectionType( propType, context, this );
}
if ( TypeUtils.isSimple( boundType ) ) {
return new JavaXSimpleType( propType, context, this );
}
throw new IllegalArgumentException( "No PropertyTypeExtractor available for type void " );
}
public boolean equals(XClass class1, Class class2) {
if ( class1 == null ) {
return class2 == null;
}
return ( (JavaXClass) class1 ).toClass().equals( class2 );
}
public TypeEnvironment toApproximatingEnvironment(TypeEnvironment context) {
return typeEnvs.toApproximatingEnvironment( context );
}
public AnnotationReader buildAnnotationReader(AnnotatedElement annotatedElement) {
return getMetadataProvider().getAnnotationReader( annotatedElement );
}
public Map getDefaults() {
return getMetadataProvider().getDefaults();
}
}

View File

@ -1,88 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import org.hibernate.annotations.common.reflection.AnnotationReader;
import org.hibernate.annotations.common.reflection.XAnnotatedElement;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
abstract class JavaXAnnotatedElement implements XAnnotatedElement {
private final JavaReflectionManager factory;
private final AnnotatedElement annotatedElement;
public JavaXAnnotatedElement(AnnotatedElement annotatedElement, JavaReflectionManager factory) {
this.factory = factory;
this.annotatedElement = annotatedElement;
}
protected JavaReflectionManager getFactory() {
return factory;
}
private AnnotationReader getAnnotationReader() {
return factory.buildAnnotationReader(annotatedElement);
}
public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
return getAnnotationReader().getAnnotation( annotationType );
}
public <T extends Annotation> boolean isAnnotationPresent(Class<T> annotationType) {
return getAnnotationReader().isAnnotationPresent( annotationType );
}
public Annotation[] getAnnotations() {
return getAnnotationReader().getAnnotations();
}
AnnotatedElement toAnnotatedElement() {
return annotatedElement;
}
@Override
public boolean equals(Object obj) {
if ( ! ( obj instanceof JavaXAnnotatedElement ) ) return false;
JavaXAnnotatedElement other = (JavaXAnnotatedElement) obj;
//FIXME yuk this defeat the type environment
return annotatedElement.equals( other.toAnnotatedElement() );
}
@Override
public int hashCode() {
return annotatedElement.hashCode();
}
@Override
public String toString() {
return annotatedElement.toString();
}
}

View File

@ -1,100 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.Collection;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeSwitch;
/**
* @author Emmanuel Bernard
* @author Paolo Perrotta
*/
class JavaXArrayType extends JavaXType {
public JavaXArrayType(Type type, TypeEnvironment context, JavaReflectionManager factory) {
super( type, context, factory );
}
public boolean isArray() {
return true;
}
public boolean isCollection() {
return false;
}
public XClass getElementClass() {
return toXClass( getElementType() );
}
private Type getElementType() {
//TODO make it a static class for faster performance?
return new TypeSwitch<Type>() {
@Override
public Type caseClass(Class classType) {
return classType.getComponentType();
}
@Override
public Type caseGenericArrayType(GenericArrayType genericArrayType) {
return genericArrayType.getGenericComponentType();
}
@Override
public Type defaultCase(Type t) {
throw new IllegalArgumentException( t + " is not an array type" );
}
}.doSwitch( approximate() );
}
public XClass getClassOrElementClass() {
return getElementClass();
}
public Class<? extends Collection> getCollectionClass() {
return null;
}
public XClass getMapKey() {
return null;
}
public XClass getType() {
Type boundType = getElementType();
if ( boundType instanceof Class ) {
boundType = arrayTypeOf( (Class) boundType );
}
return toXClass( boundType );
}
private Class<? extends Object> arrayTypeOf(Class componentType) {
return Array.newInstance( componentType, 0 ).getClass();
}
}

View File

@ -1,162 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import org.hibernate.annotations.common.reflection.Filter;
import org.hibernate.annotations.common.reflection.ReflectionUtil;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XMethod;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.annotations.common.reflection.java.generics.CompoundTypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
class JavaXClass extends JavaXAnnotatedElement implements XClass {
private final TypeEnvironment context;
private final Class clazz;
public JavaXClass(Class clazz, TypeEnvironment env, JavaReflectionManager factory) {
super( clazz, factory );
this.clazz = clazz; //optimization
this.context = env;
}
public String getName() {
return toClass().getName();
}
public XClass getSuperclass() {
return getFactory().toXClass( toClass().getSuperclass(),
CompoundTypeEnvironment.create(
getTypeEnvironment(),
getFactory().getTypeEnvironment( toClass() )
)
);
}
public XClass[] getInterfaces() {
Class[] classes = toClass().getInterfaces();
int length = classes.length;
XClass[] xClasses = new XClass[length];
if (length != 0) {
TypeEnvironment environment = CompoundTypeEnvironment.create(
getTypeEnvironment(),
getFactory().getTypeEnvironment( toClass() )
);
for ( int index = 0; index < length ; index++ ) {
xClasses[index] = getFactory().toXClass( classes[index], environment );
}
}
return xClasses;
}
public boolean isInterface() {
return toClass().isInterface();
}
public boolean isAbstract() {
return Modifier.isAbstract( toClass().getModifiers() );
}
public boolean isPrimitive() {
return toClass().isPrimitive();
}
public boolean isEnum() {
return toClass().isEnum();
}
private List<XProperty> getDeclaredFieldProperties(Filter filter) {
List<XProperty> result = new LinkedList<XProperty>();
for ( Field f : toClass().getDeclaredFields() ) {
if ( ReflectionUtil.isProperty( f, getTypeEnvironment().bind( f.getGenericType() ), filter ) ) {
result.add( getFactory().getXProperty( f, getTypeEnvironment() ) );
}
}
return result;
}
private List<XProperty> getDeclaredMethodProperties(Filter filter) {
List<XProperty> result = new LinkedList<XProperty>();
for ( Method m : toClass().getDeclaredMethods() ) {
if ( ReflectionUtil.isProperty( m, getTypeEnvironment().bind( m.getGenericReturnType() ), filter ) ) {
result.add( getFactory().getXProperty( m, getTypeEnvironment() ) );
}
}
return result;
}
public List<XProperty> getDeclaredProperties(String accessType) {
return getDeclaredProperties( accessType, XClass.DEFAULT_FILTER );
}
public List<XProperty> getDeclaredProperties(String accessType, Filter filter) {
if ( accessType.equals( ACCESS_FIELD ) ) {
return getDeclaredFieldProperties( filter );
}
if ( accessType.equals( ACCESS_PROPERTY ) ) {
return getDeclaredMethodProperties( filter );
}
throw new IllegalArgumentException( "Unknown access type " + accessType );
}
public List<XMethod> getDeclaredMethods() {
List<XMethod> result = new LinkedList<XMethod>();
for ( Method m : toClass().getDeclaredMethods() ) {
result.add( getFactory().getXMethod( m, getTypeEnvironment() ) );
}
return result;
}
public Class<?> toClass() {
return clazz;
}
public boolean isAssignableFrom(XClass c) {
return toClass().isAssignableFrom( ( (JavaXClass) c ).toClass() );
}
boolean isArray() {
return toClass().isArray();
}
TypeEnvironment getTypeEnvironment() {
return context;
}
@Override
public String toString() {
return getName();
}
}

View File

@ -1,100 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
// $Id$
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
import java.util.SortedMap;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeSwitch;
import org.hibernate.annotations.common.reflection.java.generics.TypeUtils;
/**
* @author Emmanuel Bernard
* @author Paolo Perrotta
*/
@SuppressWarnings("unchecked")
class JavaXCollectionType extends JavaXType {
public JavaXCollectionType(Type type, TypeEnvironment context, JavaReflectionManager factory) {
super( type, context, factory );
}
public boolean isArray() {
return false;
}
public boolean isCollection() {
return true;
}
public XClass getElementClass() {
return new TypeSwitch<XClass>() {
@Override
public XClass caseParameterizedType(ParameterizedType parameterizedType) {
Type[] args = parameterizedType.getActualTypeArguments();
Type componentType;
Class<? extends Collection> collectionClass = getCollectionClass();
if ( Map.class.isAssignableFrom( collectionClass )
|| SortedMap.class.isAssignableFrom( collectionClass ) ) {
componentType = args[1];
}
else {
componentType = args[0];
}
return toXClass( componentType );
}
}.doSwitch( approximate() );
}
public XClass getMapKey() {
return new TypeSwitch<XClass>() {
@Override
public XClass caseParameterizedType(ParameterizedType parameterizedType) {
if ( Map.class.isAssignableFrom( getCollectionClass() ) ) {
return toXClass( parameterizedType.getActualTypeArguments()[0] );
}
return null;
}
}.doSwitch( approximate() );
}
public XClass getClassOrElementClass() {
return toXClass( approximate() );
}
public Class<? extends Collection> getCollectionClass() {
return TypeUtils.getCollectionClass( approximate() );
}
public XClass getType() {
return toXClass( approximate() );
}
}

View File

@ -1,118 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
//$Id$
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Collection;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XMember;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
/**
* @author Emmanuel Bernard
*/
public abstract class JavaXMember extends JavaXAnnotatedElement implements XMember {
private final Type type;
private final TypeEnvironment env;
private final JavaXType xType;
protected static Type typeOf(Member member, TypeEnvironment env) {
if ( member instanceof Field ) {
return env.bind( ( (Field) member ).getGenericType() );
}
if ( member instanceof Method ) {
return env.bind( ( (Method) member ).getGenericReturnType() );
}
throw new IllegalArgumentException( "Member " + member + " is neither a field nor a method" );
}
protected JavaXMember(Member member, Type type, TypeEnvironment env, JavaReflectionManager factory, JavaXType xType) {
super( (AnnotatedElement) member, factory );
this.type = type;
this.env = env;
this.xType = xType;
}
public XClass getType() {
return xType.getType();
}
public abstract String getName();
protected Type getJavaType() {
return env.bind( type );
}
protected TypeEnvironment getTypeEnvironment() {
return env;
}
protected Member getMember() {
return (Member) toAnnotatedElement();
}
public Class<? extends Collection> getCollectionClass() {
return xType.getCollectionClass();
}
public XClass getClassOrElementClass() {
return xType.getClassOrElementClass();
}
public XClass getElementClass() {
return xType.getElementClass();
}
public XClass getMapKey() {
return xType.getMapKey();
}
public boolean isArray() {
return xType.isArray();
}
public boolean isCollection() {
return xType.isCollection();
}
public int getModifiers() {
return getMember().getModifiers();
}
public final boolean isTypeResolved() {
return xType.isResolved();
}
public void setAccessible(boolean accessible) {
( (AccessibleObject) getMember() ).setAccessible( accessible );
}
}

View File

@ -1,69 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
//$Id$
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.hibernate.annotations.common.reflection.XMethod;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
/**
* @author Emmanuel Bernard
*/
public class JavaXMethod extends JavaXMember implements XMethod {
static JavaXMethod create(Member member, TypeEnvironment context, JavaReflectionManager factory) {
final Type propType = typeOf( member, context );
JavaXType xType = factory.toXType( context, propType );
return new JavaXMethod( member, propType, context, factory, xType );
}
private JavaXMethod(Member member, Type type, TypeEnvironment env, JavaReflectionManager factory, JavaXType xType) {
super( member, type, env, factory, xType );
assert member instanceof Method;
}
public String getName() {
return getMember().getName();
}
public Object invoke(Object target, Object... parameters) {
try {
return ( (Method) getMember() ).invoke( target, parameters );
}
catch (NullPointerException e) {
throw new IllegalArgumentException( "Invoking " + getName() + " on a null object", e );
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException( "Invoking " + getName() + " with wrong parameters", e );
}
catch (Exception e) {
throw new IllegalStateException( "Unable to invoke " + getName(), e );
}
}
}

View File

@ -1,41 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import org.hibernate.annotations.common.reflection.XPackage;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
class JavaXPackage extends JavaXAnnotatedElement implements XPackage {
public JavaXPackage(Package pkg, JavaReflectionManager factory) {
super( pkg, factory );
}
public String getName() {
return ( (Package) toAnnotatedElement() ).getName();
}
}

View File

@ -1,95 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import java.beans.Introspector;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
class JavaXProperty extends JavaXMember implements XProperty {
static JavaXProperty create(Member member, final TypeEnvironment context, final JavaReflectionManager factory) {
final Type propType = typeOf( member, context );
JavaXType xType = factory.toXType( context, propType );
return new JavaXProperty( member, propType, context, factory, xType );
}
private JavaXProperty(Member member, Type type, TypeEnvironment env, JavaReflectionManager factory, JavaXType xType) {
super( member, type, env, factory, xType );
assert member instanceof Field || member instanceof Method;
}
public String getName() {
String fullName = getMember().getName();
if ( getMember() instanceof Method ) {
if ( fullName.startsWith( "get" ) ) {
return Introspector.decapitalize( fullName.substring( "get".length() ) );
}
if ( fullName.startsWith( "is" ) ) {
return Introspector.decapitalize( fullName.substring( "is".length() ) );
}
throw new RuntimeException( "Method " + fullName + " is not a property getter" );
}
else {
return fullName;
}
}
public Object invoke(Object target, Object... parameters) {
if ( parameters.length != 0 ) {
throw new IllegalArgumentException( "An XProperty cannot have invoke parameters" );
}
try {
if ( getMember() instanceof Method ) {
return ( (Method) getMember() ).invoke( target );
}
else {
return ( (Field) getMember() ).get( target );
}
}
catch (NullPointerException e) {
throw new IllegalArgumentException( "Invoking " + getName() + " on a null object", e );
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException( "Invoking " + getName() + " with wrong parameters", e );
}
catch (Exception e) {
throw new IllegalStateException( "Unable to invoke " + getName(), e );
}
}
@Override
public String toString() {
return getName();
}
}

View File

@ -1,69 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.Type;
import java.util.Collection;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
/**
* @author Emmanuel Bernard
* @author Paolo Perrotta
*/
class JavaXSimpleType extends JavaXType {
public JavaXSimpleType(Type type, TypeEnvironment context, JavaReflectionManager factory) {
super( type, context, factory );
}
public boolean isArray() {
return false;
}
public boolean isCollection() {
return false;
}
public XClass getElementClass() {
return toXClass( approximate() );
}
public XClass getClassOrElementClass() {
return getElementClass();
}
public Class<? extends Collection> getCollectionClass() {
return null;
}
public XClass getType() {
return toXClass( approximate() );
}
public XClass getMapKey() {
return null;
}
}

View File

@ -1,80 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
//$Id: PropertyTypeExtractor.java 9316 2006-02-22 20:47:31Z epbernard $
package org.hibernate.annotations.common.reflection.java;
import java.lang.reflect.Type;
import java.util.Collection;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeUtils;
/**
* The Java X-layer equivalent to a Java <code>Type</code>.
*
* @author Emmanuel Bernard
* @author Paolo Perrotta
*/
abstract class JavaXType {
private final TypeEnvironment context;
private final JavaReflectionManager factory;
private final Type approximatedType;
private final Type boundType;
protected JavaXType(Type unboundType, TypeEnvironment context, JavaReflectionManager factory) {
this.context = context;
this.factory = factory;
this.boundType = context.bind( unboundType );
this.approximatedType = factory.toApproximatingEnvironment( context ).bind( unboundType );
}
abstract public boolean isArray();
abstract public boolean isCollection();
abstract public XClass getElementClass();
abstract public XClass getClassOrElementClass();
abstract public Class<? extends Collection> getCollectionClass();
abstract public XClass getMapKey();
abstract public XClass getType();
public boolean isResolved() {
return TypeUtils.isResolved( boundType );
}
protected Type approximate() {
return approximatedType;
}
protected XClass toXClass(Type type) {
return factory.toXClass( type, context );
}
}

View File

@ -1,81 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java;
/**
* A pair of objects that can be used as a key in a Map.
*
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
abstract class Pair<T, U> {
private final T o1;
private final U o2;
private final int hashCode;
Pair(T o1, U o2) {
this.o1 = o1;
this.o2 = o2;
this.hashCode = doHashCode();
}
@Override
public boolean equals(Object obj) {
if ( ! (obj instanceof Pair) ) {
return false;
}
Pair other = (Pair) obj;
return !differentHashCode( other ) && safeEquals( o1, other.o1 ) && safeEquals( o2, other.o2 );
}
private boolean differentHashCode(Pair other) {
return hashCode != other.hashCode;
}
@Override
public int hashCode() {
//cached because the inheritance can be big
return hashCode;
}
private int doHashCode() {
return safeHashCode( o1 ) ^ safeHashCode( o2 );
}
private int safeHashCode(Object o) {
if ( o == null ) {
return 0;
}
return o.hashCode();
}
private boolean safeEquals(Object obj1, Object obj2) {
if ( obj1 == null ) {
return obj2 == null;
}
return obj1.equals( obj2 );
}
}

View File

@ -1,174 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
/**
* A <code>TypeEnvironment</code> that approximates the unresolved components of a generic simple
* type or collection to their nearest upper binding. The returned type is always fully resolved.
* <p/>
* The concept of "type approximation" is not really sound in general. This class just does what we need
* within the Hibernate Annotations environment. It's more or less a hack. The idea is that certain
* types can provide useful information even if they're not fully resolved in the environment. This class
* tries to turn those types into the nearest fully resolved type that still carries that information.
* <p/>
* For example:<br>
* <code>T</code> becomes <code>Object</code>.<br>
* <code>T extends Foo</code> becomes <code>Foo</code>.<br>
* <code>List&ltT&gt</code> becomes <code>List&ltObject&gt</code>.<br>
* <code>List&ltT extends Foo&gt</code> becomes <code>List&ltFoo&gt</code>.<br>
* An array of <code>T extends Foo</code> becomes an array of <code>Foo</code>.<p>
* <p/>
* If a type variable has multiple upper bounds, it will be approximated to <code>Object</code>.
* Lower bounds are ignored.<p>
* <p/>
* Wildcards are generally not approximated. <code>Class&lt?&gt</code> stays <code>Class&lt?&gt</code>.
* A wildcard within a generic collection is approximated to its upper binding. <code>List&lt?&gt</code> becomes
* <code>List&ltObject&gt</code><p>
* <p/>
* Note that <code>Class&ltT&gt</code> is <emp>not</emp> approximated <code>Class&ltObject&gt</code>.
* That would be wrong in any situation. All parametric types that are not type variables, collections or
* arrays are coarsely approximated to <code>Object.class</code>.
*
* @author Paolo Perrotta
* @return a type where the generic arguments have been replaced by raw classes.
*/
class ApproximatingTypeEnvironment implements TypeEnvironment {
public Type bind(final Type type) {
Type result = fineApproximation( type );
assert TypeUtils.isResolved( result );
return result;
}
private Type fineApproximation(final Type type) {
return new TypeSwitch<Type>() {
public Type caseWildcardType(WildcardType wildcardType) {
return wildcardType;
}
@Override
public Type caseClass(Class classType) {
return classType;
}
@Override
public Type caseGenericArrayType(GenericArrayType genericArrayType) {
if ( TypeUtils.isResolved( genericArrayType ) ) {
return genericArrayType;
}
Type componentType = genericArrayType.getGenericComponentType();
Type boundComponentType = bind( componentType );
if ( boundComponentType instanceof Class ) {
return Array.newInstance( (Class) boundComponentType, 0 ).getClass();
}
// fall back to coarse approximation, because I found no standard way
// to instance arrays of a generic type
return Object[].class;
}
@Override
public Type caseParameterizedType(ParameterizedType parameterizedType) {
if ( TypeUtils.isResolved( parameterizedType ) ) {
return parameterizedType;
}
if ( !TypeUtils.isCollection( parameterizedType ) ) {
return Object.class; // fall back to coarse approximation
}
Type[] typeArguments = parameterizedType.getActualTypeArguments();
Type[] approximatedTypeArguments = new Type[typeArguments.length];
for ( int i = 0; i < typeArguments.length ; i++ ) {
approximatedTypeArguments[i] = coarseApproximation( typeArguments[i] );
}
return TypeFactory.createParameterizedType(
bind( parameterizedType.getRawType() ),
approximatedTypeArguments,
parameterizedType.getOwnerType()
);
}
@Override
public Type defaultCase(Type t) {
return coarseApproximation( t );
}
}.doSwitch( type );
}
private Type coarseApproximation(final Type type) {
Type result = new TypeSwitch<Type>() {
public Type caseWildcardType(WildcardType wildcardType) {
return approximateTo( wildcardType.getUpperBounds() );
}
@Override
public Type caseGenericArrayType(GenericArrayType genericArrayType) {
if ( TypeUtils.isResolved( genericArrayType ) ) {
return genericArrayType;
}
return Object[].class;
}
@Override
public Type caseParameterizedType(ParameterizedType parameterizedType) {
if ( TypeUtils.isResolved( parameterizedType ) ) {
return parameterizedType;
}
return Object.class;
}
@Override
public Type caseTypeVariable(TypeVariable typeVariable) {
return approximateTo( typeVariable.getBounds() );
}
private Type approximateTo(Type[] bounds) {
if ( bounds.length != 1 ) {
return Object.class;
}
return coarseApproximation( bounds[0] );
}
@Override
public Type defaultCase(Type t) {
return t;
}
}.doSwitch( type );
assert TypeUtils.isResolved( result );
return result;
}
@Override
public String toString() {
return "approximated_types";
}
}

View File

@ -1,93 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.Type;
/**
* A composition of two <code>TypeEnvironment</code> functions.
*
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public class CompoundTypeEnvironment implements TypeEnvironment {
private final TypeEnvironment f;
private final TypeEnvironment g;
private final int hashCode;
public static TypeEnvironment create(TypeEnvironment f, TypeEnvironment g) {
if ( g == IdentityTypeEnvironment.INSTANCE )
return f;
if ( f == IdentityTypeEnvironment.INSTANCE )
return g;
return new CompoundTypeEnvironment( f, g );
}
private CompoundTypeEnvironment(TypeEnvironment f, TypeEnvironment g) {
this.f = f;
this.g = g;
hashCode = doHashCode();
}
public Type bind(Type type) {
return f.bind( g.bind( type ) );
}
public boolean equals(Object o) {
if ( this == o ) return true;
if ( ! ( o instanceof CompoundTypeEnvironment ) ) return false;
final CompoundTypeEnvironment that = (CompoundTypeEnvironment) o;
if ( differentHashCode( that ) ) return false;
if ( !f.equals( that.f ) ) return false;
return g.equals( that.g );
}
private boolean differentHashCode(CompoundTypeEnvironment that) {
return hashCode != that.hashCode;
}
private int doHashCode() {
int result;
result = f.hashCode();
result = 29 * result + g.hashCode();
return result;
}
public int hashCode() {
//cached because the inheritance can be big
return hashCode;
}
@Override
public String toString() {
return f.toString() + "(" + g.toString() + ")";
}
}

View File

@ -1,48 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.Type;
/**
* Substitutes a <code>Type</code> for itself.
*
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public class IdentityTypeEnvironment implements TypeEnvironment {
public static final TypeEnvironment INSTANCE = new IdentityTypeEnvironment();
private IdentityTypeEnvironment() {
}
public Type bind(Type type) {
return type;
}
public String toString() {
return "{}";
}
}

View File

@ -1,116 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.HashMap;
/**
* Binds formal type arguments (typically T, E, etc.) to actual types.
*
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
class SimpleTypeEnvironment extends HashMap<Type, Type> implements TypeEnvironment {
private static final long serialVersionUID = 1L;
private final TypeSwitch<Type> substitute = new TypeSwitch<Type>() {
@Override
public Type caseClass(Class classType) {
return classType;
}
@Override
public Type caseGenericArrayType(GenericArrayType genericArrayType) {
Type originalComponentType = genericArrayType.getGenericComponentType();
Type boundComponentType = bind( originalComponentType );
// try to keep the original type if possible
if ( originalComponentType == boundComponentType ) {
return genericArrayType;
}
return TypeFactory.createArrayType( boundComponentType );
}
@Override
public Type caseParameterizedType(ParameterizedType parameterizedType) {
Type[] originalArguments = parameterizedType.getActualTypeArguments();
Type[] boundArguments = substitute( originalArguments );
// try to keep the original type if possible
if ( areSame( originalArguments, boundArguments ) ) {
return parameterizedType;
}
return TypeFactory.createParameterizedType(
parameterizedType.getRawType(), boundArguments, parameterizedType.getOwnerType()
);
}
private boolean areSame(Object[] array1, Object[] array2) {
if ( array1.length != array2.length ) {
return false;
}
for ( int i = 0; i < array1.length ; i++ ) {
if ( array1[i] != array2[i] ) {
return false;
}
}
return true;
}
@Override
public Type caseTypeVariable(TypeVariable typeVariable) {
if ( !containsKey( typeVariable )) {
return typeVariable;
}
return get( typeVariable );
}
@Override
public Type caseWildcardType(WildcardType wildcardType) {
return wildcardType;
}
};
public SimpleTypeEnvironment(Type[] formalTypeArgs, Type[] actualTypeArgs) {
for (int i = 0; i < formalTypeArgs.length; i++) {
put( formalTypeArgs[i], actualTypeArgs[i] );
}
}
public Type bind(Type type) {
return substitute.doSwitch( type );
}
private Type[] substitute(Type[] types) {
Type[] substTypes = new Type[types.length];
for ( int i = 0; i < substTypes.length ; i++ ) {
substTypes[i] = bind( types[i] );
}
return substTypes;
}
}

View File

@ -1,76 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.Type;
/**
* A typing context that knows how to "resolve" the generic parameters of a
* <code>Type</code>.
* <p/>
* For example:
* <p/>
* <p/>
* <blockquote>
* <p/>
* <pre>
* class Shop&ltT&gt{
* List&ltT&gt getCatalog() { ... }
* }
* <p/>
* class Bakery extends Shop&ltBread&gt{}
* </pre>
* <p/>
* </blockquote>
* <p/>
* Consider the type returned by method <code>getCatalog()</code>. There are
* two possible contexts here. In the context of <code>Shop</code>, the type
* is <code>List&ltT&gt</code>. In the context of <code>Bakery</code>, the
* type is <code>List&ltBread&gt</code>. Each of these contexts can be
* represented by a <code>TypeEnvironment</code>.
*
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public interface TypeEnvironment {
/**
* Binds as many generic components of the given type as possible in this
* context.
* <p/>
* Warning: if the returned <code>Type</code> is a <code>Class</code>,
* then it's guaranteed to be a regular Java <code>Class</code>. In all
* other cases, this method might return a custom implementation of some
* interface that extends <code>Type</code>. Be sure not to mix these
* objects with Java's implementations of <code>Type</code> to avoid
* potential identity problems.
* <p/>
* This class does not support bindings involving inner classes or
* upper/lower bounds.
*
* @return a type where the generic arguments have been replaced by raw
* classes whenever this is possible.
*/
public Type bind(Type type);
}

View File

@ -1,118 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
/**
* Returns the type context for a given <code>Class</code> or <code>ParameterizedType</code>.
* <p/>
* Does not support bindings involving inner classes, nor upper/lower bounds.
*
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public class TypeEnvironmentFactory {
/**
* @return Returns a type environment suitable for resolving types occurring
* in subclasses of the context class.
*/
public TypeEnvironment getEnvironment(Class context) {
if ( context == null ) {
return IdentityTypeEnvironment.INSTANCE;
}
return createEnvironment( context );
}
public TypeEnvironment getEnvironment(Type context) {
if ( context == null ) {
return IdentityTypeEnvironment.INSTANCE;
}
return createEnvironment( context );
}
public TypeEnvironment getEnvironment(Type t, TypeEnvironment context) {
return CompoundTypeEnvironment.create( getEnvironment(t), context );
}
public TypeEnvironment toApproximatingEnvironment(TypeEnvironment context) {
return CompoundTypeEnvironment.create( new ApproximatingTypeEnvironment(), context );
}
private TypeEnvironment createEnvironment(Type context) {
return new TypeSwitch<TypeEnvironment>() {
@Override
public TypeEnvironment caseClass(Class classType) {
return CompoundTypeEnvironment.create(
createSuperTypeEnvironment( classType ),
getEnvironment( classType.getSuperclass() )
);
}
@Override
public TypeEnvironment caseParameterizedType(ParameterizedType parameterizedType) {
return createEnvironment( parameterizedType );
}
@Override
public TypeEnvironment defaultCase(Type t) {
throw new IllegalArgumentException( "Invalid type for generating environment: " + t );
}
}.doSwitch( context );
}
private TypeEnvironment createSuperTypeEnvironment(Class clazz) {
Class superclass = clazz.getSuperclass();
if ( superclass == null ) {
return IdentityTypeEnvironment.INSTANCE;
}
Type[] formalArgs = superclass.getTypeParameters();
Type genericSuperclass = clazz.getGenericSuperclass();
if ( genericSuperclass instanceof Class ) {
return IdentityTypeEnvironment.INSTANCE;
}
if ( genericSuperclass instanceof ParameterizedType ) {
Type[] actualArgs = ( (ParameterizedType) genericSuperclass ).getActualTypeArguments();
return new SimpleTypeEnvironment( formalArgs, actualArgs );
}
throw new AssertionError( "Should be unreachable" );
}
private TypeEnvironment createEnvironment(ParameterizedType t) {
Type[] tactuals = t.getActualTypeArguments();
Type rawType = t.getRawType();
if ( rawType instanceof Class ) {
TypeVariable[] tparms = ( (Class) rawType ).getTypeParameters();
return new SimpleTypeEnvironment( tparms, tactuals );
}
return IdentityTypeEnvironment.INSTANCE;
}
}

View File

@ -1,123 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
/**
* This class instances our own <code>ParameterizedTypes</code> and <code>GenericArrayTypes</code>.
* These are not supposed to be mixed with Java's implementations - beware of
* equality/identity problems.
*
* @author Paolo Perrotta
*/
class TypeFactory {
static ParameterizedType createParameterizedType(
final Type rawType, final Type[] substTypeArgs,
final Type ownerType
) {
return new ParameterizedType() {
public Type[] getActualTypeArguments() {
return substTypeArgs;
}
public Type getRawType() {
return rawType;
}
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object obj) {
if ( !( obj instanceof ParameterizedType ) ) {
return false;
}
ParameterizedType other = (ParameterizedType) obj;
return Arrays.equals( getActualTypeArguments(), other.getActualTypeArguments() )
&& safeEquals( getRawType(), other.getRawType() ) && safeEquals(
getOwnerType(), other.getOwnerType()
);
}
@Override
public int hashCode() {
return safeHashCode( getActualTypeArguments() ) ^ safeHashCode( getRawType() ) ^ safeHashCode(
getOwnerType()
);
}
};
}
static Type createArrayType(Type componentType) {
if ( componentType instanceof Class ) {
return Array.newInstance( (Class) componentType, 0 ).getClass();
}
return TypeFactory.createGenericArrayType( componentType );
}
private static GenericArrayType createGenericArrayType(final Type componentType) {
return new GenericArrayType() {
public Type getGenericComponentType() {
return componentType;
}
@Override
public boolean equals(Object obj) {
if ( !( obj instanceof GenericArrayType ) ) {
return false;
}
GenericArrayType other = (GenericArrayType) obj;
return safeEquals( getGenericComponentType(), other.getGenericComponentType() );
}
@Override
public int hashCode() {
return safeHashCode( getGenericComponentType() );
}
};
}
private static boolean safeEquals(Type t1, Type t2) {
if ( t1 == null ) {
return t2 == null;
}
return t1.equals( t2 );
}
private static int safeHashCode(Object o) {
if ( o == null ) {
return 1;
}
return o.hashCode();
}
}

View File

@ -1,82 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
/**
* A visitor for the <code>java.lang.reflect.Type</code> hierarchy.
*
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public class TypeSwitch<T> {
public final T doSwitch(Type type) {
if ( type instanceof Class ) {
return caseClass( (Class) type );
}
if ( type instanceof GenericArrayType ) {
return caseGenericArrayType( (GenericArrayType) type );
}
if ( type instanceof ParameterizedType ) {
return caseParameterizedType( (ParameterizedType) type );
}
if ( type instanceof TypeVariable ) {
return caseTypeVariable( (TypeVariable) type );
}
if ( type instanceof WildcardType ) {
return caseWildcardType( (WildcardType) type );
}
return defaultCase( type );
}
public T caseWildcardType(WildcardType wildcardType) {
return defaultCase( wildcardType );
}
public T caseTypeVariable(TypeVariable typeVariable) {
return defaultCase( typeVariable );
}
public T caseClass(Class classType) {
return defaultCase( classType );
}
public T caseGenericArrayType(GenericArrayType genericArrayType) {
return defaultCase( genericArrayType );
}
public T caseParameterizedType(ParameterizedType parameterizedType) {
return defaultCase( parameterizedType );
}
public T defaultCase(Type t) {
return null;
}
}

View File

@ -1,178 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.reflection.java.generics;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Collection;
/**
* @author Paolo Perrotta
*/
public class TypeUtils {
public static boolean isResolved(Type t) {
return new TypeSwitch<Boolean>() {
@Override
public Boolean caseClass(Class classType) {
return true;
}
@Override
public Boolean caseGenericArrayType(GenericArrayType genericArrayType) {
return isResolved( genericArrayType.getGenericComponentType() );
}
@Override
public Boolean caseParameterizedType(ParameterizedType parameterizedType) {
Type[] typeArgs = parameterizedType.getActualTypeArguments();
for ( Type arg : typeArgs ) {
if ( !isResolved( arg ) ) {
return false;
}
}
return isResolved( parameterizedType.getRawType() );
}
@Override
public Boolean caseTypeVariable(TypeVariable typeVariable) {
return false;
}
@Override
public Boolean caseWildcardType(WildcardType wildcardType) {
return areResolved( wildcardType.getUpperBounds() ) && areResolved( wildcardType.getLowerBounds() );
}
}.doSwitch( t );
}
private static Boolean areResolved(Type[] types) {
for ( Type t : types ) {
if ( !isResolved( t ) ) {
return false;
}
}
return true;
}
public static Class<? extends Collection> getCollectionClass(Type type) {
return new TypeSwitch<Class<? extends Collection>>() {
@Override
public Class<? extends Collection> caseClass(Class clazz) {
return isCollectionClass( clazz ) ? (Class<? extends Collection>) clazz : null;
}
@Override
public Class<? extends Collection> caseParameterizedType(ParameterizedType parameterizedType) {
return getCollectionClass( parameterizedType.getRawType() );
}
@Override
public Class<? extends Collection> caseWildcardType(WildcardType wildcardType) {
Type[] upperBounds = wildcardType.getUpperBounds();
if ( upperBounds.length == 0 ) {
return null;
}
return getCollectionClass( upperBounds[0] );
}
@Override
public Class<? extends Collection> defaultCase(Type t) {
return null;
}
}.doSwitch( type );
}
private static boolean isCollectionClass(Class<?> clazz) {
return clazz == Collection.class
|| clazz == java.util.List.class
|| clazz == java.util.Set.class
|| clazz == java.util.Map.class
|| clazz == java.util.SortedSet.class // extension to the specs
|| clazz == java.util.SortedMap.class; // extension to the specs
}
public static boolean isSimple(Type type) {
return new TypeSwitch<Boolean>() {
@Override
public Boolean caseClass(Class clazz) {
return !clazz.isArray() && !isCollectionClass( clazz ); // probably not fully accurate
}
@Override
public Boolean caseParameterizedType(ParameterizedType parameterizedType) {
return isSimple( parameterizedType.getRawType() );
}
@Override
public Boolean caseWildcardType(WildcardType wildcardType) {
return areSimple( wildcardType.getUpperBounds() ) && areSimple( wildcardType.getLowerBounds() );
}
@Override
public Boolean defaultCase(Type t) {
return false;
}
}.doSwitch( type );
}
private static Boolean areSimple(Type[] types) {
for ( Type t : types ) {
if ( !isSimple( t ) ) {
return false;
}
}
return true;
}
public static boolean isVoid(Type type) {
return void.class.equals( type );
}
public static boolean isArray(Type t) {
return new TypeSwitch<Boolean>() {
@Override
public Boolean caseClass(Class clazz) {
return clazz.isArray();
}
@Override
public Boolean caseGenericArrayType(GenericArrayType genericArrayType) {
return isSimple( genericArrayType.getGenericComponentType() );
}
@Override
public Boolean defaultCase(Type type) {
return false;
}
}.doSwitch( t );
}
public static boolean isCollection(Type t) {
return getCollectionClass( t ) != null;
}
}

View File

@ -1,232 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.util;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.hibernate.annotations.common.AssertionFailure;
/**
* Complete duplication of {@link org.hibernate.util.ReflectHelper}.
*
* @author Emmanuel Bernard
*/
public final class ReflectHelper {
public static final Class[] NO_PARAM_SIGNATURE = new Class[0];
public static final Object[] NO_PARAMS = new Object[0];
public static final Class[] SINGLE_OBJECT_PARAM_SIGNATURE = new Class[] { Object.class };
private static final Method OBJECT_EQUALS;
private static final Method OBJECT_HASHCODE;
static {
Method eq;
Method hash;
try {
eq = extractEqualsMethod( Object.class );
hash = extractHashCodeMethod( Object.class );
}
catch ( Exception e ) {
throw new AssertionFailure( "Could not find Object.equals() or Object.hashCode()", e );
}
OBJECT_EQUALS = eq;
OBJECT_HASHCODE = hash;
}
/**
* Disallow instantiation of ReflectHelper.
*/
private ReflectHelper() {
}
/**
* Encapsulation of getting hold of a class's {@link Object#equals equals} method.
*
* @param clazz The class from which to extract the equals method.
* @return The equals method reference
* @throws NoSuchMethodException Should indicate an attempt to extract equals method from interface.
*/
public static Method extractEqualsMethod(Class clazz) throws NoSuchMethodException {
return clazz.getMethod( "equals", SINGLE_OBJECT_PARAM_SIGNATURE );
}
/**
* Encapsulation of getting hold of a class's {@link Object#hashCode hashCode} method.
*
* @param clazz The class from which to extract the hashCode method.
* @return The hashCode method reference
* @throws NoSuchMethodException Should indicate an attempt to extract hashCode method from interface.
*/
public static Method extractHashCodeMethod(Class clazz) throws NoSuchMethodException {
return clazz.getMethod( "hashCode", NO_PARAM_SIGNATURE );
}
/**
* Determine if the given class defines an {@link Object#equals} override.
*
* @param clazz The class to check
* @return True if clazz defines an equals override.
*/
public static boolean overridesEquals(Class clazz) {
Method equals;
try {
equals = extractEqualsMethod( clazz );
}
catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
return !OBJECT_EQUALS.equals( equals );
}
/**
* Determine if the given class defines a {@link Object#hashCode} override.
*
* @param clazz The class to check
* @return True if clazz defines an hashCode override.
*/
public static boolean overridesHashCode(Class clazz) {
Method hashCode;
try {
hashCode = extractHashCodeMethod( clazz );
}
catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
return !OBJECT_HASHCODE.equals( hashCode );
}
/**
* Perform resolution of a class name.
* <p/>
* Here we first check the context classloader, if one, before delegating to
* {@link Class#forName(String, boolean, ClassLoader)} using the caller's classloader
*
* @param name The class name
* @param caller The class from which this call originated (in order to access that class's loader).
* @return The class reference.
* @throws ClassNotFoundException From {@link Class#forName(String, boolean, ClassLoader)}.
*/
public static Class classForName(String name, Class caller) throws ClassNotFoundException {
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if ( contextClassLoader != null ) {
return contextClassLoader.loadClass( name );
}
}
catch ( Throwable ignore ) {
}
return Class.forName( name, true, caller.getClassLoader() );
}
/**
* Perform resolution of a class name.
* <p/>
* Same as {@link #classForName(String, Class)} except that here we delegate to
* {@link Class#forName(String)} if the context classloader lookup is unsuccessful.
*
* @param name The class name
* @return The class reference.
* @throws ClassNotFoundException From {@link Class#forName(String)}.
*/
public static Class classForName(String name) throws ClassNotFoundException {
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if ( contextClassLoader != null ) {
return contextClassLoader.loadClass(name);
}
}
catch ( Throwable ignore ) {
}
return Class.forName( name );
}
/**
* Is this member publicly accessible.
*
* @param clazz The class which defines the member
* @param member The memeber.
* @return True if the member is publicly accessible, false otherwise.
*/
public static boolean isPublic(Class clazz, Member member) {
return Modifier.isPublic( member.getModifiers() ) && Modifier.isPublic( clazz.getModifiers() );
}
/**
* Resolve a constant to its actual value.
*
* @param name The name
* @return The value
*/
public static Object getConstantValue(String name) {
Class clazz;
try {
clazz = classForName( StringHelper.qualifier( name ) );
}
catch ( Throwable t ) {
return null;
}
try {
return clazz.getField( StringHelper.unqualify( name ) ).get( null );
}
catch ( Throwable t ) {
return null;
}
}
/**
* Determine if the given class is declared abstract.
*
* @param clazz The class to check.
* @return True if the class is abstract, false otherwise.
*/
public static boolean isAbstractClass(Class clazz) {
int modifier = clazz.getModifiers();
return Modifier.isAbstract(modifier) || Modifier.isInterface(modifier);
}
/**
* Determine is the given class is declared final.
*
* @param clazz The class to check.
* @return True if the class is final, flase otherwise.
*/
public static boolean isFinalClass(Class clazz) {
return Modifier.isFinal( clazz.getModifiers() );
}
public static Method getMethod(Class clazz, Method method) {
try {
return clazz.getMethod( method.getName(), method.getParameterTypes() );
}
catch (Exception e) {
return null;
}
}
}

View File

@ -1,516 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.annotations.common.util;
import java.util.Arrays;
import java.util.Iterator;
import java.util.StringTokenizer;
/**
* Complete duplication of {@link org.hibernate.util.StringHelper}.
*
* @author Emmanuel Bernard
*/
public final class StringHelper {
private static final int ALIAS_TRUNCATE_LENGTH = 10;
public static final String WHITESPACE = " \n\r\f\t";
private StringHelper() { /* static methods only - hide constructor */
}
/*public static boolean containsDigits(String string) {
for ( int i=0; i<string.length(); i++ ) {
if ( Character.isDigit( string.charAt(i) ) ) return true;
}
return false;
}*/
public static int lastIndexOfLetter(String string) {
for ( int i=0; i<string.length(); i++ ) {
char character = string.charAt(i);
if ( !Character.isLetter(character) /*&& !('_'==character)*/ ) return i-1;
}
return string.length()-1;
}
public static String join(String seperator, String[] strings) {
int length = strings.length;
if ( length == 0 ) return "";
StringBuffer buf = new StringBuffer( length * strings[0].length() )
.append( strings[0] );
for ( int i = 1; i < length; i++ ) {
buf.append( seperator ).append( strings[i] );
}
return buf.toString();
}
public static String join(String seperator, Iterator objects) {
StringBuffer buf = new StringBuffer();
if ( objects.hasNext() ) buf.append( objects.next() );
while ( objects.hasNext() ) {
buf.append( seperator ).append( objects.next() );
}
return buf.toString();
}
public static String[] add(String[] x, String sep, String[] y) {
String[] result = new String[x.length];
for ( int i = 0; i < x.length; i++ ) {
result[i] = x[i] + sep + y[i];
}
return result;
}
public static String repeat(String string, int times) {
StringBuffer buf = new StringBuffer( string.length() * times );
for ( int i = 0; i < times; i++ ) buf.append( string );
return buf.toString();
}
public static String repeat(char character, int times) {
char[] buffer = new char[times];
Arrays.fill( buffer, character );
return new String( buffer );
}
public static String replace(String template, String placeholder, String replacement) {
return replace( template, placeholder, replacement, false );
}
public static String[] replace(String templates[], String placeholder, String replacement) {
String[] result = new String[templates.length];
for ( int i =0; i<templates.length; i++ ) {
result[i] = replace( templates[i], placeholder, replacement );
}
return result;
}
public static String replace(String template, String placeholder, String replacement, boolean wholeWords) {
if ( template == null ) {
return template;
}
int loc = template.indexOf( placeholder );
if ( loc < 0 ) {
return template;
}
else {
final boolean actuallyReplace = !wholeWords ||
loc + placeholder.length() == template.length() ||
!Character.isJavaIdentifierPart( template.charAt( loc + placeholder.length() ) );
String actualReplacement = actuallyReplace ? replacement : placeholder;
return new StringBuffer( template.substring( 0, loc ) )
.append( actualReplacement )
.append( replace( template.substring( loc + placeholder.length() ),
placeholder,
replacement,
wholeWords ) ).toString();
}
}
public static String replaceOnce(String template, String placeholder, String replacement) {
if ( template == null ) {
return template; // returnign null!
}
int loc = template.indexOf( placeholder );
if ( loc < 0 ) {
return template;
}
else {
return new StringBuffer( template.substring( 0, loc ) )
.append( replacement )
.append( template.substring( loc + placeholder.length() ) )
.toString();
}
}
public static String[] split(String seperators, String list) {
return split( seperators, list, false );
}
public static String[] split(String seperators, String list, boolean include) {
StringTokenizer tokens = new StringTokenizer( list, seperators, include );
String[] result = new String[ tokens.countTokens() ];
int i = 0;
while ( tokens.hasMoreTokens() ) {
result[i++] = tokens.nextToken();
}
return result;
}
public static String unqualify(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( qualifiedName.lastIndexOf(".") + 1 );
}
public static String qualifier(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
return ( loc < 0 ) ? "" : qualifiedName.substring( 0, loc );
}
/**
* Collapses a name. Mainly intended for use with classnames, where an example might serve best to explain.
* Imagine you have a class named <samp>'org.hibernate.util.StringHelper'</samp>; calling collapse on that
* classname will result in <samp>'o.h.u.StringHelper'<samp>.
*
* @param name The name to collapse.
* @return The collapsed name.
*/
public static String collapse(String name) {
if ( name == null ) {
return null;
}
int breakPoint = name.lastIndexOf( '.' );
if ( breakPoint < 0 ) {
return name;
}
return collapseQualifier( name.substring( 0, breakPoint ), true ) + name.substring( breakPoint ); // includes last '.'
}
/**
* Given a qualifier, collapse it.
*
* @param qualifier The qualifier to collapse.
* @param includeDots Should we include the dots in the collapsed form?
*
* @return The collapsed form.
*/
public static String collapseQualifier(String qualifier, boolean includeDots) {
StringTokenizer tokenizer = new StringTokenizer( qualifier, "." );
String collapsed = Character.toString( tokenizer.nextToken().charAt( 0 ) );
while ( tokenizer.hasMoreTokens() ) {
if ( includeDots ) {
collapsed += '.';
}
collapsed += tokenizer.nextToken().charAt( 0 );
}
return collapsed;
}
/**
* Partially unqualifies a qualified name. For example, with a base of 'org.hibernate' the name
* 'org.hibernate.util.StringHelper' would become 'util.StringHelper'.
*
* @param name The (potentially) qualified name.
* @param qualifierBase The qualifier base.
*
* @return The name itself, or the partially unqualified form if it begins with the qualifier base.
*/
public static String partiallyUnqualify(String name, String qualifierBase) {
if ( name == null || ! name.startsWith( qualifierBase ) ) {
return name;
}
return name.substring( qualifierBase.length() + 1 ); // +1 to start after the following '.'
}
/**
* Cross between {@link #collapse} and {@link #partiallyUnqualify}. Functions much like {@link #collapse}
* except that only the qualifierBase is collapsed. For example, with a base of 'org.hibernate' the name
* 'org.hibernate.util.StringHelper' would become 'o.h.util.StringHelper'.
*
* @param name The (potentially) qualified name.
* @param qualifierBase The qualifier base.
*
* @return The name itself if it does not begin with the qualifierBase, or the properly collapsed form otherwise.
*/
public static String collapseQualifierBase(String name, String qualifierBase) {
if ( name == null || ! name.startsWith( qualifierBase ) ) {
return collapse( name );
}
return collapseQualifier( qualifierBase, true ) + name.substring( qualifierBase.length() );
}
public static String[] suffix(String[] columns, String suffix) {
if ( suffix == null ) return columns;
String[] qualified = new String[columns.length];
for ( int i = 0; i < columns.length; i++ ) {
qualified[i] = suffix( columns[i], suffix );
}
return qualified;
}
private static String suffix(String name, String suffix) {
return ( suffix == null ) ? name : name + suffix;
}
public static String root(String qualifiedName) {
int loc = qualifiedName.indexOf( "." );
return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( 0, loc );
}
public static String unroot(String qualifiedName) {
int loc = qualifiedName.indexOf( "." );
return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( loc+1, qualifiedName.length() );
}
public static boolean booleanValue(String tfString) {
String trimmed = tfString.trim().toLowerCase();
return trimmed.equals( "true" ) || trimmed.equals( "t" );
}
public static String toString(Object[] array) {
int len = array.length;
if ( len == 0 ) return "";
StringBuffer buf = new StringBuffer( len * 12 );
for ( int i = 0; i < len - 1; i++ ) {
buf.append( array[i] ).append(", ");
}
return buf.append( array[len - 1] ).toString();
}
public static String[] multiply(String string, Iterator placeholders, Iterator replacements) {
String[] result = new String[]{string};
while ( placeholders.hasNext() ) {
result = multiply( result, ( String ) placeholders.next(), ( String[] ) replacements.next() );
}
return result;
}
private static String[] multiply(String[] strings, String placeholder, String[] replacements) {
String[] results = new String[replacements.length * strings.length];
int n = 0;
for ( int i = 0; i < replacements.length; i++ ) {
for ( int j = 0; j < strings.length; j++ ) {
results[n++] = replaceOnce( strings[j], placeholder, replacements[i] );
}
}
return results;
}
public static int countUnquoted(String string, char character) {
if ( '\'' == character ) {
throw new IllegalArgumentException( "Unquoted count of quotes is invalid" );
}
if (string == null)
return 0;
// Impl note: takes advantage of the fact that an escpaed single quote
// embedded within a quote-block can really be handled as two seperate
// quote-blocks for the purposes of this method...
int count = 0;
int stringLength = string.length();
boolean inQuote = false;
for ( int indx = 0; indx < stringLength; indx++ ) {
char c = string.charAt( indx );
if ( inQuote ) {
if ( '\'' == c ) {
inQuote = false;
}
}
else if ( '\'' == c ) {
inQuote = true;
}
else if ( c == character ) {
count++;
}
}
return count;
}
public static boolean isNotEmpty(String string) {
return string != null && string.length() > 0;
}
public static boolean isEmpty(String string) {
return string == null || string.length() == 0;
}
public static String qualify(String prefix, String name) {
if ( name == null || prefix == null ) {
throw new NullPointerException();
}
return new StringBuffer( prefix.length() + name.length() + 1 )
.append(prefix)
.append('.')
.append(name)
.toString();
}
public static String[] qualify(String prefix, String[] names) {
if ( prefix == null ) return names;
int len = names.length;
String[] qualified = new String[len];
for ( int i = 0; i < len; i++ ) {
qualified[i] = qualify( prefix, names[i] );
}
return qualified;
}
public static int firstIndexOfChar(String sqlString, String string, int startindex) {
int matchAt = -1;
for ( int i = 0; i < string.length(); i++ ) {
int curMatch = sqlString.indexOf( string.charAt( i ), startindex );
if ( curMatch >= 0 ) {
if ( matchAt == -1 ) { // first time we find match!
matchAt = curMatch;
}
else {
matchAt = Math.min( matchAt, curMatch );
}
}
}
return matchAt;
}
public static String truncate(String string, int length) {
if ( string.length() <= length ) {
return string;
}
else {
return string.substring( 0, length );
}
}
public static String generateAlias(String description) {
return generateAliasRoot(description) + '_';
}
/**
* Generate a nice alias for the given class name or collection role name and unique integer. Subclasses of
* Loader do <em>not</em> have to use aliases of this form.
*
* @param description The base name (usually an entity-name or collection-role)
* @param unique A uniquing value
*
* @return an alias of the form <samp>foo1_</samp>
*/
public static String generateAlias(String description, int unique) {
return generateAliasRoot(description) +
Integer.toString(unique) +
'_';
}
/**
* Generates a root alias by truncating the "root name" defined by
* the incoming decription and removing/modifying any non-valid
* alias characters.
*
* @param description The root name from which to generate a root alias.
* @return The generated root alias.
*/
private static String generateAliasRoot(String description) {
String result = truncate( unqualifyEntityName(description), ALIAS_TRUNCATE_LENGTH )
.toLowerCase()
.replace( '/', '_' ) // entityNames may now include slashes for the representations
.replace( '$', '_' ); //classname may be an inner class
result = cleanAlias( result );
if ( Character.isDigit( result.charAt(result.length()-1) ) ) {
return result + "x"; //ick!
}
else {
return result;
}
}
/**
* Clean the generated alias by removing any non-alpha characters from the
* beginning.
*
* @param alias The generated alias to be cleaned.
* @return The cleaned alias, stripped of any leading non-alpha characters.
*/
private static String cleanAlias(String alias) {
char[] chars = alias.toCharArray();
// short cut check...
if ( !Character.isLetter( chars[0] ) ) {
for ( int i = 1; i < chars.length; i++ ) {
// as soon as we encounter our first letter, return the substring
// from that position
if ( Character.isLetter( chars[i] ) ) {
return alias.substring( i );
}
}
}
return alias;
}
public static String unqualifyEntityName(String entityName) {
String result = unqualify(entityName);
int slashPos = result.indexOf( '/' );
if ( slashPos > 0 ) {
result = result.substring( 0, slashPos - 1 );
}
return result;
}
public static String toUpperCase(String str) {
return str==null ? null : str.toUpperCase();
}
public static String toLowerCase(String str) {
return str==null ? null : str.toLowerCase();
}
public static String moveAndToBeginning(String filter) {
if ( filter.trim().length()>0 ){
filter += " and ";
if ( filter.startsWith(" and ") ) filter = filter.substring(4);
}
return filter;
}
/**
* Determine if the given string is quoted (wrapped by '`' characters at beginning and end).
*
* @param name The name to check.
* @return True if the given string starts and ends with '`'; false otherwise.
*/
public static boolean isQuoted(String name) {
return name != null && name.length() != 0 && name.charAt( 0 ) == '`' && name.charAt( name.length() - 1 ) == '`';
}
/**
* Return a representation of the given name ensuring quoting (wrapped with '`' characters). If already wrapped
* return name.
*
* @param name The name to quote.
* @return The quoted version.
*/
public static String quote(String name) {
if ( name == null || name.length() == 0 || isQuoted( name ) ) {
return name;
}
else {
return new StringBuffer( name.length() + 2 ).append('`').append( name ).append( '`' ).toString();
}
}
/**
* Return the unquoted version of name (stripping the start and end '`' characters if present).
*
* @param name The name to be unquoted.
* @return The unquoted version.
*/
public static String unquote(String name) {
if ( isQuoted( name ) ) {
return name.substring( 1, name.length() - 1 );
}
else {
return name;
}
}
}

View File

@ -1,117 +0,0 @@
/* Javadoc style sheet */
/* Define colors, fonts and other style attributes here to override the defaults */
/* Page background color */
body { font-family: Arial;
background-color: white;
font-size: 10pt;
}
td { font-family: Arial;
font-size: 10pt;
}
/* Table colors */
.TableHeadingColor { background: #F4F4F4 }
.TableSubHeadingColor { background: #F4F4F4 }
.TableRowColor { background: #FFFFFF }
/* Font used in left-hand frame lists */
.FrameTitleFont { font-size: normal; font-family: Arial }
.FrameHeadingFont { font-size: normal; font-family: Arial }
.FrameItemFont { font-size: normal; font-family: Arial }
/* Example of smaller, sans-serif font in frames */
/* .FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial, sans-serif } */
/* Navigation bar fonts and colors */
.NavBarCell1 { background-color:#F4F4F4;}
.NavBarCell1Rev { background-color:silver;}
.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;}
.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;}
.NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;}
.NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;}
A {
color: #003399;
}
A:active {
color: #003399;
}
A:visited {
color: #888888;
}
P, OL, UL, LI, DL, DT, DD, BLOCKQUOTE {
color: #000000;
}
TD, TH, SPAN {
color: #000000;
}
BLOCKQUOTE {
margin-right: 0px;
}
/*H1, H2, H3, H4, H5, H6 {
color: #000000;
font-weight:500;
margin-top:10px;
padding-top:15px;
}
H1 { font-size: 150%; }
H2 { font-size: 140%; }
H3 { font-size: 110%; font-weight: bold; }
H4 { font-size: 110%; font-weight: bold;}
H5 { font-size: 100%; font-style: italic; }
H6 { font-size: 100%; font-style: italic; }*/
TT {
font-size: 90%;
font-family: "Courier New", Courier, monospace;
color: #000000;
}
PRE {
font-size: 90%;
padding: 5px;
border-style: solid;
border-width: 1px;
border-color: #CCCCCC;
background-color: #F4F4F4;
}
UL, OL, LI {
list-style: disc;
}
HR {
width: 100%;
height: 1px;
background-color: #CCCCCC;
border-width: 0px;
padding: 0px;
color: #CCCCCC;
}
.variablelist {
padding-top: 10;
padding-bottom:10;
margin:0;
}
.itemizedlist, UL {
padding-top: 0;
padding-bottom:0;
margin:0;
}
.term {
font-weight:bold;
}

View File

@ -1 +0,0 @@
<body></body>

View File

@ -1,38 +0,0 @@
package org.hibernate.annotations.common.test.annotationfactory;
import junit.framework.TestCase;
import org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor;
import org.hibernate.annotations.common.annotationfactory.AnnotationFactory;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
public class AnnotationFactoryTest extends TestCase {
public void testCreatesProxyInstancesOfAnnotations() {
// Step 1: define the annotation descriptor.
//
// What you can/must do:
// - You can assign values with the wrong type to the annotation
// elements. The code won't check that the values are the same
// types as required by the Annotation interface. You will
// end up receiving an exception when you access the value, though.
// - You must assign a value in the descriptor to all the elements
// defined in the Annotation interface that do not have a default
// value.
// - You can ignore in the descriptor those Annotation elements that
// have default values, or you can set them to override their
// default values.
AnnotationDescriptor descriptor = new AnnotationDescriptor( TestAnnotation.class );
descriptor.setValue( "booleanElement", false );
descriptor.setValue( "stringElement", "abc" );
descriptor.setValue( "someOtherElement", "xyz" );
// Step 2: create the annotation from its descriptor.
TestAnnotation ann = AnnotationFactory.create( descriptor );
assertFalse( ann.booleanElement() );
assertEquals( "abc", ann.stringElement() );
}
}

View File

@ -1,108 +0,0 @@
package org.hibernate.annotations.common.test.annotationfactory;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor;
import org.hibernate.annotations.common.annotationfactory.AnnotationProxy;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
public class AnnotationProxyTest extends TestCase {
private AnnotationProxy ann;
private AnnotationDescriptor descriptor;
public void setUp() {
descriptor = new AnnotationDescriptor( TestAnnotation.class );
descriptor.setValue( "stringElement", "x" );
descriptor.setValue( "booleanElement", false );
descriptor.setValue( "someOtherElement", "y" );
ann = new AnnotationProxy( descriptor );
}
public void testConstructionFailsIfYouDoNotAssignValuesToAllTheElementsWithoutADefault() {
try {
AnnotationDescriptor desc = new AnnotationDescriptor( TestAnnotation.class );
desc.setValue( "stringElement", "x" );
desc.setValue( "booleanElement", false );
new AnnotationProxy( desc );
fail();
}
catch (Exception e) {
assertEquals( "No value provided for someOtherElement", e.getMessage() );
}
}
public void testConstructionFailsIfYouDefineElementsThatAreNotInTheAnnotationInterface() {
try {
AnnotationDescriptor desc = new AnnotationDescriptor( Deprecated.class );
desc.setValue( "wrongElement", "xxx" );
new AnnotationProxy( desc );
fail();
}
catch (Exception e) {
assertTrue( e.getMessage().contains( "unknown elements" ) );
}
}
public void testSupportsGenericCallsToAllElements() throws Throwable {
assertEquals( "x", invoke( ann, "stringElement" ) );
assertFalse( (Boolean) invoke( ann, "booleanElement" ) );
}
public void testPretendsThatItHasTheGivenType() {
assertSame( TestAnnotation.class, ann.annotationType() );
}
public void testItsToStringConformsToTheJavaAnnotationDocumentation() throws Throwable {
String expectedString = "@org.hibernate.annotations.common.test.annotationfactory.TestAnnotation(booleanElement=false, elementWithDefault=abc, someOtherElement=y, stringElement=x)";
assertEquals( expectedString, invoke( ann, "toString" ) );
}
public void testSupportsGenericCallsToMethods() throws Throwable {
assertEquals( ann.annotationType(), invoke( ann, "annotationType" ) );
assertEquals( ann.toString(), invoke( ann, "toString" ) );
}
public void testThrowsARuntimeExceptionIfYouUseAnElementWhichIsNotInTheAnnotationInterface() {
AnnotationDescriptor elements = new AnnotationDescriptor( TestAnnotation.class );
elements.setValue( "anOddElement", "x" );
try {
new AnnotationProxy( elements );
fail();
}
catch (RuntimeException e) {
}
}
public void testUsesTheDefaultValueForUndefinedElementsWhenAvailable() throws Throwable {
assertEquals( "abc", invoke( ann, "elementWithDefault" ) );
}
public void testThrowsANoSuchMethodExceptionWhenAccessingAnUndefinedMethod() throws Throwable {
try {
invoke( ann, "anElementThatDoesNotExist" );
fail();
}
catch (NoSuchMethodException e) {
}
try {
invoke( ann, "anOddElement", "arg1", "arg2" );
fail();
}
catch (NoSuchMethodException e) {
}
}
private Object invoke(AnnotationProxy proxy, String methodName, Object... args) throws Throwable {
Class[] parameterTypes = new Class[args.length];
for ( int i = 0; i < args.length ; i++ ) {
parameterTypes[i] = args[i].getClass();
}
Method method = TestAnnotation.class.getMethod( methodName, parameterTypes );
return proxy.invoke( proxy, method, parameterTypes );
}
}

View File

@ -1,18 +0,0 @@
/**
*
*/
package org.hibernate.annotations.common.test.annotationfactory;
/**
* @author Paolo Perrotta
* @author Davide Marchignoli
*/
@interface TestAnnotation {
String stringElement();
String elementWithDefault() default "abc";
boolean booleanElement();
String someOtherElement();
}

View File

@ -1,31 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java;
import java.util.List;
/**
* @author Paolo Perrotta
*/
@TestAnnotation(name = "xyz")
public class Foo extends FooFather {
public static Integer staticField;
Integer fieldProperty;
public List<String> getCollectionProperty() {
return null;
}
@TestAnnotation(name = "xyz")
public Integer getMethodProperty() {
return null;
}
public int getPrimitiveProperty() {
return 0;
}
public static Integer getStaticThing() {
return null;
}
}

View File

@ -1,23 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java;
import java.util.List;
/**
* @author Paolo Perrotta
*/
public abstract class FooFather<T> {
public Integer fatherField;
public Boolean isFatherMethod() {
return null;
}
public T getParameterizedProperty() {
return null;
}
public List<T> getParameterizedCollectionProperty() {
return null;
}
}

View File

@ -1,41 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
/**
* @author Paolo Perrotta
*/
public class JavaReflectionManagerTest extends TestCase {
private ReflectionManager rm = new JavaReflectionManager();
public void testReturnsAnXClassThatWrapsTheGivenClass() {
XClass xc = rm.toXClass( Integer.class );
assertEquals( "java.lang.Integer", xc.getName() );
}
public void testReturnsSameXClassForSameClass() {
XClass xc1 = rm.toXClass( void.class );
XClass xc2 = rm.toXClass( void.class );
assertSame( xc2, xc1 );
}
public void testReturnsNullForANullClass() {
assertNull( rm.toXClass( null ) );
}
public void testComparesXClassesWithClasses() {
XClass xc = rm.toXClass( Integer.class );
assertTrue( rm.equals( xc, Integer.class ) );
}
public void testSupportsNullsInComparisons() {
XClass xc = rm.toXClass( Integer.class );
assertFalse( rm.equals( null, Number.class ) );
assertFalse( rm.equals( xc, null ) );
assertTrue( rm.equals( null, null ) );
}
}

View File

@ -1,90 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java;
import java.io.Serializable;
import java.util.List;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XAnnotatedElement;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
import org.hibernate.annotations.common.test.reflection.java.generics.Dad;
import org.hibernate.annotations.common.test.reflection.java.generics.Grandpa;
import org.hibernate.annotations.common.test.reflection.java.generics.Language;
import org.hibernate.annotations.common.test.reflection.java.generics.Son;
/**
* @author Paolo Perrotta
*/
public class JavaXClassTest extends XAnnotatedElementTestCase {
ReflectionManager factory = new JavaReflectionManager();
XClass fatherAsSeenFromSon = factory.toXClass( Son.class ).getSuperclass();
XClass grandpa = factory.toXClass( Grandpa.class );
public void testHasAPointOfViewClass() {
// Since Dad is an Entity, getting it through Son.getSuperclass() gives
// us a view of properties from Dad with Son as a point of view.
XClass sameView = factory.toXClass( Son.class ).getSuperclass();
XClass differentView = factory.toXClass( Dad.class );
assertSame( "Should be the same instance: same owner", sameView, fatherAsSeenFromSon );
assertNotSame( "Should be a different instance: different owner", differentView, fatherAsSeenFromSon );
assertEquals( ".equals() should show equality", sameView, differentView );
}
public void testHasAName() {
assertSame( "org.hibernate.annotations.common.test.reflection.java.generics.Dad", fatherAsSeenFromSon.getName() );
}
public void testHasASuperclass() {
assertEquals( grandpa, fatherAsSeenFromSon.getSuperclass() );
}
public void testSuperSuperClass() {
assertEquals( factory.toXClass( Object.class ), grandpa.getSuperclass() );
assertEquals( null, grandpa.getSuperclass().getSuperclass() );
}
public void testHasInterfaces() {
XClass[] interfaces = fatherAsSeenFromSon.getSuperclass().getInterfaces();
assertEquals( 2, interfaces.length );
assertTrue( factory.equals( interfaces[0], Serializable.class ) );
assertTrue( factory.equals( interfaces[1], Language.class ) );
}
public void testCanBeAssignableFromAnotherXClass() {
assertFalse( fatherAsSeenFromSon.isAssignableFrom( grandpa ) );
assertTrue( grandpa.isAssignableFrom( fatherAsSeenFromSon ) );
}
public void testExtractsPublicFieldsAsProperties() {
List<XProperty> fieldProperties = fatherAsSeenFromSon.getDeclaredProperties( "field" );
assertEquals( 1, fieldProperties.size() );
}
public void testExtractsPublicMethodsAsProperties() {
List<XProperty> methodProperties = fatherAsSeenFromSon.getDeclaredProperties( "property" );
assertEquals( 9, methodProperties.size() );
}
public void testCanBeAbstract() {
assertFalse( fatherAsSeenFromSon.isAbstract() );
assertTrue( factory.toXClass( Grandpa.class ).isAbstract() );
}
public void testCanBeAPrimitive() {
assertFalse( fatherAsSeenFromSon.isPrimitive() );
assertTrue( factory.toXClass( int.class ).isPrimitive() );
}
public void testCanBeAnEnum() {
assertFalse( fatherAsSeenFromSon.isEnum() );
assertTrue( factory.toXClass( Sex.class ).isEnum() );
}
@Override
protected XAnnotatedElement getConcreteInstance() {
return factory.toXClass( Dad.class );
}
}

View File

@ -1,166 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import junit.framework.AssertionFailedError;
import org.hibernate.annotations.common.reflection.Filter;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
import org.hibernate.annotations.common.test.reflection.java.generics.Dad;
import org.hibernate.annotations.common.test.reflection.java.generics.Son;
/**
* @author Paolo Perrotta
*/
public class JavaXPropertyTest extends XAnnotatedElementTestCase {
private ReflectionManager factory = new JavaReflectionManager();
private XClass dadAsSeenFromItself = factory.toXClass( Dad.class );
private XClass dadAsSeenFromSon = factory.toXClass( Son.class ).getSuperclass();
public void testFollowsJavaBeansConventionsForPropertyNames() throws Exception {
List<String> properties = new LinkedList<String>();
properties.add( "collectionProperty" );
properties.add( "methodProperty" );
properties.add( "primitiveProperty" );
properties.add( "primitiveArrayProperty" );
properties.add( "arrayProperty" );
properties.add( "genericCollectionProperty" );
properties.add( "nongenericCollectionProperty" );
properties.add( "propertyStartingWithIs" );
properties.add( "language" );
List<XProperty> methodProperties = dadAsSeenFromSon.getDeclaredProperties( "property" );
assertEquals( properties.size(), methodProperties.size() );
for ( XProperty member : methodProperties ) {
assertTrue( properties.contains( member.getName() ) );
}
List<XProperty> fieldProperties = dadAsSeenFromSon.getDeclaredProperties( "field" );
XProperty field = fieldProperties.get( 0 );
assertEquals( "fieldProperty", field.getName() );
}
public void testReturnsPropertiesWithUnresolvedParametricTypes() {
assertEquals( 9, dadAsSeenFromItself.getDeclaredProperties( "property" ).size() );
}
public void testKnowsWhetherItsTypeIsFullyResolved() {
XProperty notFullyResolvedProperty = getPropertyNamed_from(
"collectionProperty", dadAsSeenFromItself
.getDeclaredProperties( "property" )
);
assertFalse( notFullyResolvedProperty.isTypeResolved() );
XProperty fullyResolvedProperty = getPropertyNamed_from(
"collectionProperty", dadAsSeenFromSon
.getDeclaredProperties( "property" )
);
assertTrue( fullyResolvedProperty.isTypeResolved() );
}
public void testCanBeFiltered() {
assertEquals(
10, dadAsSeenFromSon.getDeclaredProperties(
"property", new Filter() {
public boolean returnStatic() {
return true;
}
public boolean returnTransient() {
return false;
}
}
).size()
);
}
public void testCanBeASimpleType() {
List<XProperty> declaredProperties = dadAsSeenFromSon.getDeclaredProperties( "field" );
XProperty p = getPropertyNamed_from( "fieldProperty", declaredProperties );
assertTrue( factory.equals( p.getType(), String.class ) );
assertTrue( factory.equals( p.getElementClass(), String.class ) );
assertTrue( factory.equals( p.getClassOrElementClass(), String.class ) );
assertNull( p.getCollectionClass() );
assertFalse( p.isArray() );
assertFalse( p.isCollection() );
}
public void testResolveInterfaceType() {
List<XProperty> declaredProperties = dadAsSeenFromSon.getDeclaredProperties( "property" );
XProperty p = getPropertyNamed_from( "language", declaredProperties );
assertTrue( factory.equals( p.getType(), String.class ) );
assertTrue( factory.equals( p.getElementClass(), String.class ) );
assertTrue( factory.equals( p.getClassOrElementClass(), String.class ) );
assertNull( p.getCollectionClass() );
assertNull( p.getMapKey() );
assertFalse( p.isArray() );
assertFalse( p.isCollection() );
}
public void testCanBeAnArray() {
List<XProperty> declaredProperties = dadAsSeenFromSon.getDeclaredProperties( "property" );
XProperty p = getPropertyNamed_from( "arrayProperty", declaredProperties );
assertTrue( factory.equals( p.getType(), String[].class ) );
assertTrue( factory.equals( p.getElementClass(), String.class ) );
assertTrue( factory.equals( p.getClassOrElementClass(), String.class ) );
assertNull( p.getCollectionClass() );
assertNull( p.getMapKey() );
assertTrue( p.isArray() );
assertFalse( p.isCollection() );
}
public void testCanBeAnArrayOfPrimitives() {
List<XProperty> declaredProperties = dadAsSeenFromSon.getDeclaredProperties( "property" );
XProperty p = getPropertyNamed_from( "primitiveArrayProperty", declaredProperties );
assertTrue( factory.equals( p.getType(), int[].class ) );
assertTrue( factory.equals( p.getElementClass(), int.class ) );
assertTrue( factory.equals( p.getClassOrElementClass(), int.class ) );
assertNull( p.getCollectionClass() );
assertNull( p.getMapKey() );
assertTrue( p.isArray() );
assertFalse( p.isCollection() );
}
public void testCanBeACollection() {
List<XProperty> declaredProperties = dadAsSeenFromSon.getDeclaredProperties( "property" );
XProperty p = getPropertyNamed_from( "collectionProperty", declaredProperties );
assertTrue( factory.equals( p.getType(), Map.class ) );
assertTrue( factory.equals( p.getElementClass(), String.class ) );
assertTrue( factory.equals( p.getClassOrElementClass(), Map.class ) );
assertTrue( factory.equals( p.getMapKey(), Double.class ) );
assertEquals( Map.class, p.getCollectionClass() );
assertFalse( p.isArray() );
assertTrue( p.isCollection() );
}
private XProperty getPropertyNamed_from(String name, List<XProperty> properties) {
for ( XProperty p : properties ) {
if ( p.getName().equals( name ) ) {
return p;
}
}
throw new AssertionFailedError( "No property '" + name + "' found" );
}
public void testSupportsMethodsStartingWithIs() throws Exception {
assertEquals( "methodProperty", getConcreteInstance().getName() );
}
@Override
protected XProperty getConcreteInstance() {
XClass xClass = factory.toXClass( Dad.class );
List<XProperty> properties = xClass.getDeclaredProperties( "property" );
for ( XProperty p : properties ) {
if ( p.getName().equals( "methodProperty" ) ) {
return p;
}
}
throw new AssertionFailedError( "Cannot find Foo.getMethodProperty()" );
}
}

View File

@ -1,10 +0,0 @@
//$Id: $
package org.hibernate.annotations.common.test.reflection.java;
/**
* @author Emmanuel Bernard
*/
public enum Sex {
MALE,
FEMALE
}

View File

@ -1,12 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java;
import static java.lang.annotation.ElementType.*;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface TestAnnotation {
String name() default "abc";
}

View File

@ -1,23 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.XAnnotatedElement;
import org.hibernate.annotations.common.test.reflection.java.generics.TestAnnotation;
/**
* @author Paolo Perrotta
*/
public abstract class XAnnotatedElementTestCase extends TestCase {
public void testKnowsWhetherAnAnnotationIsPresent() {
assertTrue( getConcreteInstance().isAnnotationPresent( TestAnnotation.class ) );
assertFalse( getConcreteInstance().isAnnotationPresent( Override.class ) );
}
public void testReturnsSpecificAnnotations() {
TestAnnotation ent = getConcreteInstance().getAnnotation( TestAnnotation.class );
assertEquals( "xyz", ent.name() );
}
protected abstract XAnnotatedElement getConcreteInstance();
}

View File

@ -1,70 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironmentFactory;
public class ApproximatingTypeEnvironmentTest extends TestCase {
TypeEnvironmentFactory teFactory = new TypeEnvironmentFactory();
TypeEnvironment unboundContext = teFactory.getEnvironment( BigBlob.class );
TypeEnvironment approximatingUnboundContext = teFactory.toApproximatingEnvironment( unboundContext );
TypeEnvironment boundContext = teFactory.getEnvironment( SonOfBlob.class );
TypeEnvironment approximatingBoundContext = teFactory.toApproximatingEnvironment( boundContext );
public void testDoesNothingOnClasses() throws SecurityException {
assertEquals( String[].class, approximatingUnboundContext.bind( String[].class ) );
}
public void testDoesNothingOnWildcards() throws Exception {
Type type = BigBlob.class.getMethod( "genericClass", new Class[0] ).getGenericReturnType();
Type approxType = approximatingBoundContext.bind( type );
assertEquals( "java.lang.Class<?>", approxType.toString() );
}
public void testDoesNothingOnParameterizedTypesThatAreAlreadyFullyBound() throws Exception {
Type type = BigBlob.class.getMethod( "simpleGenericType", new Class[0] ).getGenericReturnType();
assertEquals( boundContext.bind( type ), approximatingBoundContext.bind( type ) );
}
public void testDoesNothingOnComplexParameterizedTypesThatAreNotCollections() throws Exception {
Type type = BigBlob.class.getMethod( "genericType", new Class[0] ).getGenericReturnType();
assertEquals( boundContext.bind( type ), approximatingBoundContext.bind( type ) );
}
public void testDoesNothingOnGenericArraysThatAreAlreadyFullyBound() throws Exception {
Type type = BigBlob.class.getMethod( "array", new Class[0] ).getGenericReturnType();
assertEquals( boundContext.bind( type ), approximatingBoundContext.bind( type ) );
}
public void testApproximatesSimpleGenericTypesToTheirUpperBound() throws Exception {
Type type = BigBlob.class.getMethod( "simpleGenericType", new Class[0] ).getGenericReturnType();
assertEquals( "java.util.List<java.lang.String>", approximatingBoundContext.bind( type ).toString() );
}
public void testApproximatesGenericsInArraysToTheirUpperBounds() throws Exception {
Type type = BigBlob.class.getMethod( "array", new Class[0] ).getGenericReturnType();
assertEquals( Collection[].class, approximatingUnboundContext.bind( type ) );
}
public void testApproximatesArraysOfComplexTypesToArraysOfObjects() throws Exception {
Type type = BigBlob.class.getMethod( "complexGenericArray", new Class[0] ).getGenericReturnType();
assertEquals( Object[].class, approximatingUnboundContext.bind( type ) );
}
public void testApproximatesGenericsAndWildcardsInCollectionsToTheirUpperBounds() throws Exception {
Type type = BigBlob.class.getMethod( "genericCollection", new Class[0] ).getGenericReturnType();
ParameterizedType approxType = (ParameterizedType) approximatingUnboundContext.bind( type );
assertEquals( Map.class, approxType.getRawType() );
assertNull( approxType.getOwnerType() );
assertEquals( 2, approxType.getActualTypeArguments().length );
assertEquals( Object.class, approxType.getActualTypeArguments()[0] );
assertEquals( Collection.class, approxType.getActualTypeArguments()[1] );
}
}

View File

@ -1,32 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class BigBlob<T, E extends Collection> {
public E simpleGenericType() {
return null;
}
public Class<?> genericClass() {
return null;
}
public Class<T> genericType() {
return null;
}
public Map<T, ? extends E> genericCollection() {
return null;
}
public E[] array() {
return null;
}
public List<? extends T>[] complexGenericArray() {
return null;
}
}

View File

@ -1,57 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.util.List;
import java.util.Map;
/**
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
@TestAnnotation(name = "xyz")
public class Dad<T> extends Grandpa<List<T>, Integer> {
static Integer staticField;
T fieldProperty;
public Map<Double, T> getCollectionProperty() {
return null;
}
@TestAnnotation(name = "xyz")
public Integer getMethodProperty() {
return null;
}
public int getPrimitiveProperty() {
return 0;
}
public boolean isPropertyStartingWithIs() {
return false;
}
public int[] getPrimitiveArrayProperty() {
return null;
}
public T[] getArrayProperty() {
return null;
}
public List<T> getGenericCollectionProperty() {
return null;
}
public List<String> getNongenericCollectionProperty() {
return null;
}
public static Integer getStaticThing() {
return null;
}
public String getLanguage() {
return null;
}
}

View File

@ -1,21 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.io.Serializable;
/**
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public abstract class Grandpa<T, U> implements Serializable, Language<String> {
Integer grandpaField;
public T returnsGeneric() {
return null;
}
// generic embedded value
public Neighbour<U> getFriend() {
return null;
}
}

View File

@ -1,9 +0,0 @@
//$Id$
package org.hibernate.annotations.common.test.reflection.java.generics;
/**
* @author Emmanuel Bernard
*/
public interface Language<T> {
T getLanguage();
}

View File

@ -1,14 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.util.Set;
/**
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public class Neighbour<T> {
public Set<T> embeddedProperty() {
return null;
}
}

View File

@ -1,8 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
/**
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public class Son extends Dad<String> {
}

View File

@ -1,8 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.util.List;
public class SonOfBlob extends BigBlob<String, List<String>> {
}

View File

@ -1,16 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import static java.lang.annotation.ElementType.*;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface TestAnnotation {
String name() default "abc";
}

View File

@ -1,59 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironmentFactory;
/**
* @author Davide Marchignoli
* @author Paolo Perrotta
*/
public class TypeEnvironmentFactoryTest extends TestCase {
public void testBindsGenericsToSuperclassEnvironment() throws SecurityException, NoSuchMethodException {
TypeEnvironmentFactory env = new TypeEnvironmentFactory();
Type type = Grandpa.class.getMethod( "returnsGeneric", new Class[0] ).getGenericReturnType();
Type asSeenFromGrandpa = env.getEnvironment( Grandpa.class ).bind( type );
assertTrue( asSeenFromGrandpa instanceof TypeVariable );
assertEquals( "T", asSeenFromGrandpa.toString() );
Type asSeenFromDad = env.getEnvironment( Dad.class ).bind( type );
assertTrue( asSeenFromDad instanceof ParameterizedType );
assertEquals( "java.util.List<T>", asSeenFromDad.toString() );
ParameterizedType asSeenFromSon = (ParameterizedType) env.getEnvironment( Son.class ).bind( type );
assertType_isCollectionOfClass_withElementsOfClass( asSeenFromSon, List.class, String.class );
}
public void testBindsGenericsToOwnerEnvironment() throws SecurityException, NoSuchMethodException {
TypeEnvironmentFactory env = new TypeEnvironmentFactory();
Type friendType = Dad.class.getMethod( "getFriend", new Class[0] ).getGenericReturnType();
ParameterizedType friendTypeAsSeenFromDad = (ParameterizedType) env.getEnvironment( Dad.class ).bind(
friendType
);
Class friendClass = (Class) friendTypeAsSeenFromDad.getRawType();
Type returnType = friendClass.getMethod( "embeddedProperty", new Class[0] ).getGenericReturnType();
ParameterizedType boundType = (ParameterizedType) env.getEnvironment( friendTypeAsSeenFromDad ).bind(
returnType
);
assertType_isCollectionOfClass_withElementsOfClass( boundType, Set.class, Integer.class );
}
private void assertType_isCollectionOfClass_withElementsOfClass(
ParameterizedType t, Class collectionClass,
Class elementClass
) {
assertEquals( collectionClass, t.getRawType() );
assertEquals( 1, t.getActualTypeArguments().length );
assertEquals( elementClass, t.getActualTypeArguments()[0] );
}
}

View File

@ -1,43 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics;
import java.lang.reflect.Type;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironment;
import org.hibernate.annotations.common.reflection.java.generics.TypeEnvironmentFactory;
import org.hibernate.annotations.common.reflection.java.generics.TypeUtils;
public class TypeUtilsTest extends TestCase {
TypeEnvironmentFactory env = new TypeEnvironmentFactory();
TypeEnvironment dadContext = env.getEnvironment( Dad.class );
TypeEnvironment sonContext = env.getEnvironment( Son.class );
public void testAClassIsAlwaysFullyResolved() throws Exception {
assertTrue( TypeUtils.isResolved( Dad.class ) );
}
private Type getPropertyFromDad(String propertyName) throws NoSuchMethodException {
return Dad.class.getMethod( propertyName, new Class[0] ).getGenericReturnType();
}
public void testKnowsWhetherAParametricTypeIsFullyResolved() throws Exception {
Type simpleType = getPropertyFromDad( "returnsGeneric" );
assertFalse( TypeUtils.isResolved( dadContext.bind( simpleType ) ) );
assertTrue( TypeUtils.isResolved( sonContext.bind( simpleType ) ) );
}
public void testKnowsWhetherAnArrayTypeIsFullyResolved() throws Exception {
Type arrayType = getPropertyFromDad( "getArrayProperty" );
assertFalse( TypeUtils.isResolved( dadContext.bind( arrayType ) ) );
assertTrue( TypeUtils.isResolved( sonContext.bind( arrayType ) ) );
}
public void testKnowsWhetherATypeIsSimple() throws Exception {
assertTrue( TypeUtils.isSimple( String.class ) );
assertFalse( TypeUtils.isSimple( new String[1].getClass() ) );
assertFalse( TypeUtils.isSimple( getPropertyFromDad( "getNongenericCollectionProperty" ) ) );
assertFalse( TypeUtils.isSimple( getPropertyFromDad( "getGenericCollectionProperty" ) ) );
}
}

View File

@ -1,33 +0,0 @@
//$Id: $
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import java.util.List;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
/**
* @author Paolo Perrotta
*/
public class ANN612IssueTest extends TestCase {
public static class J<T> {}
public static class C {
public J<Object> thisOneAlwaysWorkedFine;
public J<Object[]> thisOneUsedToCauseProblems;
}
public void testANN612IssueIsFixed() throws Exception {
JavaReflectionManager factory = new JavaReflectionManager();
XClass clazz = factory.toXClass( C.class );
List<XProperty> properties = clazz.getDeclaredProperties( XClass.ACCESS_FIELD );
for( XProperty property : properties )
assertTrue( property.isTypeResolved() );
}
}

View File

@ -1,48 +0,0 @@
//$Id: $
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import java.util.List;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
/**
* @author Paolo Perrotta
*/
public class DeepGenericsContainment extends TestCase {
public static class Contained<T> {
T generic;
}
public static class Container {
Contained<String> contained;
}
public static class ContainerWithCollection {
List<Contained<String>> contained;
}
public void test2StepsGenerics() throws Exception {
JavaReflectionManager factory = new JavaReflectionManager();
XClass container = factory.toXClass( Container.class );
XProperty contained = container.getDeclaredProperties( XClass.ACCESS_FIELD ).get( 0 );
assertTrue( contained.isTypeResolved() );
XProperty generic = contained.getType().getDeclaredProperties( XClass.ACCESS_FIELD ).get( 0 );
assertTrue( generic.isTypeResolved() );
}
public void test2StepsGenericsCollection() throws Exception {
JavaReflectionManager factory = new JavaReflectionManager();
XClass container = factory.toXClass( ContainerWithCollection.class );
XProperty collection = container.getDeclaredProperties( XClass.ACCESS_FIELD ).get( 0 );
assertTrue( collection.isTypeResolved() );
XClass elementClass = collection.getElementClass();
XProperty generic = elementClass.getDeclaredProperties( XClass.ACCESS_FIELD ).get( 0 );
assertTrue( generic.isTypeResolved() );
}
}

View File

@ -1,23 +0,0 @@
//$Id: $
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import junit.framework.TestCase;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
import org.hibernate.annotations.common.reflection.XClass;
/**
* @author Emmanuel Bernard
*/
public class DeepGenericsInheritance extends TestCase {
public void test2StepsGenerics() throws Exception {
JavaReflectionManager factory = new JavaReflectionManager();
XClass subclass2 = factory.toXClass( Subclass2.class );
XClass dummySubclass = factory.toXClass( DummySubclass.class );
XClass superclass = subclass2.getSuperclass();
XClass supersuperclass = superclass.getSuperclass();
assertTrue( supersuperclass.getDeclaredProperties( "field" ).get( 1 ).isTypeResolved() );
assertEquals( dummySubclass, supersuperclass.getDeclaredProperties( "field" ).get( 1 ).getType() );
}
}

View File

@ -1,20 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
public class Dummy {
protected Long id;
private String name;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,6 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.Dummy;
public class DummySubclass extends Dummy {
}

View File

@ -1,18 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.Dummy;
public class GenericSuperclass1<T extends Dummy> {
protected Long id;
protected T dummy;
public Long getId() {
return id;
}
public T getDummy() {
return dummy;
}
}

View File

@ -1,7 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.Dummy;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.GenericSuperclass1;
public class GenericSuperclass2<T extends Dummy> extends GenericSuperclass1<T> {
}

View File

@ -1,7 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.DummySubclass;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.GenericSuperclass1;
public class Subclass1 extends GenericSuperclass1<DummySubclass> {
}

View File

@ -1,7 +0,0 @@
package org.hibernate.annotations.common.test.reflection.java.generics.deep;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.DummySubclass;
import org.hibernate.annotations.common.test.reflection.java.generics.deep.GenericSuperclass2;
public class Subclass2 extends GenericSuperclass2<DummySubclass> {
}