Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2007 Daniel Spiewak
   * 
   * Licensed under the Apache License, Version 2.0 (the "License"); 
   * you may not use this file except in compliance with the License. 
   * You may obtain a copy of the License at
   * 
   *	    http://www.apache.org/licenses/LICENSE-2.0 
   * 
  * Unless required by applicable law or agreed to in writing, software 
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package net.java.ao;
 
 import java.sql.Types;
 import java.util.List;
 import java.util.Set;
 
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.collect.Lists.newArrayList;

WARNING: Not part of the public API. This class is public only to allow its use within other packages in the ActiveObjects library.

Author(s):
Daniel Spiewak
 
 public final class Common {
 
     public static <T extends RawEntity<K>, K> T createPeer(EntityManager managerClass<T> type, K keythrows SQLException
     {
         return manager.peer(manager.resolveEntityInfo(type), key);
     }
 
 	public static String convertSimpleClassName(String name) {
 		String[] array = name.split("\\.");
 		return array[array.length - 1];
 	}
 
 	public static String convertDowncaseName(String name) {
 		StringBuilder back = new StringBuilder();
 
 		back.append(Character.toLowerCase(name.charAt(0)));
 		back.append(name.substring(1));
 
 		return back.toString();
 	}

    

See also:
AO-325
 
     @Deprecated
     public static String[] getMappingFields(FieldNameConverter converterClass<? extends RawEntity<?>> fromClass<? extends RawEntity<?>> to)
     {
 		Set<Stringback = new LinkedHashSet<String>();
 
 		for (Method method : from.getMethods()) {
 			Class<?> attributeType = getAttributeTypeFromMethod(method);
 
 			if (attributeType == null) {
 				continue;
 			}
 
             if (to.isAssignableFrom(attributeType)) {
 				back.add(converter.getName(method));
 			} else if (attributeType.getAnnotation(Polymorphic.class) != null
 					&& attributeType.isAssignableFrom(to)) {
 				back.add(converter.getName(method));
			}
		}
		return back.toArray(new String[back.size()]);
	}

    

See also:
AO-325
    @Deprecated
    public static String[] getPolymorphicFieldNames(FieldNameConverter converterClass<? extends RawEntity<?>> from,
			Class<? extends RawEntity<?>> to) {
		Set<Stringback = new LinkedHashSet<String>();
		for (Method method : from.getMethods()) {
			Class<?> attributeType = getAttributeTypeFromMethod(method);
            if (attributeType != null && attributeType.isAssignableFrom(to)
					&& attributeType.getAnnotation(Polymorphic.class) != null) {
				back.add(converter.getPolyTypeName(method));
			}
		}
		return back.toArray(new String[back.size()]);
	}

Note: this method leads to the creation and quick discard of large numbers of AnnotationDelegate objects. Need to do some research to determine whether or not this is actually a problem.

Deprecated:
All annotation information should be resolved upfront using net.java.ao.schema.info.EntityInfo
    @Deprecated
	public static AnnotationDelegate getAnnotationDelegate(FieldNameConverter converterMethod method) {
		return new AnnotationDelegate(methodfindCounterpart(convertermethod));
	}

Finds the corresponding method in an accessor/mutator pair based on the given method (or null if no corresponding method).

Parameters:
converter TODO
	private static Method findCounterpart(FieldNameConverter converterMethod method) {
        return MethodFinder.getInstance().findCounterPartMethod(convertermethod);
	}
    public static boolean isMutator(Method method)
    {
        return (isAnnotatedMutator(method) || isNamedAsSetter(method)) && isValidMutator(method);
    }
    public static boolean isAnnotatedMutator(Method method)
    {
        return method.isAnnotationPresent(Mutator.class);
    }
    private static boolean isNamedAsSetter(Method method)
    {
        return method.getName().startsWith("set");
    }
    private static boolean isValidMutator(Method method)
    {
        return method.getReturnType() == . && method.getParameterTypes().length == 1;
    }
    public static boolean isAccessor(Method method)
    {
        return (isAnnotatedAccessor(method) || isNamedAsGetter(method)) && isValidAccessor(method);
    }
    private static boolean isAnnotatedAccessor(Method method)
    {
        return method.isAnnotationPresent(Accessor.class);
    }
    private static boolean isNamedAsGetter(Method method)
    {
        return method.getName().startsWith("get")
                || method.getName().startsWith("is");
    }
    private static boolean isValidAccessor(Method method)
    {
        return method.getReturnType() != . && method.getParameterTypes().length == 0;
    }
    public static boolean isAnnotatedAsRelational(Method method)
    {
        return method.isAnnotationPresent(OneToOne.class)
                || method.isAnnotationPresent(OneToMany.class)
                || method.isAnnotationPresent(ManyToMany.class);
    }
    public static Class<?> getAttributeTypeFromMethod(Method method)
    {
        if (isAnnotatedAsRelational(method))
        {
            return null;
        }
        if (isMutator(method))
        {
            return getMutatorParameterType(method);
        }
        if (isAccessor(method))
        {
            return getAccessorReturnType(method);
        }
        return null;
    }
    private static Class<?> getMutatorParameterType(Method method)
    {
        checkArgument(isValidMutator(method), "Method '%s' on class '%s' is not a valid mutator"method.getName(), method.getDeclaringClass().getCanonicalName());
        return method.getParameterTypes()[0];
    }
    private static Class<?> getAccessorReturnType(Method method)
    {
        checkArgument(isValidAccessor(method), "Method '%s' on class '%s' is not a valid accessor"method.getName(), method.getDeclaringClass().getCanonicalName());
        return method.getReturnType();
    }
    public static String getCallingClassName(int depth) {
        StackTraceElement[] stack = new Exception().getStackTrace();
        return stack[depth + 2].getClassName();
    }
	public static List<StringgetSearchableFields(EntityManager managerClass<? extends RawEntity<?>> type) {
		List<Stringback = new ArrayList<String>();
		for (Method m : type.getMethods()) {
			if (annot != null) {
				Class<?> attributeType = Common.getAttributeTypeFromMethod(m);
				// don't index Entity fields
                if (name != null && !RawEntity.class.isAssignableFrom(attributeType) && !back.contains(name)) {
					back.add(name);
				}
			}
		}
		return back;
	}
    private static Method getPrimaryKeyAccessor(Class<? extends RawEntity<?>> type)
    {
        final Iterable<Methodmethods = MethodFinder.getInstance().findAnnotatedMethods(PrimaryKey.classtype);
        if (Iterables.isEmpty(methods))
        {
            throw new RuntimeException("Entity " + type.getSimpleName() + " has no primary key field");
        }
        for (Method method : methods)
        {
            if (!method.getReturnType().equals(.) && method.getParameterTypes().length == 0)
            {
                return method;
            }
        }
        return null;
    }
    public static String getPrimaryKeyField(Class<? extends RawEntity<?>> typeFieldNameConverter converter)
    {
        final Iterable<Methodmethods = MethodFinder.getInstance().findAnnotatedMethods(PrimaryKey.classtype);
        if (Iterables.isEmpty(methods))
        {
            throw new RuntimeException("Entity " + type.getSimpleName() + " has no primary key field");
        }
        return converter.getName(methods.iterator().next());
    }
    public static <K> TypeInfo<K> getPrimaryKeyType(TypeManager typeManagerClass<? extends RawEntity<K>> type) {
		return typeManager.getType(getPrimaryKeyClassType(type));
	}
    public static <K> Class<K> getPrimaryKeyClassType(Class<? extends RawEntity<K>> type)
    {
        final Iterable<Methodmethods = MethodFinder.getInstance().findAnnotatedMethods(PrimaryKey.classtype);
        if (Iterables.isEmpty(methods))
        {
            throw new RuntimeException("Entity " + type.getSimpleName() + " has no primary key field");
        }
        final Method m = methods.iterator().next();
        Class<K> keyType = (Class<K>) m.getReturnType();
        if (keyType.equals(.))
        {
            keyType = (Class<K>) m.getParameterTypes()[0];
        }
        return keyType;
    }
    public static <K> K getPrimaryKeyValue(RawEntity<K> entity) {
        if (entity instanceof EntityProxyAccessor) {
            return (K) ((EntityProxyAccessorentity).getEntityProxy().getKey();
        }
		try {
			return (K) Common.getPrimaryKeyAccessor(entity.getEntityType()).invoke(entity);
catch (IllegalArgumentException e) {
			return null;
catch (IllegalAccessException e) {
			return null;
catch (InvocationTargetException e) {
			return null;
		}
	}
    public static <K> void validatePrimaryKey(FieldInfo<K> primaryKeyInfoObject value)
    {
        if(null == value)
        {
            throw new IllegalArgumentException("Cannot set primary key to NULL");
        }
        TypeInfo<K> typeInfo = primaryKeyInfo.getTypeInfo();
        Class<K> javaTypeClass = primaryKeyInfo.getJavaType();
        if(!typeInfo.isAllowedAsPrimaryKey())
        {
            throw new ActiveObjectsException(javaTypeClass.getName() + " cannot be used as a primary key!");
        }
        typeInfo.getLogicalType().validate(value);
        if((value instanceof String) && StringUtils.isBlank((String)value))
        {
            throw new ActiveObjectsException("Cannot set primary key to blank String");
        }
    }
	public static boolean fuzzyCompare(TypeManager typeManagerObject aObject b) {
		if (a == null && b == null) {
			return true;
else if (a == null || b == null) {	// implicitly, one or other is null, not both
			return false;
		}
		Object array = null;
		Object other = null;
		if (a.getClass().isArray()) {
			array = a;
			other = b;
else if (b.getClass().isArray()) {
			array = b;
			other = a;
		}
		if (array != null) {
			for (int i = 0; i < Array.getLength(array); i++) {
				if (fuzzyCompare(typeManager, Array.get(arrayi), other)) {
					return true;
				}
			}
		}
		return typeManager.getType(a.getClass()).getLogicalType().valueEquals(ab)
			|| typeManager.getType(b.getClass()).getLogicalType().valueEquals(ba);
	}
	public static boolean fuzzyTypeCompare(int typeAint typeB) {
		if (typeA == .) {
			switch (typeB) {
					return true;
				case .:
					return true;
					return true;
					return true;
					return true;
					return true;
			}
		}
		if ((typeA == . || typeA == . || typeA == . || typeA == .
				|| typeA == . || typeA == .) && typeB == .) {
			return true;
else if (typeA == . && (typeB == . || typeB == .)) {
			return true;
else if ((typeA == . || typeA == .) && typeB == .) {
			return true;
else if ((typeA == . || typeA == . || typeA == . || typeA == .
				|| typeA == . || typeA == . || typeA == . || typeA == .
				|| typeA == .) && typeB == .) {
			return true;
		}
		return typeA == typeB;
	}

    
Gets all the methods of an entity that correspond to a value field. This means fields that are stored as values in the database as opposed to fields (IDs) that define a relationship to another table in the database. Note that the values are retrieved based on the relationship annotations, at the field level, which the user may not have entered.

Parameters:
entity the entity to look up the methods from
converter the field name converter currently in use for entities
Returns:
the set of method found
    public static Set<MethodgetValueFieldsMethods(final Class<? extends RawEntity<?>> entityfinal FieldNameConverter converter)
    {
        return Sets.filter(Sets.newHashSet(entity.getMethods()), new Predicate<Method>()
        {
            public boolean apply(Method m)
            {
                final AnnotationDelegate annotations = getAnnotationDelegate(converterm);
                return !annotations.isAnnotationPresent(Ignore.class)
                        && !annotations.isAnnotationPresent(OneToOne.class)
                        && !annotations.isAnnotationPresent(OneToMany.class)
                        && !annotations.isAnnotationPresent(ManyToMany.class);
            }
        });
    }

    
Gets all the names of fields of an entity that correspond to a value field. This means fields that are stored as values in the database as opposed to fields (IDs) that define a relationship to another table in the database.

Parameters:
entityInfo the entity to look up the methods from
Returns:
the set of names found
    public static ImmutableSet<StringgetValueFieldsNames(final EntityInfo<? extends RawEntity<?>, ?> entityInfofinal FieldNameConverter converter)
    {
        List<StringvalueFieldsNames = new ArrayList<String>();
        for (FieldInfo fieldInfo : entityInfo.getFields())
        {
            // filter out just the value fields - we need to remove any entities from polymorphic relationships
            if (!Entity.class.isAssignableFrom(fieldInfo.getJavaType()))
            {
                // apply the name converter if we have a getter
                if (fieldInfo.hasAccessor())
                {
                    valueFieldsNames.add(converter.getName(fieldInfo.getAccessor()));
                }
            }
        }
        return ImmutableSet.copyOf(valueFieldsNames);
    }
    public static List<StringpreloadValue(Preload preloadfinal FieldNameConverter fnc)
    {
        final List<Stringvalue = newArrayList(preload.value());
        if (fnc instanceof FieldNameProcessor)
        {
            return Lists.transform(valuenew Function<StringString>()
            {
                @Override
                public String apply(String from)
                {
                    return ((FieldNameProcessorfnc).convertName(from);
                }
            });
        }
        else
        {
            return value;
        }
    }
    public static String where(OneToOne oneToOnefinal FieldNameConverter fnc)
    {
        return where(oneToOne.where(), fnc);
    }
    public static String where(OneToMany oneToManyfinal FieldNameConverter fnc)
    {
        return where(oneToMany.where(), fnc);
    }
    public static String where(ManyToMany manyToManyfinal FieldNameConverter fnc)
    {
        return where(manyToMany.where(), fnc);
    }
    private static String where(String wherefinal FieldNameConverter fnc)
    {
        if (fnc instanceof FieldNameProcessor)
        {
            final Matcher matcher = ..matcher(where);
            final StringBuffer sb = new StringBuffer();
            while (matcher.find())
            {
                matcher.appendReplacement(sbconvert(fncmatcher.group(1)));
            }
            matcher.appendTail(sb);
            return sb.toString();
        }
        else
        {
            return where;
        }
    }
    public static String convert(FieldNameConverter fncString column)
    {
        if (fnc instanceof FieldNameProcessor)
        {
            return ((FieldNameProcessorfnc).convertName(column);
        }
        else
        {
            return column;
        }
    }

    
Closes the java.sql.ResultSet in a null safe manner and quietly, i.e without throwing nor logging any exception

Parameters:
resultSet the result set to close
    @Deprecated
    public static void closeQuietly(ResultSet resultSet)
    {
        if (resultSet != null)
        {
            try
            {
                resultSet.close();
            }
            catch (SQLException e)
            {
                // ignored
            }
        }
    }

    
Closes the java.sql.Statement in a null safe manner and quietly, i.e without throwing nor logging any exception

Parameters:
statement the statement to close
    @Deprecated
    public static void closeQuietly(Statement statement)
    {
        if (statement != null)
        {
            try
            {
                statement.close();
            }
            catch (SQLException e)
            {
                // ignored
            }
        }
    }

    
Closes the java.sql.Connection in a null safe manner and quietly, i.e without throwing nor logging any exception

Parameters:
connection the connection to close, can be null
    @Deprecated
    public static void closeQuietly(Connection connection)
    {
        if (connection != null)
        {
            try
            {
                connection.close();
            }
            catch (SQLException e)
            {
                // ignored
            }
        }
    }

    
Shortens a String to the given length if necessary. The process of shortening is stable.
    public static String shorten(String sint length)
    {
        if (s == null || s.length() <= length)
        {
            return s;
        }
        final int tailLength = length / 3;
        final int hash = Math.abs((int) (s.hashCode() % Math.round(Math.pow(10, tailLength))));
        return s.substring(0, length - tailLength - 1) + hash;
    }
New to GrepCode? Check out our FAQ X