Ejemplo n.º 1
0
        public void TestDeSerializeClassHierarchy()
        {
            Type timerType            = typeof(Timer);
            Type SecondType           = typeof(Timer.Seconds);
            Type simpleCOnstuctorType = typeof(SimpleConstructors);

            IClassHierarchy ns             = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Timer).Assembly.GetName().Name });
            IClassNode      timerClassNode = (IClassNode)ns.GetNode(timerType.AssemblyQualifiedName);
            INode           secondNode     = (INode)ns.GetNode(SecondType.AssemblyQualifiedName);
            IClassNode      SimpleConstructorsClassNode = (IClassNode)ns.GetNode(simpleCOnstuctorType.AssemblyQualifiedName);

            ProtocolBufferClassHierarchy.Serialize("node.bin", ns);
            IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("node.bin");

            IClassNode timerClassNode2 = (IClassNode)ch.GetNode(timerType.AssemblyQualifiedName);
            INode      secondNode2     = ch.GetNode(SecondType.AssemblyQualifiedName);
            IClassNode SimpleConstructorsClassNode2 = (IClassNode)ch.GetNode(simpleCOnstuctorType.AssemblyQualifiedName);

            Assert.Equal(timerClassNode.GetFullName(), timerClassNode2.GetFullName());
            Assert.Equal(secondNode.GetFullName(), secondNode2.GetFullName());
            Assert.Equal(SimpleConstructorsClassNode.GetFullName(), SimpleConstructorsClassNode2.GetFullName());

            Assert.True(SimpleConstructorsClassNode2.GetChildren().Count == 0);
            IList <IConstructorDef> def = SimpleConstructorsClassNode2.GetInjectableConstructors();

            Assert.Equal(3, def.Count);
        }
        private static ClassHierarchyProto.Node SerializeNode(INode n)
        {
            IList <ClassHierarchyProto.Node> children = new List <ClassHierarchyProto.Node>();

            foreach (INode child in n.GetChildren())
            {
                children.Add(SerializeNode(child));
            }


            if (n is IClassNode)
            {
                IClassNode cn = (IClassNode)n;
                IList <IConstructorDef> injectable = cn.GetInjectableConstructors();
                IList <IConstructorDef> all        = cn.GetAllConstructors();
                IList <IConstructorDef> others     = new List <IConstructorDef>(all);

                foreach (var c in injectable)
                {
                    others.Remove(c);
                }

                IList <ClassHierarchyProto.ConstructorDef> injectableConstructors = new List <ClassHierarchyProto.ConstructorDef>();
                foreach (IConstructorDef inj in injectable)
                {
                    injectableConstructors.Add(SerializeConstructorDef(inj));
                }

                IList <ClassHierarchyProto.ConstructorDef> otherConstructors = new List <ClassHierarchyProto.ConstructorDef>();
                foreach (IConstructorDef other in others)
                {
                    otherConstructors.Add(SerializeConstructorDef(other));
                }

                List <string> implFullNames = new List <string>();
                foreach (IClassNode impl in cn.GetKnownImplementations())
                {
                    implFullNames.Add(impl.GetFullName());
                }

                return(NewClassNode(cn.GetName(), cn.GetFullName(),
                                    cn.IsInjectionCandidate(), cn.IsExternalConstructor(), cn.IsUnit(),
                                    injectableConstructors, otherConstructors, implFullNames, children));
            }
            else if (n is INamedParameterNode)
            {
                INamedParameterNode np = (INamedParameterNode)n;
                return(NewNamedParameterNode(np.GetName(), np.GetFullName(),
                                             np.GetSimpleArgName(), np.GetFullArgName(), np.IsSet(), np.GetDocumentation(),
                                             np.GetShortName(), np.GetDefaultInstanceAsStrings(), children));
            }
            else if (n is IPackageNode)
            {
                return(NewPackageNode(n.GetName(), n.GetFullName(), children));
            }
            else
            {
                throw new IllegalStateException("Encountered unknown type of Node: " + n);
            }
        }
