Example #1
0
        public void TestTimer()
        {
            IClassNode timerClassNode = (IClassNode)ns.GetNode("Com.Microsoft.Tang.Examples.Timer");
            INode      secondNode     = ns.GetNode("Com.Microsoft.Tang.Examples.Timer+Seconds");

            Assert.AreEqual(secondNode.GetFullName(), "Com.Microsoft.Tang.Examples.Timer+Seconds");
        }
Example #2
0
        public void TestTimer()
        {
            IClassNode timerClassNode = (IClassNode)ns.GetNode(typeof(Timer).AssemblyQualifiedName);
            INode      secondNode     = ns.GetNode(typeof(Timer.Seconds).AssemblyQualifiedName);

            Assert.Equal(secondNode.GetFullName(), ReflectionUtilities.GetAssemblyQualifiedName(typeof(Timer.Seconds)));
        }
        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);
            }
        }
Example #4
0
        public void TestSerializeClassHierarchy()
        {
            IClassHierarchy ns             = TangFactory.GetTang().GetClassHierarchy(new string[] { @"Com.Microsoft.Tang.Examples" });
            IClassNode      timerClassNode = (IClassNode)ns.GetNode("Com.Microsoft.Tang.Examples.Timer");

            ProtocolBufferClassHierarchy.Serialize("node.bin", ns);
        }
Example #5
0
 public bool IsImplementation(IClassNode inter, IClassNode impl)
 {
     lock (_implLock)
     {
         return(impl.IsImplementationOf(inter));
     }
 }
Example #6
0
        public void TestDeSerializeClassHierarchyAndBind()
        {
            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.GetName(), StreamTask1ClassNode2.GetName());
            Assert.Equal(HelloTaskClassNode.GetName(), HelloTaskClassNode2.GetName());

            // have to use original class hierarchy for the merge. ClassHierarchy from ProtoBuffer doesn't support merge.
            IConfigurationBuilder cb = TangFactory.GetTang()
                                       .NewConfigurationBuilder(ns);

            cb.AddConfiguration(TaskConfiguration.ConfigurationModule
                                .Set(TaskConfiguration.Identifier, "Hello_From_Streaming1")
                                .Set(TaskConfiguration.Task, GenericType <StreamTask1> .Class)
                                .Build());

            IConfiguration taskConfiguration = cb.Build();
            StreamTask1    st = TangFactory.GetTang().NewInjector(taskConfiguration).GetInstance <StreamTask1>();

            Assert.NotNull(st);
        }
Example #7
0
        private static InjectorImpl Copy(InjectorImpl old, IConfiguration[] configurations)
        {
            InjectorImpl i;

            try
            {
                IConfigurationBuilder cb = old.configuration.newBuilder();
                foreach (IConfiguration c in configurations)
                {
                    cb.AddConfiguration(c);
                }
                i = new InjectorImpl(cb.Build());
            }
            catch (BindException e)
            {
                throw new IllegalStateException("Unexpected error copying configuration!", e);
            }

            foreach (IClassNode cn in old.instances.Keys)
            {
                if (cn.GetFullName().Equals(ReflectionUtilities.GetFullName(typeof(IInjector))) ||
                    cn.GetFullName().Equals(ReflectionUtilities.GetFullName(typeof(InjectorImpl))))
                {
                    // This would imply that we're treating injector as a singleton somewhere.  It should be copied fresh each time.
                    throw new IllegalStateException("");
                }
                try
                {
                    IClassNode new_cn = (IClassNode)i.classHierarchy.GetNode(cn.GetFullName());

                    object o = null;
                    old.instances.TryGetValue(cn, out o);
                    if (o != null)
                    {
                        i.instances.Add(new_cn, o);
                    }
                }
                catch (BindException e)
                {
                    throw new IllegalStateException("Could not resolve name "
                                                    + cn.GetFullName() + " when copying injector", e);
                }
            }

            foreach (INamedParameterNode np in old.namedParameterInstances.Keys)
            {
                // if (!builder.namedParameters.containsKey(np)) {
                Object o = null;
                old.namedParameterInstances.TryGetValue(np, out o);
                INamedParameterNode new_np = (INamedParameterNode)i.classHierarchy.GetNode(np.GetFullName());
                i.namedParameterInstances.Add(new_np, o);
            }

            // Fork the aspect (if any)
            if (old.aspect != null)
            {
                i.BindAspect(old.aspect.CreateChildAspect());
            }
            return(i);
        }
Example #8
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);
        }
