Exemplo n.º 1
0
        private static void AddConfiguration(IConfigurationBuilder conf, StreamReader reader)
        {
            IList <KeyValuePair <string, string> > settings = new List <KeyValuePair <string, string> >();

            while (!reader.EndOfStream)
            {
                string   line = reader.ReadLine();
                string[] p    = line.Split('=');
                if (p.Length == 2)
                {
                    settings.Add(new KeyValuePair <string, string>(GetAssemblyName(p[0]), GetAssemblyName(p[1])));
                }
                else if (p.Length > 2)
                {
                    string v = line.Substring(p[0].Length + 1, line.Length - p[0].Length - 1);
                    settings.Add(new KeyValuePair <string, string>(GetAssemblyName(p[0]), GetAssemblyName(v)));
                }
                else
                {
                    var e = new TangApplicationException("Config data is not in format of KeyValuePair: " + line);
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
            }
            ProcessConfigData(conf, settings);
        }
Exemplo n.º 2
0
        public AvroConfiguration AvroDeserializeFromFile(string fileName)
        {
            AvroConfiguration avroConf = null;

            try
            {
                using (var buffer = new MemoryStream())
                {
                    if (!ReadFile(buffer, fileName))
                    {
                        var e = new TangApplicationException("Error during file operation. Quitting method : " + fileName);
                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                    }

                    buffer.Seek(0, SeekOrigin.Begin);
                    using (var reader = new SequentialReader <AvroConfiguration>(AvroContainer.CreateReader <AvroConfiguration>(buffer, true)))
                    {
                        var results = reader.Objects;

                        if (results != null)
                        {
                            avroConf = (AvroConfiguration)results.First();
                        }
                    }
                }
            }
            catch (SerializationException ex)
            {
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(ex, Level.Error, LOGGER);
                var e = new TangApplicationException("Cannot deserialize the file: " + fileName, ex);
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
            }

            return(avroConf);
        }
Exemplo n.º 3
0
 public object GetNamedInstance(Type t)
 {
     if (!ReflectionUtilities.IsAssignableFromIgnoreGeneric(typeof(Name <>), t))
     {
         var ex = new TangApplicationException(string.Format(CultureInfo.CurrentCulture, "The parameter {0} is not inherit from Name<>", t));
         Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
     }
     return(GetInstance(classHierarchy.GetNode(t)));
 }
Exemplo n.º 4
0
 /// <summary>
 /// Determines whether [is generic typeof] [the specified iface].
 /// </summary>
 /// <param name="iface">The iface.</param>
 /// <param name="type">The type.</param>
 /// <returns>
 ///   <c>true</c> if [is generic typeof] [the specified iface]; otherwise, <c>false</c>.
 /// </returns>
 /// <exception cref="TangApplicationException">The type passed in IsGenericTypeof is null: iface : + iface + type: + type + .</exception>
 public static bool IsGenericTypeof(Type iface, Type type)
 {
     if (iface == null || type == null)
     {
         var ex = new TangApplicationException(string.Format(CultureInfo.CurrentCulture,
                                                             "The type passed in IsGenericTypeof is null: iface : {0} type: {1}. ",
                                                             iface, type));
         Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
     }
     if (type.IsGenericType)
     {
         if (GetAssemblyQualifiedName(iface).Equals(GetAssemblyQualifiedNameForGeneric(type)))
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Serialize a ClassHierarchy into a file
        /// </summary>
        /// <param name="c"></param>
        /// <param name="fileName"></param>
        public void ToFile(IClassHierarchy c, string fileName)
        {
            var avroNodeData = ToAvroNode(c);

            using (var buffer = new MemoryStream())
            {
                using (var w = AvroContainer.CreateWriter <AvroNode>(buffer, Codec.Null))
                {
                    using (var writer = new SequentialWriter <AvroNode>(w, 24))
                    {
                        writer.Write(avroNodeData);
                    }
                }

                if (!WriteFile(buffer, fileName))
                {
                    var e = new TangApplicationException("Error during file operation. Quitting method: " + fileName);
                    Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
            }
        }
 private void AddAlias(INamedParameterNode np)
 {
     if (!string.IsNullOrEmpty(np.GetAlias()))
     {
         IDictionary <string, string> mapping = null;
         _aliasLookupTable.TryGetValue(np.GetAliasLanguage().ToString(), out mapping);
         if (mapping == null)
         {
             mapping = new Dictionary <string, string>();
             _aliasLookupTable.Add(np.GetAliasLanguage().ToString(), mapping);
         }
         try
         {
             mapping.Add(np.GetAlias(), np.GetFullName());
         }
         catch (Exception)
         {
             var e = new TangApplicationException(string.Format(CultureInfo.CurrentCulture, "Duplicated alias {0} on named parameter {1}.", np.GetAlias(), np.GetFullName()));
             Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
         }
     }
 }
Exemplo n.º 7
0
        public void ToFile(IConfiguration c, string fileName)
        {
            var avronConfigurationData = ToAvroConfiguration(c);

            using (var buffer = new MemoryStream())
            {
                using (var w = AvroContainer.CreateWriter <AvroConfiguration>(buffer, Codec.Null))
                {
                    using (var writer = new SequentialWriter <AvroConfiguration>(w, 24))
                    {
                        // Serialize the data to stream using the sequential writer
                        writer.Write(avronConfigurationData);
                    }
                }

                if (!WriteFile(buffer, fileName))
                {
                    var e = new TangApplicationException("Error during file operation. Quitting method: " + fileName);
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
            }
        }
Exemplo n.º 8
0
        public object InjectFromPlan(InjectionPlan plan)
        {
            if (!plan.IsFeasible())
            {
                var ex = new InjectionException("Cannot inject " + plan.GetNode().GetFullName() + ": "
                                                + plan.ToCantInjectString());
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
            }

            if (plan.IsAmbiguous())
            {
                var ex = new InjectionException("Cannot inject " + plan.GetNode().GetFullName() + " "
                                                + plan.ToCantInjectString());
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
            }

            if (plan is InjectionFuturePlan)
            {
                InjectionFuturePlan fut = (InjectionFuturePlan)plan;
                INode  node             = fut.GetNode();
                string key = node.GetFullName();
                try
                {
                    Type t        = null;
                    Type nodeType = classHierarchy.ClassForName(node.GetFullName());

                    if (node is IClassNode)
                    {
                        t = nodeType;
                    }
                    else if (node is INamedParameterNode)
                    {
                        var nn = (INamedParameterNode)node;
                        t = classHierarchy.ClassForName(nn.GetFullArgName());
                        if (nn.IsSet())
                        {
                            t = typeof(ISet <>).MakeGenericType(new Type[] { t });
                        }
                    }
                    else
                    {
                        var ex = new TangApplicationException("Unexpected node type. Wanted ClassNode or NamedParameterNode.  Got: " + node);
                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                    }

                    // Java - InjectionFuture<?> ret = new InjectionFuture<>(this, javaNamespace.classForName(fut.getNode().getFullName()));
                    // C# - InjectionFuture<object> ret = new InjectionFutureImpl<object>(this, classHierarchy.ClassForName(fut.GetNode().GetFullName()));
                    // We cannot simply create an object from generic with object as <T>
                    // typeof(InjectionFutureImpl<>).MakeGenericType(t) will get the InjectionFutureImpl generic Type with <T> as t
                    // for ClassNode, t is the Type of the class, for NamedParameterNode, t is the Type of the argument
                    // we then use reflection to invoke the constructor
                    // To retain generic argument information??
                    Type injectionFuture          = typeof(InjectionFutureImpl <>).MakeGenericType(t);
                    var  constructor              = injectionFuture.GetConstructor(new Type[] { typeof(IInjector), typeof(Type) });
                    IInjectionFuture <object> ret = (IInjectionFuture <object>)constructor.Invoke(new object[] { this, nodeType });

                    pendingFutures.Add(ret);
                    return(ret);
                }
                catch (TypeLoadException e)
                {
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new InjectionException("Could not get class for " + key), LOGGER);
                }
            }
            else if (plan.GetNode() is IClassNode && GetCachedInstance((IClassNode)plan.GetNode()) != null)
            {
                return(GetCachedInstance((IClassNode)plan.GetNode()));
            }
            else if (plan is CsInstance)
            {
                // TODO: Must be named parameter node.  Check.
                // throw new IllegalStateException("Instance from plan not in Injector's set of instances?!?");
                return(((CsInstance)plan).instance);
            }
            else if (plan is Constructor)
            {
                Constructor     constructor = (Constructor)plan;
                object[]        args        = new object[constructor.GetArgs().Length];
                InjectionPlan[] argPlans    = constructor.GetArgs();

                for (int i = 0; i < argPlans.Length; i++)
                {
                    args[i] = InjectFromPlan(argPlans[i]);
                }

                try
                {
                    concurrentModificationGuard = true;
                    object ret = null;
                    try
                    {
                        IConstructorDef def = (IConstructorDef)constructor.GetConstructorDef();
                        ConstructorInfo c   = GetConstructor(def);

                        if (aspect != null)
                        {
                            ret = aspect.Inject(def, c, args);
                        }
                        else
                        {
                            ret = c.Invoke(args);
                        }
                    }
                    catch (ArgumentException e)
                    {
                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                        StringBuilder sb = new StringBuilder("Internal Tang error?  Could not call constructor " + constructor.GetConstructorDef() + " with arguments [");
                        foreach (object o in args)
                        {
                            sb.Append("\n\t" + o);
                        }
                        sb.Append("]");
                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new IllegalStateException(sb.ToString(), e), LOGGER);
                    }
                    if (ret is IExternalConstructor <object> )
                    {
                        ret = ((IExternalConstructor <object>)ret).NewInstance();
                    }
                    instances.Add(constructor.GetNode(), ret);
                    return(ret);
                }
                catch (TargetInvocationException e)
                {
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new InjectionException("Could not invoke constructor: " + plan, e), LOGGER);
                }
                finally
                {
                    concurrentModificationGuard = false;
                }
            }
            else if (plan is Subplan)
            {
                Subplan ambiguous = (Subplan)plan;
                return(InjectFromPlan(ambiguous.GetDelegatedPlan()));
            }
            else if (plan is SetInjectionPlan)
            {
                SetInjectionPlan setPlan   = (SetInjectionPlan)plan;
                INode            n         = setPlan.GetNode();
                string           typeOfSet = null;

                // TODO: This doesn't work for sets of generics (e.g., Set<Foo<int>>
                // because GetFullName and GetFullArgName strip generic info).
                if (n is INamedParameterNode)
                {
                    INamedParameterNode np = (INamedParameterNode)n;
                    typeOfSet = np.GetFullArgName();
                }
                else if (n is IClassNode)
                {
                    typeOfSet = n.GetFullName();
                }
                else
                {
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new TangApplicationException("Unknown node type :" + n.ToString()), LOGGER);
                }

                Type t = classHierarchy.ClassForName(typeOfSet);

                // MakeGenericType(t = int: MonotonicHashSet<> -> MonotonicHashSet<int>
                // Get constructor: MonotonicHashSet<int> -> public MonotonicHashSet<int>() { ... }
                // Invoke: public MonotonicHashSet<int> -> new MonotonicHashSet<int>()
                object ret = typeof(MonotonicHashSet <>).MakeGenericType(t).GetConstructor(new Type[] { }).Invoke(new object[] { }); // (this, classHierarchy.ClassForName(fut.GetNode().GetFullName()));

                MethodInfo mf = ret.GetType().GetMethod("Add");

                foreach (InjectionPlan subplan in setPlan.GetEntryPlans())
                {
                    // ret.Add(InjectFromPlan(subplan));
                    mf.Invoke(ret, new object[] { InjectFromPlan(subplan) });
                }
                return(ret);
            }
            else if (plan is ListInjectionPlan)
            {
                ListInjectionPlan listPlan   = (ListInjectionPlan)plan;
                INode             n          = listPlan.GetNode();
                string            typeOfList = null;

                if (n is INamedParameterNode)
                {
                    INamedParameterNode np = (INamedParameterNode)n;
                    typeOfList = np.GetFullArgName();
                }
                else if (n is IClassNode)
                {
                    typeOfList = n.GetFullName();
                }
                else
                {
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new TangApplicationException("Unknown node type :" + n.ToString()), LOGGER);
                }

                Type   t   = classHierarchy.ClassForName(typeOfList);
                object ret = typeof(List <>).MakeGenericType(t).GetConstructor(new Type[] { }).Invoke(new object[] { });

                MethodInfo mf = ret.GetType().GetMethod("Add");

                foreach (InjectionPlan subplan in listPlan.GetEntryPlans())
                {
                    mf.Invoke(ret, new object[] { InjectFromPlan(subplan) });
                }
                return(ret);
            }
            else
            {
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new IllegalStateException("Unknown plan type: " + plan), LOGGER);
            }
            return(null); // should never reach here
        }
