private void CreateIndexes(Configuration config, Collection collection) { if(collection.Element is ManyToOne) { // many-to-many collection // collect all columns that participate in foreign keys HybridSet columns = new HybridSet(); foreach (ForeignKey fk in collection.CollectionTable.ForeignKeyIterator) { CollectionUtils.ForEach(fk.ColumnIterator, delegate(Column col) { columns.Add(col); }); } // there should always be exactly 2 "foreign key' columns in a many-many join table, AFAIK if (columns.Count != 2) { throw new Exception("SNAFU"); } List<Column> indexColumns = new List<Column>(new TypeSafeEnumerableWrapper<Column>(columns)); // create two indexes, each containing both columns, going in both directions CreateIndex(collection.CollectionTable, indexColumns); indexColumns.Reverse(); CreateIndex(collection.CollectionTable, indexColumns); } else { // this is a value collection, or a one-to-many collection // find the foreign-key that refers back to the owner table (assume there is only one of these - is this always true??) ForeignKey foreignKey = CollectionUtils.SelectFirst<ForeignKey>(collection.CollectionTable.ForeignKeyIterator, delegate (ForeignKey fk) { return Equals(fk.ReferencedTable, collection.Table); }); // create an index on all columns in this foreign key if(foreignKey != null) { CreateIndex(collection.CollectionTable, new TypeSafeEnumerableWrapper<Column>(foreignKey.ColumnIterator)); } } }
/// <summary> /// Retains only the elements in this set that are contained in the specified collection. /// </summary> /// <param name="c">Collection that defines the set of elements to be retained.</param> /// <returns><c>true</c> if this set changed as a result of this operation.</returns> public override bool RetainAll(ICollection c) { //Put data from C into a set so we can use the Contains() method. Set cSet = new HybridSet(c); //We are going to build a set of elements to remove. Set removeSet = new HybridSet(); foreach(object o in this) { //If C does not contain O, then we need to remove O from our //set. We can't do this while iterating through our set, so //we put it into RemoveSet for later. if(!cSet.Contains(o)) removeSet.Add(o); } return this.RemoveAll(removeSet); }
/// <summary> /// Create an array of arguments to invoke a constructor or static factory method, /// given the resolved constructor arguments values. /// </summary> /// <remarks>When return value is null the out parameter UnsatisfiedDependencyExceptionData will contain /// information for use in throwing a UnsatisfiedDependencyException by the caller. This avoids using /// exceptions for flow control as in the original implementation.</remarks> private ArgumentsHolder CreateArgumentArray(string objectName, RootObjectDefinition rod, ConstructorArgumentValues resolvedValues, ObjectWrapper wrapper, Type[] paramTypes, MethodBase methodOrCtorInfo, bool autowiring, out UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData) { string methodType = (methodOrCtorInfo is ConstructorInfo) ? "constructor" : "factory method"; unsatisfiedDependencyExceptionData = null; ArgumentsHolder args = new ArgumentsHolder(paramTypes.Length); ISet usedValueHolders = new HybridSet(); IList autowiredObjectNames = new LinkedList(); bool resolveNecessary = false; ParameterInfo[] argTypes = methodOrCtorInfo.GetParameters(); for (int paramIndex = 0; paramIndex < paramTypes.Length; paramIndex++) { Type paramType = paramTypes[paramIndex]; string parameterName = argTypes[paramIndex].Name; // If we couldn't find a direct match and are not supposed to autowire, // let's try the next generic, untyped argument value as fallback: // it could match after type conversion (for example, String -> int). ConstructorArgumentValues.ValueHolder valueHolder = null; if (resolvedValues.GetNamedArgumentValue(parameterName) != null) { valueHolder = resolvedValues.GetArgumentValue(parameterName, paramType, usedValueHolders); } else { valueHolder = resolvedValues.GetArgumentValue(paramIndex, paramType, usedValueHolders); } if (valueHolder == null && !autowiring) { valueHolder = resolvedValues.GetGenericArgumentValue(null, usedValueHolders); } if (valueHolder != null) { // We found a potential match - let's give it a try. // Do not consider the same value definition multiple times! usedValueHolders.Add(valueHolder); args.rawArguments[paramIndex] = valueHolder.Value; try { object originalValue = valueHolder.Value; object convertedValue = TypeConversionUtils.ConvertValueIfNecessary(paramType, originalValue, null); args.arguments[paramIndex] = convertedValue; //? args.preparedArguments[paramIndex] = convertedValue; } catch (TypeMismatchException ex) { //To avoid using exceptions for flow control, this is not a cost in Java as stack trace is lazily created. string errorMessage = String.Format(CultureInfo.InvariantCulture, "Could not convert {0} argument value [{1}] to required type [{2}] : {3}", methodType, valueHolder.Value, paramType, ex.Message); unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return null; } } else { // No explicit match found: we're either supposed to autowire or // have to fail creating an argument array for the given constructor. if (!autowiring) { string errorMessage = String.Format(CultureInfo.InvariantCulture, "Ambiguous {0} argument types - " + "Did you specify the correct object references as {0} arguments?", methodType); unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return null; } try { MethodParameter param = MethodParameter.ForMethodOrConstructor(methodOrCtorInfo, paramIndex); object autowiredArgument = ResolveAutoWiredArgument(param, objectName, autowiredObjectNames); args.rawArguments[paramIndex] = autowiredArgument; args.arguments[paramIndex] = autowiredArgument; args.preparedArguments[paramIndex] = new AutowiredArgumentMarker(); resolveNecessary = true; } catch (ObjectsException ex) { unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, ex.Message); return null; } } } foreach (string autowiredObjectName in autowiredObjectNames) { if (log.IsDebugEnabled) { log.Debug("Autowiring by type from object name '" + objectName + "' via " + methodType + " to object named '" + autowiredObjectName + "'"); } } return args; }
/// <summary> /// Determines the <see cref="System.Type"/> of the object defined /// by the supplied object <paramref name="definition"/>. /// </summary> /// <param name="objectName"> /// The name associated with the supplied object <paramref name="definition"/>. /// </param> /// <param name="definition"> /// The <see cref="Spring.Objects.Factory.Support.RootObjectDefinition"/> /// that the <see cref="System.Type"/> is to be determined for. /// </param> /// <returns> /// The <see cref="System.Type"/> of the object defined by the supplied /// object <paramref name="definition"/>; or <see lang="null"/> if the /// <see cref="System.Type"/> cannot be determined. /// </returns> protected override Type GetTypeForFactoryMethod(string objectName, RootObjectDefinition definition) { Type factoryType = null; bool isStatic = true; if (StringUtils.HasText(definition.FactoryObjectName)) { // check declared factory method return type on factory type... factoryType = GetType(definition.FactoryObjectName); isStatic = false; } else { factoryType = ResolveObjectType(definition, objectName); } if (factoryType == null) { return null; } // If all factory methods have the same return type, return that type. // Can't clearly figure out exact method due to type converting / autowiring! int minNrOfArgs = definition.ConstructorArgumentValues.GenericArgumentValues.Count; MethodInfo[] candidates = factoryType.GetMethods(); ISet returnTypes = new HybridSet(); foreach (MethodInfo factoryMethod in candidates) { #if NET_2_0 GenericArgumentsHolder genericArgsInfo = new GenericArgumentsHolder(definition.FactoryMethodName); if (factoryMethod.IsStatic == isStatic && factoryMethod.Name.Equals(genericArgsInfo.GenericMethodName) && ReflectionUtils.GetParameterTypes(factoryMethod).Length >= minNrOfArgs && factoryMethod.GetGenericArguments().Length == genericArgsInfo.GetGenericArguments().Length) { if (genericArgsInfo.ContainsGenericArguments) { string[] unresolvedGenericArgs = genericArgsInfo.GetGenericArguments(); Type[] genericArgs = new Type[unresolvedGenericArgs.Length]; for (int j = 0; j < unresolvedGenericArgs.Length; j++) { genericArgs[j] = TypeResolutionUtils.ResolveType(unresolvedGenericArgs[j]); } returnTypes.Add(factoryMethod.MakeGenericMethod(genericArgs).ReturnType); } else { returnTypes.Add(factoryMethod.ReturnType); } } #else if (factoryMethod.IsStatic == isStatic && factoryMethod.Name.Equals(definition.FactoryMethodName) && ReflectionUtils.GetParameterTypes(factoryMethod).Length >= minNrOfArgs) { returnTypes.Add(factoryMethod.ReturnType); } #endif } if (returnTypes.Count == 1) { // clear return type found: all factory methods return same type... return (Type)ObjectUtils.EnumerateFirstElement(returnTypes); } // ambiguous return types found: return null to indicate "not determinable"... return null; }
/// <summary> /// Resolves this managed collection at runtime. /// </summary> /// <param name="objectName"> /// The name of the top level object that is having the value of one of it's /// collection properties resolved. /// </param> /// <param name="definition"> /// The definition of the named top level object. /// </param> /// <param name="propertyName"> /// The name of the property the value of which is being resolved. /// </param> /// <param name="resolver"> /// The callback that will actually do the donkey work of resolving /// this managed collection. /// </param> /// <returns>A fully resolved collection.</returns> public ICollection Resolve(string objectName, IObjectDefinition definition, string propertyName, ManagedCollectionElementResolver resolver) { ISet set = new HybridSet(); Type elementType = null; if (StringUtils.HasText(this.elementTypeName)) { elementType = TypeResolutionUtils.ResolveType(this.elementTypeName); } string elementName = propertyName + "[(set-element)]"; foreach (object element in this) { object resolvedElement = resolver(objectName, definition, elementName, element); if (elementType != null) { try { resolvedElement = TypeConversionUtils.ConvertValueIfNecessary(elementType, resolvedElement, propertyName); } catch (TypeMismatchException) { throw new TypeMismatchException( String.Format( "Unable to convert managed set element '{0}' from [{1}] into [{2}] during initialization" + " of property '{3}' for object '{4}'. Do you have an appropriate type converter registered?", resolvedElement, resolvedElement.GetType(), elementType, propertyName, objectName)); } } set.Add(resolvedElement); } return set; }
/// <summary> /// Gets all of the interfaces that the /// supplied <see cref="System.Type"/> implements. /// </summary> /// <remarks> /// This includes interfaces implemented by any superclasses. /// </remarks> /// <param name="type"> /// The type to analyse for interfaces. /// </param> /// <returns> /// All of the interfaces that the supplied <see cref="System.Type"/> implements. /// </returns> public static Type[] GetAllInterfacesFromType(Type type) { AssertUtils.ArgumentNotNull(type, "type"); ISet interfaces = new HybridSet(); do { Type[] ifcs = type.GetInterfaces(); foreach (Type ifc in ifcs) { interfaces.Add(ifc); } type = type.BaseType; } while (type != null); if (interfaces.Count > 0) { Type[] types = new Type[interfaces.Count]; interfaces.CopyTo(types, 0); return types; } return Type.EmptyTypes; }
/// <summary> /// Create an array of arguments to invoke a constructor or static factory method, /// given the resolved constructor arguments values. /// </summary> /// <remarks>When return value is null the out parameter UnsatisfiedDependencyExceptionData will contain /// information for use in throwing a UnsatisfiedDependencyException by the caller. This avoids using /// exceptions for flow control as in the original implementation.</remarks> private ArgumentsHolder CreateArgumentArray(string objectName, RootObjectDefinition rod, ConstructorArgumentValues resolvedValues, ObjectWrapper wrapper, Type[] paramTypes, MethodBase methodOrCtorInfo, bool autowiring, out UnsatisfiedDependencyExceptionData unsatisfiedDependencyExceptionData) { string methodType = (methodOrCtorInfo is ConstructorInfo) ? "constructor" : "factory method"; unsatisfiedDependencyExceptionData = null; ArgumentsHolder args = new ArgumentsHolder(paramTypes.Length); ISet usedValueHolders = new HybridSet(); IList autowiredObjectNames = new LinkedList(); bool resolveNecessary = false; ParameterInfo[] argTypes = methodOrCtorInfo.GetParameters(); for (int paramIndex = 0; paramIndex < paramTypes.Length; paramIndex++) { Type paramType = paramTypes[paramIndex]; string parameterName = argTypes[paramIndex].Name; // If we couldn't find a direct match and are not supposed to autowire, // let's try the next generic, untyped argument value as fallback: // it could match after type conversion (for example, String -> int). ConstructorArgumentValues.ValueHolder valueHolder = null; if (resolvedValues.GetNamedArgumentValue(parameterName) != null) { valueHolder = resolvedValues.GetArgumentValue(parameterName, paramType, usedValueHolders); } else { valueHolder = resolvedValues.GetArgumentValue(paramIndex, paramType, usedValueHolders); } if (valueHolder == null && !autowiring) { valueHolder = resolvedValues.GetGenericArgumentValue(null, usedValueHolders); } if (valueHolder != null) { // We found a potential match - let's give it a try. // Do not consider the same value definition multiple times! usedValueHolders.Add(valueHolder); args.rawArguments[paramIndex] = valueHolder.Value; try { object originalValue = valueHolder.Value; object convertedValue = TypeConversionUtils.ConvertValueIfNecessary(paramType, originalValue, null); args.arguments[paramIndex] = convertedValue; //? args.preparedArguments[paramIndex] = convertedValue; } catch (TypeMismatchException ex) { //To avoid using exceptions for flow control, this is not a cost in Java as stack trace is lazily created. string errorMessage = String.Format(CultureInfo.InvariantCulture, "Could not convert {0} argument value [{1}] to required type [{2}] : {3}", methodType, valueHolder.Value, paramType, ex.Message); unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return(null); } } else { // No explicit match found: we're either supposed to autowire or // have to fail creating an argument array for the given constructor. if (!autowiring) { string errorMessage = String.Format(CultureInfo.InvariantCulture, "Ambiguous {0} argument types - " + "Did you specify the correct object references as {0} arguments?", methodType); unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, errorMessage); return(null); } try { MethodParameter param = MethodParameter.ForMethodOrConstructor(methodOrCtorInfo, paramIndex); object autowiredArgument = ResolveAutoWiredArgument(param, objectName, autowiredObjectNames); args.rawArguments[paramIndex] = autowiredArgument; args.arguments[paramIndex] = autowiredArgument; args.preparedArguments[paramIndex] = new AutowiredArgumentMarker(); resolveNecessary = true; } catch (ObjectsException ex) { unsatisfiedDependencyExceptionData = new UnsatisfiedDependencyExceptionData(paramIndex, paramType, ex.Message); return(null); } } } foreach (string autowiredObjectName in autowiredObjectNames) { if (log.IsDebugEnabled) { log.Debug("Autowiring by type from object name '" + objectName + "' via " + methodType + " to object named '" + autowiredObjectName + "'"); } } return(args); }
public static HybridSet GetOperatorsForRequest(BookRequest b, NameValueCollection settings) { NameValueCollection pars = new NameValueCollection(); HybridSet filterlist = new HybridSet(); HybridSet filteredaircraftlist = new HybridSet(); pars.Add("status", "confirm"); IList <Operator> oplist = OperatorDAO.GetOperators(pars); HybridSet aircraftlist = new HybridSet(); foreach (Operator op in oplist) { aircraftlist.AddAll(op.Aircrafts); } String regionmatch = settings.Get("regionmatch"); switch (regionmatch) { case "allinoperatedcountries": { ListSet countries = b.GetLegCountries(); foreach (Operator op in oplist) { if (op.OperatorCountries.ContainsAll(countries)) { filteredaircraftlist.AddAll(op.Aircrafts); } } break; } case "startingoperatedcountries": { String country = b.GetStartingLeg().Source.Country.Trim(); foreach (Operator op in oplist) { if (op.OperatorCountries.Contains(country)) { filteredaircraftlist.AddAll(op.Aircrafts); } } break; } case "aircraftpresentinstartlocation": { String location = b.GetStartingLeg().Source.City; if (location != null && location.Trim() != "") { foreach (Airplane a in aircraftlist) { if (a.AircraftLocation.Trim().ToLower().Equals(location.ToLower())) { filteredaircraftlist.Add(a); } } } else { location = b.GetStartingLeg().Source.AirfieldName; foreach (String s in location.Split(" ".ToCharArray())) { if (s.Trim() != "") { foreach (Airplane a in aircraftlist) { if (a.AircraftLocation.Trim().ToLower().Equals(s.ToLower())) { filteredaircraftlist.Add(a); } } } } } break; } default: { foreach (Operator op in oplist) { filteredaircraftlist.AddAll(op.Aircrafts); } break; } } String aircraftcategorymatch = settings.Get("aircraftcategorymatch"); HybridSet categoryfilteredlist = new HybridSet(filteredaircraftlist); switch (aircraftcategorymatch) { case "exactmatch": { foreach (Airplane a in filteredaircraftlist) { if (!a.AircraftType.Equals(b.PlaneType)) { categoryfilteredlist.Remove(a); } } break; } case "parentmatch": { foreach (Airplane a in filteredaircraftlist) { if (!a.AircraftType.ParentCategory.Equals(b.PlaneType.ParentCategory)) { categoryfilteredlist.Remove(a); } } break; } default: { break; } } foreach (Airplane a in categoryfilteredlist) { filterlist.Add(a.Vendor); } return(filterlist); }