Example #9
0
        public static InjectionPlan Deserialize(IClassHierarchy ch, InjectionPlanProto.InjectionPlan ip)
        {
            string fullName = ip.name;

            if (ip.constructor != null)
            {
                InjectionPlanProto.Constructor cons = ip.constructor;
                IClassNode cn = (IClassNode)ch.GetNode(fullName);

                InjectionPlanProto.InjectionPlan[] protoBufArgs = cons.args.ToArray();

                IClassNode[] cnArgs = new IClassNode[protoBufArgs.Length];

                for (int i = 0; i < protoBufArgs.Length; i++)
                {
                    INode no = ch.GetNode(protoBufArgs[i].name);
                    if (no is IClassNode)
                    {
                        cnArgs[i] = (IClassNode)no;
                    }
                    else if (no is INamedParameterNode)
                    {
                        INamedParameterNode np = (INamedParameterNode)no;
                        cnArgs[i] = (IClassNode)ch.GetNode(np.GetFullArgName());
                    }
                }

                InjectionPlan[] ipArgs = new InjectionPlan[protoBufArgs.Length];

                for (int i = 0; i < protoBufArgs.Length; i++)
                {
                    ipArgs[i] = (InjectionPlan)Deserialize(ch, protoBufArgs[i]);
                }

                IConstructorDef constructor = cn.GetConstructorDef(cnArgs);
                return(new Constructor(cn, constructor, ipArgs));
            }
            if (ip.instance != null)
            {
                InjectionPlanProto.Instance ins = ip.instance;
                object instance = Parse(ip.name, ins.value);
                return(new CsInstance(ch.GetNode(ip.name), instance));
            }
            if (ip.subplan != null)
            {
                InjectionPlanProto.Subplan         subplan       = ip.subplan;
                InjectionPlanProto.InjectionPlan[] protoBufPlans = subplan.plans.ToArray();

                InjectionPlan[] subPlans = new InjectionPlan[protoBufPlans.Length];
                for (int i = 0; i < protoBufPlans.Length; i++)
                {
                    subPlans[i] = (InjectionPlan)Deserialize(ch, protoBufPlans[i]);
                }
                INode n = ch.GetNode(fullName);
                return(new Subplan(n, subPlans));
            }
            Org.Apache.Reef.Utilities.Diagnostics.Exceptions.Throw(new IllegalStateException("Encountered unknown type of InjectionPlan: " + ip), LOGGER);
            return(null);
        }
        public IClassNode GetBoundConstructor(IClassNode cn)
        {
            IClassNode v;

            Builder.BoundConstructors.TryGetValue(cn, out v);

            return v;
        }
Example #11
0
        public IClassNode GetBoundConstructor(IClassNode cn)
        {
            IClassNode v;

            Builder.BoundConstructors.TryGetValue(cn, out v);

            return(v);
        }
Example #12
0
 public void TestDeSerializeClassHierarchyFromJava()
 {
     //the file comes from Java TestClassHierarchyRoundTrip SetUp3 testSimpleConstructors
     IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("simpleConstructorJavaProto.bin");
     IClassNode simpleConstructorNode = (IClassNode)ch.GetNode("org.apache.reef.tang.implementation.SimpleConstructors");
     Assert.AreEqual(simpleConstructorNode.GetChildren().Count, 0);
     Assert.AreEqual(simpleConstructorNode.GetInjectableConstructors().Count, 3);
 }
Example #13
0
        public IConstructorDef GetLegacyConstructor(IClassNode cn)
        {
            IConstructorDef v;

            Builder.LegacyConstructors.TryGetValue(cn, out v);

            return v;
        }
Example #14
0
        public IClassNode GetBoundImplementation(IClassNode cn)
        {
            IClassNode v;

            Builder.BoundImpls.TryGetValue(cn, out v);

            return(v);
        }
Example #15
0
        public IConstructorDef GetLegacyConstructor(IClassNode cn)
        {
            IConstructorDef v;

            Builder.LegacyConstructors.TryGetValue(cn, out v);

            return(v);
        }
        public IClassNode GetBoundImplementation(IClassNode cn)
        {
            IClassNode v;

            Builder.BoundImpls.TryGetValue(cn, out v);

            return v;
        }
Example #17
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));
         }
     }
 }
Example #18
0
        public void TestSimpleConstructors()
        {
            IClassNode cls = (IClassNode)ns.GetNode("Com.Microsoft.Tang.Examples.SimpleConstructors");

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

            Assert.AreEqual(3, def.Count);
        }
Example #19
0
        public void TestSimpleConstructors()
        {
            IClassNode cls = (IClassNode)ns.GetNode(typeof(SimpleConstructors).AssemblyQualifiedName);

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

            Assert.Equal(3, def.Count);
        }
        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);
        }