Exemplo n.º 9
0
        public INode BuildPathToNode(Type type)
        {
            INode parent = GetParentNode(type);

            Type argType = ReflectionUtilities.GetNamedParameterTargetOrNull(type);

            if (argType == null)
            {
                return(NodeFactory.CreateClassNode(parent, type));
            }
            INamedParameterNode np = NodeFactory.CreateNamedParameterNode(parent, type, argType);

            if (Parameterparser.CanParse(ReflectionUtilities.GetAssemblyQualifiedName(argType)))
            {
                if (type.GetCustomAttribute <NamedParameterAttribute>().DefaultClass != null)
                {
                    var e = new ClassHierarchyException("Named parameter " + ReflectionUtilities.GetAssemblyQualifiedName(type) + " defines default implementation for parsable type " + ReflectionUtilities.GetAssemblyQualifiedName(argType));
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
            }

            if (!string.IsNullOrEmpty(np.GetAlias()))
            {
                var aliasLanguage = np.GetAliasLanguage().ToString();
                IDictionary <string, string> mapping;
                if (!_aliasLookupTable.TryGetValue(aliasLanguage, out mapping))
                {
                    mapping = new Dictionary <string, string>();
                    _aliasLookupTable.Add(aliasLanguage, mapping);
                }
                try
                {
                    mapping.Add(np.GetAlias(), np.GetFullName());
                }
                catch (Exception)
                {
                    var e = new TangApplicationException(string.Format(CultureInfo.CurrentCulture, "Duplicated alias {0} on named parameter {1}.", np.GetAlias(), np.GetFullName()));
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
            }

            string shortName = np.GetShortName();

            if (shortName != null && !shortName.Equals(string.Empty))
            {
                INamedParameterNode oldNode = null;
                shortNames.TryGetValue(shortName, out oldNode);
                if (oldNode != null)
                {
                    if (oldNode.GetFullName().Equals(np.GetFullName()))
                    {
                        var ex = new IllegalStateException("Tried to double bind "
                                                           + oldNode.GetFullName() + " to short name " + shortName);
                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                    }
                    var e = new ClassHierarchyException("Named parameters " + oldNode.GetFullName()
                                                        + " and " + np.GetFullName() + " have the same short name: "
                                                        + shortName);
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
                shortNames.Add(shortName, np);
            }
            return(np);
        }