Ejemplo n.º 3
0
        private static Org.Apache.REEF.Tang.Protobuf.Node SerializeNode(INode n)
        {
            IList <Org.Apache.REEF.Tang.Protobuf.Node> children = new List <Org.Apache.REEF.Tang.Protobuf.Node>();

            foreach (INode child in n.GetChildren())
            {
                children.Add(SerializeNode(child));
            }

            if (n is IClassNode)
            {
                IClassNode cn = (IClassNode)n;
                IList <IConstructorDef> injectable = cn.GetInjectableConstructors();
                IList <IConstructorDef> all        = cn.GetAllConstructors();
                IList <IConstructorDef> others     = new List <IConstructorDef>(all);

                foreach (var c in injectable)
                {
                    others.Remove(c);
                }

                IList <Org.Apache.REEF.Tang.Protobuf.ConstructorDef> injectableConstructors = new List <Org.Apache.REEF.Tang.Protobuf.ConstructorDef>();
                foreach (IConstructorDef inj in injectable)
                {
                    injectableConstructors.Add(SerializeConstructorDef(inj));
                }

                IList <Org.Apache.REEF.Tang.Protobuf.ConstructorDef> otherConstructors = new List <Org.Apache.REEF.Tang.Protobuf.ConstructorDef>();
                foreach (IConstructorDef other in others)
                {
                    otherConstructors.Add(SerializeConstructorDef(other));
                }

                List <string> implFullNames = new List <string>();
                foreach (IClassNode impl in cn.GetKnownImplementations())
                {
                    implFullNames.Add(impl.GetFullName());  // we use class fully qualifed name
                }

                return(NewClassNode(cn.GetName(), cn.GetFullName(),
                                    cn.IsInjectionCandidate(), cn.IsExternalConstructor(), cn.IsUnit(),
                                    injectableConstructors, otherConstructors, implFullNames, children));
            }
            if (n is INamedParameterNode)
            {
                INamedParameterNode np = (INamedParameterNode)n;
                return(NewNamedParameterNode(np.GetName(), np.GetFullName(),
                                             np.GetSimpleArgName(), np.GetFullArgName(), np.IsSet(), np.IsList(), np.GetDocumentation(),
                                             np.GetShortName(), np.GetDefaultInstanceAsStrings(), children, np.GetAlias(), np.GetAliasLanguage()));
            }
            if (n is IPackageNode)
            {
                return(NewPackageNode(n.GetName(), n.GetFullName(), children));
            }
            Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new IllegalStateException("Encountered unknown type of Node: " + n), LOGGER);
            return(null);
        }
Ejemplo n.º 4
0
        private void AddConfiguration(IClassHierarchy ns, ConfigurationBuilderImpl builder)
        {
            this.ClassHierarchy = this.ClassHierarchy.Merge(ns);

            //TODO
            //((ClassHierarchyImpl) ClassHierarchy).parameterParser
            //    .mergeIn(((ClassHierarchyImpl) namespace).parameterParser);

            foreach (IClassNode cn in builder.BoundImpls.Keys)
            {
                IClassNode n = null;
                builder.BoundImpls.TryGetValue(cn, out n);
                if (n != null)
                {
                    Bind(cn.GetFullName(), n.GetFullName());
                }
            }

            foreach (IClassNode cn in builder.BoundConstructors.Keys)
            {
                IClassNode n = null;
                builder.BoundConstructors.TryGetValue(cn, out n);
                if (n != null)
                {
                    Bind(cn.GetFullName(), n.GetFullName());
                }
            }

            // The namedParameters set contains the strings that can be used to
            // instantiate new
            // named parameter instances. Create new ones where we can.
            foreach (INamedParameterNode np in builder.NamedParameters.Keys)
            {
                string v = null;
                builder.NamedParameters.TryGetValue(np, out v);
                Bind(np.GetFullName(), v);
            }

            foreach (IClassNode cn in builder.LegacyConstructors.Keys)
            {
                IConstructorDef cd = null;
                builder.LegacyConstructors.TryGetValue(cn, out cd);
                //RegisterLegacyConstructor(cn, cd.GetArgs());  TODO
            }

            //for (Entry<NamedParameterNode<Set<?>>, Object> e: builder.boundSetEntries) {
            //  String name = ((NamedParameterNode<Set<T>>)(NamedParameterNode<?>)e.getKey()).getFullName();
            //  if(e.getValue() instanceof Node) {
            //    bindSetEntry(name, (Node)e.getValue());
            //  } else if(e.getValue() instanceof String) {
            //    bindSetEntry(name, (String)e.getValue());
            //  } else {
            //    throw new IllegalStateException();
            //  }
            //}
        }