Example #21
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();
            //  }
            //}
        }
Example #22
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);
        }
Example #23
0
        public void RegisterLegacyConstructor(string s, IList <string> args)
        {
            IClassNode         cn     = (IClassNode)this.ClassHierarchy.GetNode(s);
            IList <IClassNode> cnArgs = new List <IClassNode>();

            for (int i = 0; i < args.Count; i++)
            {
                cnArgs.Add((IClassNode)ClassHierarchy.GetNode(args[i]));
            }
            RegisterLegacyConstructor(cn, cnArgs);
        }
Example #24
0
        public void TestGenericClass()
        {
            IClassHierarchy ns = TangFactory.GetTang().GetClassHierarchy(new string[] { typeof(Timer).Assembly.GetName().Name });

            Type t = typeof(Timer);
            IClassNode EventClassNode = (IClassNode)ns.GetNode(t.AssemblyQualifiedName);
            ProtocolBufferClassHierarchy.Serialize("event.bin", ns);
            IClassHierarchy ch = ProtocolBufferClassHierarchy.DeSerialize("event.bin");
            IClassNode EventClassNode1 = (IClassNode)ns.GetNode(t.AssemblyQualifiedName);
            Assert.AreEqual(EventClassNode.GetName(), EventClassNode1.GetName());
        }
Example #25
0
 public void BindImplementation(IClassNode n, IClassNode m)
 {
     if (this.ClassHierarchy.IsImplementation(n, m))
     {
         BoundImpls.Add(n, m);
     }
     else
     {
         throw new ArgumentException(string.Format("Class {0} does not extend {1}.", m, n));
     }
 }
Example #26
0
        private void WireUpInheritanceRelationships(AvroNode n)
        {
            if (n.classNode != null && !n.classNode.Equals(string.Empty))
            {
                AvroClassNode cn    = (AvroClassNode)n.classNode;
                IClassNode    iface = null;

                try
                {
                    iface = (IClassNode)GetNode(n.fullName);
                }
                catch (NameResolutionException e)
                {
                    Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                    var ex = new IllegalStateException("When reading protocol buffer node "
                                                       + n.fullName + " does not exist.  Full record is " + n, e);
                    Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                }

                foreach (string impl in cn.implFullNames)
                {
                    try
                    {
                        iface.PutImpl((IClassNode)GetNode(impl));
                    }
                    catch (NameResolutionException e)
                    {
                        Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                        var ex = new IllegalStateException("When reading protocol buffer node "
                                                           + n + " refers to non-existent implementation:" + impl);
                        Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                    }
                    catch (InvalidCastException e)
                    {
                        Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                        try
                        {
                            var ex = new IllegalStateException(
                                "When reading protocol buffer node " + n
                                + " found implementation" + GetNode(impl)
                                + " which is not a ClassNode!");
                            Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                        }
                        catch (NameResolutionException ne)
                        {
                            Utilities.Diagnostics.Exceptions.Caught(ne, Level.Error, LOGGER);
                            var ex = new IllegalStateException(
                                "Got 'cant happen' exception when producing error message for " + e);
                            Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                        }
                    }
                }
            }
        }
Example #27
0
 public void BindImplementation(IClassNode n, IClassNode m)
 {
     if (this.ClassHierarchy.IsImplementation(n, m))
     {
         BoundImpls.Add(n, m);
     }
     else
     {
         var ex = new ArgumentException(string.Format("Class {0} does not extend {1}.", m, n));
         Org.Apache.Reef.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
     }
 }
        public static InjectionPlan Deserialize(IClassHierarchy ch, InjectionPlanProto.InjectionPlan ip)
        {
            string fullName = ip.name;

            if (ip.constructor != null)
            {
                InjectionPlanProto.Constructor cons = ip.constructor;
                IClassNode cn = (IClassNode)ch.GetNode(fullName);

                InjectionPlanProto.InjectionPlan[] protoBufArgs = cons.args.ToArray();

                INode[] cnArgs = new INode[protoBufArgs.Length];

                for (int i = 0; i < protoBufArgs.Length; i++)
                {
                    cnArgs[i] = (INode)ch.GetNode(protoBufArgs[i].name);
                }

                InjectionPlan[] ipArgs = new InjectionPlan[protoBufArgs.Length];

                for (int i = 0; i < protoBufArgs.Length; i++)
                {
                    ipArgs[i] = (InjectionPlan)Deserialize(ch, protoBufArgs[i]);
                }

                IConstructorDef constructor = cn.GetConstructorDef(cnArgs);
                return(new Constructor(cn, constructor, ipArgs));
            }
            else if (ip.instance != null)
            {
                InjectionPlanProto.Instance ins = ip.instance;
                object instance = Parse(ip.name, ins.value);
                return(new CsInstance(ch.GetNode(ip.name), instance));
            }
            else if (ip.subplan != null)
            {
                InjectionPlanProto.Subplan         subplan       = ip.subplan;
                InjectionPlanProto.InjectionPlan[] protoBufPlans = subplan.plans.ToArray();

                InjectionPlan[] subPlans = new InjectionPlan[protoBufPlans.Length];
                for (int i = 0; i < protoBufPlans.Length; i++)
                {
                    subPlans[i] = (InjectionPlan)Deserialize(ch, protoBufPlans[i]);
                }
                INode n = ch.GetNode(fullName);
                return(new Subplan(n, subPlans));
            }
            else
            {
                throw new IllegalStateException("Encountered unknown type of injection plan: " + ip);
            }
        }
        /// <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()));
            }
        }
        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);
        }
Example #31
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());
        }
Example #32
0
 private InjectionPlan WrapInjectionPlans(IClassNode infeasibleNode,
                                          List <InjectionPlan> list, bool forceAmbiguous, int selectedIndex)
 {
     if (list.Count == 0)
     {
         return(new Subplan(infeasibleNode, new InjectionPlan[] {}));
     }
     else if ((!forceAmbiguous) && list.Count == 1)
     {
         return(list[0]);
     }
     else
     {
         return(new Subplan(infeasibleNode, selectedIndex, list.ToArray()));
     }
 }
Example #33
0
 private IClassNode ParseDefaultImplementation(IClassNode cn)
 {
     if (cn.GetDefaultImplementation() != null)
     {
         try
         {
             return((IClassNode)this.classHierarchy.GetNode(cn.GetDefaultImplementation()));
         }
         catch (NameResolutionException e)
         {
             var ex = new IllegalStateException("After validation, " + cn + " had a bad default implementation named " + cn.GetDefaultImplementation(), e);
             Org.Apache.REEF.Utilities.Diagnostics.Exceptions.CaughtAndThrow(ex, Level.Error, LOGGER);
         }
     }
     return(null);
 }
Example #34
0
 public Constructor(IClassNode classNode,
     IConstructorDef constructor, InjectionPlan[] args) : base(classNode)
 {
     this.constructor = constructor;
     this.args = args;
     int curAlternatives = 1;
     bool curAmbiguous = false;
     bool curInjectable = true;
     foreach (InjectionPlan plan in args) 
     {
         curAlternatives *= plan.GetNumAlternatives();
         curAmbiguous |= plan.IsAmbiguous();
         curInjectable &= plan.IsInjectable();
     }
     this.numAlternatives = curAlternatives;
     this.isAmbiguous = curAmbiguous;
     this.isInjectable = curInjectable;
 }
Example #35
0
 private IClassNode ParseDefaultImplementation(IClassNode cn)
 {
     if (cn.GetDefaultImplementation() != null)
     {
         try
         {
             return (IClassNode)this.classHierarchy.GetNode(cn.GetDefaultImplementation());
         }
         catch( NameResolutionException e)
         {
             throw new IllegalStateException("After validation, " + cn + " had a bad default implementation named " + cn.GetDefaultImplementation(), e);
         }
     }
     else
     {
         return null;
     }
 }
Example #36
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);
        }
Example #37
0
 private InjectionPlan WrapInjectionPlans(IClassNode infeasibleNode,
     List<InjectionPlan> list, bool forceAmbiguous, int selectedIndex)
 {
     if (list.Count == 0)
     {
         return new Subplan(infeasibleNode, new InjectionPlan[]{});
     }
     else if ((!forceAmbiguous) && list.Count == 1)
     {
         return list[0];
     }
     else
     {
         return new Subplan(infeasibleNode, selectedIndex, list.ToArray());
     }
 }
 /// <summary>
 /// Check if impl is an implementation of inter
 /// </summary>
 /// <param name="inter"></param>
 /// <param name="impl"></param>
 /// <returns></returns>
 public bool IsImplementation(IClassNode inter, IClassNode impl)
 {
     return impl.IsImplementationOf(inter);
 }
 public IConstructorDef GetLegacyConstructor(IClassNode cn)
 {
     throw new NotImplementedException();
 }
 public IClassNode GetBoundImplementation(IClassNode cn)
 {
     throw new NotImplementedException();
 }
Example #41
0
 public void PutImpl(IClassNode impl)
 {
     knownImpls.Add(impl);
 }