Ejemplo n.º 5
0
        public void RegisterLegacyConstructor(IClassNode c, IList <IConstructorArg> args)
        {
            string[] cn = new string[args.Count];

            for (int i = 0; i < args.Count; i++)
            {
                cn[i] = args[i].Gettype();
            }
            RegisterLegacyConstructor(c.GetFullName(), cn);
        }
        /// <summary>
        /// This program generates class hierarchy bin file for the list of dlls, plus a defalut list
        /// The default list include: ITask, StreamTask1, HelloTask and ShellTask, please remove if not needed
        /// </summary>
        /// <param name="args"> additional dlls needed to build class hierarchy </param>
        public static void Main(string[] args)
        {
            const string DllSubfix = ".dll";
            const string ClassHierarchyBinFileName = "task.bin";

            List <string> taskDlls = new List <string>();

            foreach (string arg in args)
            {
                string assemblyName = arg;
                if (!arg.EndsWith(DllSubfix, StringComparison.OrdinalIgnoreCase))
                {
                    assemblyName += DllSubfix;
                }
                if (!File.Exists(assemblyName))
                {
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "invalid argument: assembly {0} cannot be found", assemblyName));
                }
                taskDlls.Add(arg);
            }

            taskDlls.Add(GetAssemblyName(typeof(ITask)));
            taskDlls.Add(GetAssemblyName(typeof(HelloTask)));
            taskDlls.Add(GetAssemblyName(typeof(ShellTask)));
            taskDlls.Add(GetAssemblyName(typeof(StreamTask1)));

            IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(taskDlls.ToArray());

            // the following is verification only
            // to verify that a class indeeded has been added to the class hierarchy, check the class name
            IClassNode streamTaskClassNode = (IClassNode)ns.GetNode(typeof(StreamTask1).AssemblyQualifiedName);
            IClassNode helloTaskClassNode  = (IClassNode)ns.GetNode(typeof(HelloTask).AssemblyQualifiedName);
            IClassNode shellTaskClassNode  = (IClassNode)ns.GetNode(typeof(ShellTask).AssemblyQualifiedName);

            ProtocolBufferClassHierarchy.Serialize(ClassHierarchyBinFileName, ns);
            IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize(ClassHierarchyBinFileName);

            IClassNode retrievedStreamTaskClassNode = (IClassNode)ch.GetNode(typeof(StreamTask1).AssemblyQualifiedName);
            IClassNode retrievedHelloTaskClassNode  = (IClassNode)ch.GetNode(typeof(HelloTask).AssemblyQualifiedName);
            IClassNode retrievedShellTaskClassNode  = (IClassNode)ch.GetNode(typeof(ShellTask).AssemblyQualifiedName);

            if (!streamTaskClassNode.GetFullName().Equals(retrievedStreamTaskClassNode.GetFullName()) ||
                !helloTaskClassNode.GetFullName().Equals(retrievedHelloTaskClassNode.GetFullName()) ||
                !shellTaskClassNode.GetFullName().Equals(retrievedShellTaskClassNode.GetFullName()))
            {
                Console.WriteLine("Node deseriliazed is not equal");
            }
            else
            {
                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Class hierarchy written to [{0}].", Directory.GetCurrentDirectory()));
            }
        }