Example #42
0
 public void RegisterLegacyConstructor(IClassNode cn, IList<IClassNode> args)
 {
     LegacyConstructors.Add(cn, cn.GetConstructorDef(args));
 }
        public static Org.Apache.REEF.Tang.Implementations.InjectionPlan.InjectionPlan Deserialize(IClassHierarchy ch, Org.Apache.REEF.Tang.Protobuf.InjectionPlan ip) 
        {
            string fullName = ip.name;
            if (ip.constructor != null) 
            {
                Org.Apache.REEF.Tang.Protobuf.Constructor cons = ip.constructor;
                IClassNode cn = (IClassNode) ch.GetNode(fullName);

                Org.Apache.REEF.Tang.Protobuf.InjectionPlan[] protoBufArgs = cons.args.ToArray();

                IClassNode[] cnArgs = new IClassNode[protoBufArgs.Length];

                for (int i = 0; i < protoBufArgs.Length; i++) 
                {
                    INode no = ch.GetNode(protoBufArgs[i].name);
                    if (no is IClassNode)
                    {
                        cnArgs[i] = (IClassNode)no;
                    }
                    else if (no is INamedParameterNode)
                    {
                        INamedParameterNode np = (INamedParameterNode)no;
                        cnArgs[i] = (IClassNode)ch.GetNode(np.GetFullArgName());
                    }
                }

                Org.Apache.REEF.Tang.Implementations.InjectionPlan.InjectionPlan[] ipArgs = new Org.Apache.REEF.Tang.Implementations.InjectionPlan.InjectionPlan[protoBufArgs.Length];

                for (int i = 0; i < protoBufArgs.Length; i++) 
                {
                    ipArgs[i] = (Org.Apache.REEF.Tang.Implementations.InjectionPlan.InjectionPlan)Deserialize(ch, protoBufArgs[i]);
                }

                IConstructorDef constructor = cn.GetConstructorDef(cnArgs);
                return new Org.Apache.REEF.Tang.Implementations.InjectionPlan.Constructor(cn, constructor, ipArgs);
            }
            if (ip.instance != null) 
            {
                Org.Apache.REEF.Tang.Protobuf.Instance ins = ip.instance;
                object instance = Parse(ip.name, ins.value);
                return new CsInstance(ch.GetNode(ip.name), instance);
            } 
            if (ip.subplan != null) 
            {
                Org.Apache.REEF.Tang.Protobuf.Subplan subplan = ip.subplan;
                Org.Apache.REEF.Tang.Protobuf.InjectionPlan[] protoBufPlans = subplan.plans.ToArray();

                Org.Apache.REEF.Tang.Implementations.InjectionPlan.InjectionPlan[] subPlans = new Org.Apache.REEF.Tang.Implementations.InjectionPlan.InjectionPlan[protoBufPlans.Length];
                for (int i = 0; i < protoBufPlans.Length; i++) 
                {
                    subPlans[i] = (Org.Apache.REEF.Tang.Implementations.InjectionPlan.InjectionPlan)Deserialize(ch, protoBufPlans[i]);
                }
                INode n = ch.GetNode(fullName);
                return new Org.Apache.REEF.Tang.Implementations.InjectionPlan.Subplan(n, subPlans);
            } 
            Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new IllegalStateException("Encountered unknown type of InjectionPlan: " + ip), LOGGER);
            return null;
        }
 public void BindImplementation(IClassNode n, IClassNode m)
 {
     if (this.ClassHierarchy.IsImplementation(n, m))
     {
         BoundImpls.Add(n, m);
     }
     else
     {
         throw new ArgumentException(string.Format("Class {0} does not extend {1}.", m, n));
     }
 }
Example #45
0
 public void BindImplementation(IClassNode n, IClassNode m)
 {
     if (this.ClassHierarchy.IsImplementation(n, m))
     {
         BoundImpls.Add(n, m);
     }
     else
     {
         var ex = new ArgumentException(string.Format("Class {0} does not extend {1}.", m, n));
         Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
     }
 }
Example #46
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;
            }
        }
 public IClassNode GetBoundConstructor(IClassNode cn)
 {
     throw new NotImplementedException();
 }
Example #48
0
 public bool IsImplementationOf(IClassNode inter)
 {
     List<IClassNode> worklist = new List<IClassNode>();
     if (this.Equals(inter))
     {
         return true;
     }
     worklist.Add(inter);
     while (worklist.Count != 0)
     {
         IClassNode cn = worklist[worklist.Count - 1];
         worklist.RemoveAt(worklist.Count - 1);
         ISet<IClassNode> impls = cn.GetKnownImplementations();
         if (impls.Contains(this))
         {
             return true;
         }
         worklist.AddRange(impls);
     }
     return false;
 }
Example #49
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);
         }
     }
 }