Ejemplo n.º 7
0
        public IClassHierarchy Merge(IClassHierarchy ch)
        {
            if (this == ch)
            {
                return(this);
            }

            if (!(ch is ProtocolBufferClassHierarchy))
            {
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new NotSupportedException(
                                                                           "Cannot merge ExternalClassHierarchies yet!"), LOGGER);
            }

            ProtocolBufferClassHierarchy pch = (ProtocolBufferClassHierarchy)ch;

            foreach (var pair in pch.lookupTable)
            {
                if (!this.lookupTable.ContainsKey(pair.Key))
                {
                    this.lookupTable.Add(pair);
                }
            }

            foreach (INode n in ch.GetNamespace().GetChildren())
            {
                if (!rootNode.Contains(n.GetFullName()))
                {
                    if (n is INamedParameterNode)
                    {
                        INamedParameterNode np = (INamedParameterNode)n;
                        new NamedParameterNodeImpl(this.rootNode, np.GetName(),
                                                   np.GetFullName(), np.GetFullArgName(), np.GetSimpleArgName(),
                                                   np.IsSet(), np.IsList(), np.GetDocumentation(), np.GetShortName(),
                                                   np.GetDefaultInstanceAsStrings().ToArray());
                    }
                    else if (n is IClassNode)
                    {
                        IClassNode cn = (IClassNode)n;
                        new ClassNodeImpl(rootNode, cn.GetName(), cn.GetFullName(),
                                          cn.IsUnit(), cn.IsInjectionCandidate(),
                                          cn.IsExternalConstructor(), cn.GetInjectableConstructors(),
                                          cn.GetAllConstructors(), cn.GetDefaultImplementation());
                    }
                }
            }

            return(this);
        }
Ejemplo n.º 8
0
        public void TestDeSerializeClassHierarchyForActivity()
        {
            string[] s = new string[2];
            s[0] = @"com.microsoft.reef.activity";
            s[1] = @"com.microsoft.reef.activityInterface";

            IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(s);
            IClassNode      activityClassNode = (IClassNode)ns.GetNode("com.microsoft.reef.activity.HelloActivity");

            ProtocolBufferClassHierarchy.Serialize("activity.bin", ns);
            IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("activity.bin");

            IClassNode activityClassNode2 = (IClassNode)ch.GetNode("com.microsoft.reef.activity.HelloActivity");

            Assert.AreEqual(activityClassNode.GetFullName(), activityClassNode2.GetFullName());
        }
Ejemplo n.º 9
0
        public void TestDeSerializeClassHierarchyForTask()
        {
            Type streamTask1Type = typeof(StreamTask1);
            Type helloTaskType   = typeof(HelloTask);

            IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(HelloTask).Assembly.GetName().Name });
            IClassNode      StreamTask1ClassNode = (IClassNode)ns.GetNode(streamTask1Type.AssemblyQualifiedName);
            IClassNode      HelloTaskClassNode   = (IClassNode)ns.GetNode(helloTaskType.AssemblyQualifiedName);

            ProtocolBufferClassHierarchy.Serialize("task.bin", ns);
            IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("task.bin");
            IClassNode      StreamTask1ClassNode2 = (IClassNode)ch.GetNode(streamTask1Type.AssemblyQualifiedName);
            IClassNode      HelloTaskClassNode2   = (IClassNode)ch.GetNode(helloTaskType.AssemblyQualifiedName);

            Assert.Equal(StreamTask1ClassNode.GetFullName(), StreamTask1ClassNode2.GetFullName());
            Assert.Equal(HelloTaskClassNode.GetFullName(), HelloTaskClassNode2.GetFullName());
        }
Ejemplo n.º 10
0
        private object GetCachedInstance(IClassNode cn)
        {
            if (cn.GetFullName().Equals("com.Microsoft.Tang.Interface.IInjector"))
            {
                return(this);// TODO: We should be insisting on injection futures here! .forkInjector();
            }
            else
            {
                object t = null;

                instances.TryGetValue(cn, out t);

                if (t != null && t is InjectionFuture)
                {
                    throw new IllegalStateException("Found an injection future in getCachedInstance: " + cn);
                }
                return(t);
            }
        }
Ejemplo n.º 11
0
        private object GetCachedInstance(IClassNode cn)
        {
            //// if (cn.GetFullName().Equals(ReflectionUtilities.NonGenericFullName(typeof(IInjector))))
            if (cn.GetFullName().Equals(ReflectionUtilities.GetAssemblyQualifiedName(typeof(IInjector))))
            {
                return(this.ForkInjector()); // TODO: We should be insisting on injection futures here! .forkInjector();
            }
            else
            {
                object t = null;

                instances.TryGetValue(cn, out t);

                if (t != null && t is IInjectionFuture <object> )
                {
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new IllegalStateException("Found an injection future in getCachedInstance: " + cn), LOGGER);
                }
                return(t);
            }
        }
Ejemplo n.º 12
0
        public static void GetNodeFromHierarchy(ClassHierarchyImpl classHierarchyImpl)
        {
            IClassNode timerClassNode = (IClassNode)classHierarchyImpl.GetNode("Com.Microsoft.Tang.Examples.Timer");
            INode      secondNode     = classHierarchyImpl.GetNode("Com.Microsoft.Tang.Examples.Timer+Seconds");

            string classNmae = timerClassNode.GetFullName();
            //Type clazz = classHierarchyImpl.loader.GetType(classNmae);

            IList <IConstructorDef> constuctorDefs = timerClassNode.GetAllConstructors();

            foreach (IConstructorDef consDef in constuctorDefs)
            {
                IList <IConstructorArg> consArgs = consDef.GetArgs();
                foreach (IConstructorArg arg in consArgs)
                {
                    string argName     = arg.GetName();
                    string argTypeName = arg.Gettype();
                    Type   nt          = Type.GetType(argName);
                    INode  argNode     = classHierarchyImpl.GetNode(nt);
                }
            }
        }
Ejemplo n.º 13
0
        public void TestDeSerializeClassHierarchy()
        {
            IClassHierarchy ns             = TangFactory.GetTang().GetClassHierarchy(new string[] { @"Com.Microsoft.Tang.Examples" });
            IClassNode      timerClassNode = (IClassNode)ns.GetNode("Com.Microsoft.Tang.Examples.Timer");
            INode           secondNode     = (INode)ns.GetNode("Com.Microsoft.Tang.Examples.Timer+Seconds");
            IClassNode      SimpleConstructorsClassNode = (IClassNode)ns.GetNode("Com.Microsoft.Tang.Examples.SimpleConstructors");

            ProtocolBufferClassHierarchy.Serialize("node.bin", ns);
            IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("node.bin");

            IClassNode timerClassNode2 = (IClassNode)ch.GetNode("Com.Microsoft.Tang.Examples.Timer");
            INode      secondNode2     = ch.GetNode("Com.Microsoft.Tang.Examples.Timer+Seconds");
            IClassNode SimpleConstructorsClassNode2 = (IClassNode)ch.GetNode("Com.Microsoft.Tang.Examples.SimpleConstructors");

            Assert.AreEqual(timerClassNode.GetFullName(), timerClassNode2.GetFullName());
            Assert.AreEqual(secondNode.GetFullName(), secondNode.GetFullName());
            Assert.AreEqual(SimpleConstructorsClassNode.GetFullName(), SimpleConstructorsClassNode2.GetFullName());

            Assert.IsTrue(SimpleConstructorsClassNode2.GetChildren().Count == 0);
            IList <IConstructorDef> def = SimpleConstructorsClassNode2.GetInjectableConstructors();

            Assert.AreEqual(3, def.Count);
        }
Ejemplo n.º 14
0
 private InjectionPlan BuildClassNodeInjectionPlan(IClassNode cn,
     object cachedInstance,
     IClassNode externalConstructor, 
     IClassNode boundImpl,
     IClassNode defaultImpl,
     IDictionary<INode, InjectionPlan> memo)
 {
     if (cachedInstance != null)
     {
         return new CsInstance(cn, cachedInstance);
     }
     else if (externalConstructor != null)
     {
         BuildInjectionPlan(externalConstructor, memo);
         InjectionPlan ip = null;
         memo.TryGetValue(externalConstructor, out ip);
         return new Subplan(cn, 0, new InjectionPlan[] { ip });
     }
     else if (boundImpl != null && !cn.Equals(boundImpl))
     {
         // We need to delegate to boundImpl, so recurse.
         BuildInjectionPlan(boundImpl, memo);
         InjectionPlan ip = null;
         memo.TryGetValue(boundImpl, out ip);
         return new Subplan(cn, 0, new InjectionPlan[] { ip });
     }
     else if (defaultImpl != null && !cn.Equals(defaultImpl))
     {
         BuildInjectionPlan(defaultImpl, memo);
         InjectionPlan ip = null;
         memo.TryGetValue(defaultImpl, out ip);
         return new Subplan(cn, 0, new InjectionPlan[] { ip });
     }
     else {
         // if we're here and there is a bound impl or a default impl,
         // then we're bound / defaulted to ourselves, so don't add
         // other impls to the list of things to consider.
         List<IClassNode> candidateImplementations = new List<IClassNode>();
         if (boundImpl == null && defaultImpl == null)
         {
             foreach (var ki in cn.GetKnownImplementations())
             candidateImplementations.Add(ki);
         }
         candidateImplementations.Add(cn);
         List<InjectionPlan> sub_ips = FilterCandidateConstructors(candidateImplementations, memo);
         if (candidateImplementations.Count == 1 && candidateImplementations[0].GetFullName().Equals(cn.GetFullName()))
         {
             return WrapInjectionPlans(cn, sub_ips, false, -1);
         }
         else
         {
             return WrapInjectionPlans(cn, sub_ips, true, -1);
         }
     }
 }
Ejemplo n.º 15
0
        private void AddConfiguration(IClassHierarchy ns, ConfigurationBuilderImpl builder)
        {
            this.ClassHierarchy = this.ClassHierarchy.Merge(ns);

            if ((ClassHierarchy is ClassHierarchyImpl || builder.ClassHierarchy is ClassHierarchyImpl))
            {
                if ((ClassHierarchy is ClassHierarchyImpl && builder.ClassHierarchy is ClassHierarchyImpl))
                {
                    ((ClassHierarchyImpl)ClassHierarchy).Parameterparser.MergeIn(((ClassHierarchyImpl)builder.ClassHierarchy).Parameterparser);
                }
                else
                {
                    Org.Apache.Reef.Utilities.Diagnostics.Exceptions.Throw(new ArgumentException("Attempt to merge Java and non-Java class hierarchy!  Not supported."), LOGGER);
                }
            }

            foreach (IClassNode cn in builder.BoundImpls.Keys)
            {
                IClassNode n = null;
                builder.BoundImpls.TryGetValue(cn, out n);
                if (n != null)
                {
                    Bind(cn.GetFullName(), n.GetFullName());
                }
            }

            foreach (IClassNode cn in builder.BoundConstructors.Keys)
            {
                IClassNode n = null;
                builder.BoundConstructors.TryGetValue(cn, out n);
                if (n != null)
                {
                    Bind(cn.GetFullName(), n.GetFullName());
                }
            }

            // The namedParameters set contains the strings that can be used to
            // instantiate new
            // named parameter instances. Create new ones where we can.
            foreach (INamedParameterNode np in builder.NamedParameters.Keys)
            {
                string v = null;
                builder.NamedParameters.TryGetValue(np, out v);
                Bind(np.GetFullName(), v);
            }

            foreach (IClassNode cn in builder.LegacyConstructors.Keys)
            {
                IConstructorDef cd = null;
                builder.LegacyConstructors.TryGetValue(cn, out cd);
                RegisterLegacyConstructor(cn, cd.GetArgs());
            }

            foreach (KeyValuePair <INamedParameterNode, object> e in builder.BoundSetEntries)
            {
                String name = ((INamedParameterNode)e.Key).GetFullName();
                if (e.Value is INode)
                {
                    BindSetEntry(name, (INode)e.Value);
                }
                else if (e.Value is string)
                {
                    BindSetEntry(name, (string)e.Value);
                }
                else
                {
                    var ex = new IllegalStateException(string.Format(CultureInfo.CurrentCulture, "The value {0} set to the named parameter {1} is illegel.", e.Value, name));
                    Org.Apache.Reef.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                }
            }

            foreach (var p in builder.BoundLists)
            {
                BoundLists.Add(p.Key, p.Value);
            }
        }
Ejemplo n.º 16
0
        public INode RegisterType(Type type)
        {
            if (ReflectionUtilities.IsAnonymousType(type))
            {
                // DevNote: Kinda hacky way to indicate the no-op case.
                return(rootNode);
            }

            INode n = GetAlreadyBoundNode(type);

            if (n != null)
            {
                return(n);
            }

            if (type.BaseType != null)
            {
                RegisterType(type.BaseType);
            }

            foreach (Type interf in type.GetInterfaces())
            {
                RegisterType(ReflectionUtilities.EnsureInterfaceType(interf));
            }

            Type enclosingClass = type.DeclaringType; // this.GetEnclosingClass(type);

            if (enclosingClass != null)
            {
                RegisterType(enclosingClass);
            }

            INode node = RegisterClass(type);

            foreach (Type inner in type.GetNestedTypes())
            {
                RegisterType(inner);
            }

            IClassNode classNode = node as ClassNodeImpl;

            if (classNode != null)
            {
                foreach (IConstructorDef constructorDef in classNode.GetInjectableConstructors())
                {
                    foreach (IConstructorArg constructorArg in constructorDef.GetArgs())
                    {
                        if (constructorArg.Gettype() == null)
                        {
                            Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new ArgumentException("not type in arg"), LOGGER);
                        }
                        RegisterType(constructorArg.Gettype());  // Gettype returns param's Type.fullname
                        if (constructorArg.GetNamedParameterName() != null)
                        {
                            var pn = RegisterType(constructorArg.GetNamedParameterName());

                            if (!(pn is INamedParameterNode))
                            {
                                string message = string.Format(CultureInfo.CurrentCulture,
                                                               "The class {0}, used in the constructor of {1}, should not be defined as a NamedParameter.",
                                                               constructorArg.GetNamedParameterName(),
                                                               constructorDef.GetClassName());
                                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new ArgumentException(message), LOGGER);
                            }

                            INamedParameterNode np = (INamedParameterNode)RegisterType(constructorArg.GetNamedParameterName());
                            try
                            {
                                if (np.IsSet() || np.IsList())
                                {
                                    // throw new NotImplementedException();
                                }
                                else
                                {
                                    if (!ReflectionUtilities.IsCoercable(ClassForName(constructorArg.Gettype()), ClassForName(np.GetFullArgName())))
                                    {
                                        var e = new ClassHierarchyException(
                                            "Named parameter type mismatch in " + classNode.GetFullName() + ".  Constructor expects a "
                                            + constructorArg.Gettype() + " but " + np.GetName() + " is a "
                                            + np.GetFullArgName());
                                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                                    }
                                }
                            }
                            catch (TypeLoadException e)
                            {
                                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                                var ex = new ClassHierarchyException("Constructor refers to unknown class "
                                                                     + constructorArg.GetType(), e);
                                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                            }
                        }
                    }
                }
            }
            else
            {
                INamedParameterNode npNode = node as INamedParameterNode;
                if (npNode != null)
                {
                    RegisterType(npNode.GetFullArgName());
                }
            }

            return(node);
        }
Ejemplo n.º 17
0
        public object Parse(INamedParameterNode np, string value)
        {
            IClassNode iface = null;

            try
            {
                iface = (IClassNode)GetNode(np.GetFullArgName());
            }
            catch (NameResolutionException e)
            {
                Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                var ex = new IllegalStateException("Could not parse validated named parameter argument type.  NamedParameter is " + np.GetFullName() + " argument type is " + np.GetFullArgName(), e);
                Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
            }
            Type   clazz;
            string fullName;

            try
            {
                clazz    = (Type)ClassForName(iface.GetFullName());
                fullName = null;
            }
            catch (TypeLoadException e)
            {
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Warning, LOGGER);
                clazz    = null;
                fullName = iface.GetFullName();
            }

            object result = null;

            if (clazz != null)
            {
                result = Parameterparser.Parse(clazz, value);
            }
            else
            {
                result = Parameterparser.Parse(fullName, value);
            }

            if (result == null)
            {
                try
                {
                    INode impl = GetNode(value);
                    if (impl is IClassNode)
                    {
                        if (IsImplementation(iface, (IClassNode)impl))
                        {
                            return(impl);
                        }
                    }
                    var ex =
                        new ParseException(
                            "Name<" + iface.GetFullName() + "> " + np.GetFullName() + " cannot take non-subclass " +
                            impl.GetFullName());
                    Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                }
                catch (NameResolutionException ec)
                {
                    Utilities.Diagnostics.Exceptions.Caught(ec, Level.Error, LOGGER);
                    var ex =
                        new ParseException(
                            "Name<" + iface.GetFullName() + "> " + np.GetFullName() + " cannot take non-class " + value,
                            ec);
                    Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                }
            }
            return(result);
        }
Ejemplo n.º 18
0
        public void RegisterLegacyConstructor(IClassNode c, IList<IConstructorArg> args)
        {
            string[] cn = new string[args.Count];

            for (int i = 0; i < args.Count; i++)
            {
                cn[i] = args[i].Gettype();
            }
            RegisterLegacyConstructor(c.GetFullName(), cn);
        }
Ejemplo n.º 19
0
 private InjectionPlan BuildClassNodeInjectionPlan(IClassNode cn,
                                                   object cachedInstance,
                                                   IClassNode externalConstructor,
                                                   IClassNode boundImpl,
                                                   IClassNode defaultImpl,
                                                   IDictionary <INode, InjectionPlan> memo)
 {
     if (cachedInstance != null)
     {
         return(new CsInstance(cn, cachedInstance));
     }
     else if (externalConstructor != null)
     {
         BuildInjectionPlan(externalConstructor, memo);
         InjectionPlan ip = null;
         memo.TryGetValue(externalConstructor, out ip);
         return(new Subplan(cn, 0, new InjectionPlan[] { ip }));
     }
     else if (boundImpl != null && !cn.Equals(boundImpl))
     {
         // We need to delegate to boundImpl, so recurse.
         BuildInjectionPlan(boundImpl, memo);
         InjectionPlan ip = null;
         memo.TryGetValue(boundImpl, out ip);
         return(new Subplan(cn, 0, new InjectionPlan[] { ip }));
     }
     else if (defaultImpl != null && !cn.Equals(defaultImpl))
     {
         BuildInjectionPlan(defaultImpl, memo);
         InjectionPlan ip = null;
         memo.TryGetValue(defaultImpl, out ip);
         return(new Subplan(cn, 0, new InjectionPlan[] { ip }));
     }
     else
     {
         // if we're here and there is a bound impl or a default impl,
         // then we're bound / defaulted to ourselves, so don't add
         // other impls to the list of things to consider.
         List <IClassNode> candidateImplementations = new List <IClassNode>();
         if (boundImpl == null && defaultImpl == null)
         {
             foreach (var ki in cn.GetKnownImplementations())
             {
                 candidateImplementations.Add(ki);
             }
         }
         candidateImplementations.Add(cn);
         List <InjectionPlan> sub_ips = FilterCandidateConstructors(candidateImplementations, memo);
         if (candidateImplementations.Count == 1 && candidateImplementations[0].GetFullName().Equals(cn.GetFullName()))
         {
             return(WrapInjectionPlans(cn, sub_ips, false, -1));
         }
         else
         {
             return(WrapInjectionPlans(cn, sub_ips, true, -1));
         }
     }
 }
Ejemplo n.º 20
0
        private object GetCachedInstance(IClassNode cn)
        {
            if (cn.GetFullName().Equals("com.Microsoft.Tang.Interface.IInjector"))
            {
                return this;// TODO: We should be insisting on injection futures here! .forkInjector();
            }
            else
            {
                object t = null;

                instances.TryGetValue(cn, out t);

                if (t != null && t is InjectionFuture)
                {
                    throw new IllegalStateException("Found an injection future in getCachedInstance: " + cn);
                }
                return t;
            }
        }