public void SearchParent() { try { Configuration configuration = ReadConfiguration(); Assert.NotNull(configuration); string path = "root/configuration/node_1/ELEMENT_LIST"; AbstractConfigNode node = configuration.Find(path); Assert.NotNull(node); Assert.Equal(path, node.GetSearchPath()); path = "../node_2/node_3/../#"; node = node.Find(path); Assert.NotNull(node); Assert.True(node.GetType() == typeof(ConfigParametersNode)); LogUtils.Debug(node.GetAbsolutePath()); } catch (Exception ex) { LogUtils.Error(ex); throw ex; } }
public void SearchWildcar() { try { Configuration configuration = ReadConfiguration(); Assert.NotNull(configuration); string path = "root/configuration/node_1/node_2/node_3/*"; AbstractConfigNode node = configuration.Find(path); Assert.NotNull(node); Assert.True(node.GetType() == typeof(ConfigSearchResult)); path = "configuration/node_1/node_2/node_3/*/LONG_VALUE_LIST"; node = configuration.Find(path); Assert.NotNull(node); Assert.True(node.GetType() == typeof(ConfigListValueNode)); Assert.Equal(8, ((ConfigListValueNode)node).Count()); LogUtils.Debug(node.GetAbsolutePath()); } catch (Exception ex) { LogUtils.Error(ex); throw ex; } }
public void SearchRecursive() { try { Configuration configuration = ReadConfiguration(); Assert.NotNull(configuration); String path = "root/**/updatedBy"; AbstractConfigNode node = configuration.Find(path); Assert.NotNull(node); Assert.True(node.GetType() == typeof(ConfigSearchResult)); path = "/**/node_2/#PARAM_1"; node = node.Find(path); Assert.NotNull(node); Assert.True(node.GetType() == typeof(ConfigValueNode)); LogUtils.Debug("NODE>>", node); } catch (Exception ex) { LogUtils.Error(ex); throw ex; } }
/// <summary> /// Process the annotated field and set the values from the configuration value. /// </summary> /// <typeparam name="T">Target Instance type</typeparam> /// <param name="node">Configuration Node</param> /// <param name="target">Target Type instance.</param> /// <param name="field">Property to update</param> /// <param name="configValue">Config value annotation</param> /// <returns>Updated Target Type instance.</returns> private static T ProcessField <T>(ConfigPathNode node, T target, FieldInfo field, ConfigValue configValue, List <string> valuePaths) { string pname = configValue.Name; if (String.IsNullOrWhiteSpace(pname)) { pname = field.Name; } string value = null; if (!String.IsNullOrWhiteSpace(configValue.Path)) { AbstractConfigNode nnode = node.Find(configValue.Path); if (nnode != null && nnode.GetType() == typeof(ConfigPathNode)) { node = (ConfigPathNode)nnode; } else { node = null; } } if (node != null) { AbstractConfigNode cnode = node.GetChildNode(pname); if (cnode != null) { if (valuePaths != null) { valuePaths.Add(cnode.GetSearchPath()); } if (cnode.GetType() == typeof(ConfigValueNode)) { ConfigValueNode vn = (ConfigValueNode)cnode; if (vn != null) { value = vn.GetValue(); } if (!String.IsNullOrWhiteSpace(value)) { object v = GetValue <T>(pname, value, configValue.Function, field.FieldType, target, configValue.Required); if (v != null) { TypeUtils.CallSetter(field, target, v); } } } else { if (ReflectionUtils.IsSubclassOfRawGeneric(field.FieldType, typeof(List <>))) { if (cnode.GetType() == typeof(ConfigListValueNode)) { ConfigListValueNode configList = (ConfigListValueNode)cnode; List <string> values = configList.GetValueList(); if (values != null) { Type inner = field.FieldType.GetGenericArguments()[0]; object v = ReflectionUtils.ConvertListFromStrings(inner, values); if (v != null) { TypeUtils.CallSetter(field, target, v); } } } } else if (ReflectionUtils.IsSubclassOfRawGeneric(field.FieldType, typeof(HashSet <>))) { if (cnode.GetType() == typeof(ConfigListValueNode)) { ConfigListValueNode configList = (ConfigListValueNode)cnode; List <string> values = configList.GetValueList(); if (values != null) { Type inner = field.FieldType.GetGenericArguments()[0]; object v = ReflectionUtils.ConvertSetFromStrings(inner, values); if (v != null) { TypeUtils.CallSetter(field, target, v); } } } } } } } object ov = TypeUtils.CallGetter(field, target); if (ov == null && configValue.Required) { throw AnnotationProcessorException.Throw(target.GetType(), pname); } return(target); }
/// <summary> /// Create a new Instance of the specified type. /// /// Type should have an empty constructor or a constructor with annotation. /// </summary> /// <typeparam name="T">Target Instance type</typeparam> /// <param name="type">Type</param> /// <param name="node">Configuration node.</param> /// <returns>Created Instance</returns> public static T CreateInstance <T>(Type type, ConfigPathNode node) { T target = default(T); ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); if (constructors != null && constructors.Length > 0) { foreach (ConstructorInfo ci in constructors) { MethodInvoke mi = (MethodInvoke)Attribute.GetCustomAttribute(ci, typeof(MethodInvoke)); if (mi != null) { ParameterInfo[] parameters = ci.GetParameters(); ConfigPathNode nnode = node; if (parameters != null && parameters.Length > 0) { if (!String.IsNullOrWhiteSpace(mi.Path)) { AbstractConfigNode cnode = nnode.Find(mi.Path); if (cnode != null && cnode.GetType() == typeof(ConfigPathNode)) { nnode = (ConfigPathNode)cnode; } } if (nnode != null) { ConfigParametersNode pnode = nnode.GetParameters(); if (pnode != null) { List <object> values = FindParameters(pnode, ci.Name, parameters); if (values != null && values.Count > 0) { target = (T)Activator.CreateInstance(type, values.ToArray()); break; } } } } else { target = Activator.CreateInstance <T>(); break; } } } } if (ReflectionUtils.IsNull(target)) { target = Activator.CreateInstance <T>(); } if (!ReflectionUtils.IsNull(target)) { target = ReadValues((ConfigPathNode)node, target, null); CallMethodInvokes((ConfigPathNode)node, target); } else { throw new AnnotationProcessorException(String.Format("Error creating instance of Type: [path={0}][type={1}]", node.GetSearchPath(), type.FullName)); } return(target); }
/// <summary> /// Set the target instance values reading from the passed configuration node. /// </summary> /// <typeparam name="T">Target Instance type</typeparam> /// <param name="parent">Configuration node instance</param> /// <param name="target">Target Type instance</param> /// <returns>Updated Target Type instance</returns> public static T Process <T>(AbstractConfigNode parent, T target) { List <string> valuePaths = null; return(Process <T>(parent, target, out valuePaths)); }
/// <summary> /// Get a File/Blob resource as a stream. Method is applicable only for Zip/Directory Resources. /// </summary> /// <param name="configuration">Configuration instance.</param> /// <param name="path">Search path for the resource node.</param> /// <param name="file">Sub-path for the file</param> /// <returns>Stream Reader</returns> public static StreamReader GetResourceStream(this Configuration configuration, string path, string file) { Preconditions.CheckArgument(configuration); Preconditions.CheckArgument(path); Preconditions.CheckArgument(file); AbstractConfigNode node = configuration.Find(path); if (node != null && typeof(ConfigResourceNode).IsAssignableFrom(node.GetType())) { ConfigResourceNode rnode = (ConfigResourceNode)node; if (rnode.GetType() == typeof(ConfigResourceZip)) { ConfigResourceZip fnode = (ConfigResourceZip)rnode; if (fnode.Downloaded) { Conditions.NotNull(fnode.File); FileInfo fi = new FileInfo(fnode.File.FullName); if (!fi.Exists) { throw new ConfigurationException(String.Format("Invalid File Resource Node: File not found. [file={0}]", fi.FullName)); } string filename = String.Format("{0}/{1}", fi.FullName, file); fi = new FileInfo(filename); if (!fi.Exists) { throw new ConfigurationException(String.Format("File not found. [file={0}]", fi.FullName)); } return(new StreamReader(fi.FullName)); } else { lock (fnode) { DownloadResource(fnode); UnzipResource(fnode); } string filename = String.Format("{0}/{1}", fnode.Directory.FullName, file); FileInfo fi = new FileInfo(filename); if (!fi.Exists) { throw new ConfigurationException(String.Format("Invalid File Resource Node: File not found. [file={0}]", fi.FullName)); } return(new StreamReader(fi.FullName)); } } else if (rnode.GetType() == typeof(ConfigDirectoryResource)) { ConfigDirectoryResource dnode = (ConfigDirectoryResource)rnode; if (!dnode.Directory.Exists) { throw new ConfigurationException(String.Format("Directory not found. [file={0}]", dnode.Directory.FullName)); } string filename = String.Format("{0}/{1}", dnode.Directory.FullName, file); FileInfo fi = new FileInfo(filename); if (!fi.Exists) { throw new ConfigurationException(String.Format("Invalid File Resource Node: File not found. [file={0}]", fi.FullName)); } return(new StreamReader(fi.FullName)); } } return(null); }
/// <summary> /// Recursively replace defined variables with properties in the configuration nodes. /// /// </summary> /// <param name="node">Configuration Node.</param> /// <param name="inProps">Scoped properties map</param> /// <param name="replace">Replace variables?</param> private void NodePostLoad(AbstractConfigNode node, Dictionary <string, ConfigValueNode> inProps, bool replace) { Dictionary <string, ConfigValueNode> properties = General.Clone <string, ConfigValueNode>(inProps); if (node.GetType() == typeof(ConfigPathNode)) { ConfigPathNode pnode = (ConfigPathNode)node; ConfigPropertiesNode props = pnode.GetProperties(); if (props != null && !props.IsEmpty()) { Dictionary <string, ConfigValueNode> pd = props.GetValues(); foreach (string key in pd.Keys) { if (!properties.ContainsKey(key)) { properties.Add(key, pd[key]); } else { properties[key] = pd[key]; } } } if (!pnode.IsEmpty()) { foreach (string key in pnode.GetChildren().Keys) { NodePostLoad(pnode.GetChildren()[key], properties, replace); } } } else { if (node.GetType() == typeof(ConfigParametersNode)) { ConfigParametersNode pnode = (ConfigParametersNode)node; if (!pnode.IsEmpty() && replace) { foreach (string key in pnode.GetValues().Keys) { ConfigValueNode vn = pnode.GetValue(key); string value = vn.GetValue(); if (!String.IsNullOrWhiteSpace(value)) { string nv = ReplaceVariable(value, properties); vn.SetValue(nv); } } } } else if (node.GetType() == typeof(ConfigAttributesNode)) { ConfigAttributesNode pnode = (ConfigAttributesNode)node; if (!pnode.IsEmpty() && replace) { foreach (string key in pnode.GetValues().Keys) { ConfigValueNode vn = pnode.GetValue(key); string value = vn.GetValue(); if (!String.IsNullOrWhiteSpace(value)) { string nv = ReplaceVariable(value, properties); vn.SetValue(nv); } } } } else if (node.GetType() == typeof(ConfigListValueNode)) { ConfigListValueNode pnode = (ConfigListValueNode)node; if (!pnode.IsEmpty() && replace) { foreach (ConfigValueNode vn in pnode.GetValues()) { string value = vn.GetValue(); if (!String.IsNullOrWhiteSpace(value)) { string nv = ReplaceVariable(value, properties); vn.SetValue(nv); } } } } else if (node.GetType() == typeof(ConfigElementListNode)) { ConfigElementListNode pnode = (ConfigElementListNode)node; if (!pnode.IsEmpty()) { foreach (ConfigElementNode vn in pnode.GetValues()) { NodePostLoad(vn, properties, replace); } } } else if (node.GetType() == typeof(ConfigValueNode)) { if (replace) { ConfigValueNode vn = (ConfigValueNode)node; string value = vn.GetValue(); if (!String.IsNullOrWhiteSpace(value)) { string nv = ReplaceVariable(value, properties); vn.SetValue(nv); } } } } }
public override void Configure(AbstractConfigNode node) { throw new NotImplementedException(); }
public abstract void Configure(AbstractConfigNode node);
/// <summary> /// Create/Get an instance of an autowired object. /// </summary> /// <typeparam name="T">Type of Object</typeparam> /// <param name="configName">Configuration Name (should be loaded)</param> /// <param name="path">Path in the configuration</param> /// <param name="update">Node path updated</param> /// <returns>Object Instance</returns> private T AutowireType <T>(string configName, string path) { Preconditions.CheckArgument(configName); Type type = typeof(T); string key = GetTypeKey(type, path, configName); if (!String.IsNullOrWhiteSpace(key)) { if (!autowiredObjects.ContainsKey(key)) { lock (autowiredObjects) { if (!autowiredObjects.ContainsKey(key)) { Configuration config = ReadLockConfig(configName, DEFAULT_READ_LOCK_TIMEOUT); if (config != null) { try { T value = default(T); value = Activator.CreateInstance <T>(); autowiredObjects[key] = value; List <string> valuePaths = null; if (!String.IsNullOrWhiteSpace(path)) { AbstractConfigNode node = config.Find(path); if (node == null) { throw new ConfigurationException( String.Format("Specified configuration node not found. [config={0}][path={1}]", configName, path)); } ConfigurationAnnotationProcessor.Process <T>(node, value, out valuePaths); } else { ConfigurationAnnotationProcessor.Process <T>(config, value, out valuePaths); } if (valuePaths != null && valuePaths.Count > 0 && (config.SyncMode == ESyncMode.BATCH || config.SyncMode == ESyncMode.EVENTS)) { AutowiredIndexStruct ais = new AutowiredIndexStruct(); ais.ConfigName = configName; ais.Type = type; ais.RelativePath = path; ais.Instance = value; foreach (string vp in valuePaths) { string vk = GetTypeIndexKey(vp, configName); autowiredIndex.Add(vk, ais); } } } finally { ConfigReleaseRead(config.Header.Name); } } else { throw new ConfigurationException( String.Format("Error getting confguration. (Might be a lock timeout) [name={0}]", configName)); } } } } return((T)autowiredObjects[key]); } throw new ConfigurationException( String.Format("Error creating autowired instance. [type={0}][config={1}]", type.FullName, configName)); }
/// <summary> /// Parse a configuration node. /// </summary> /// <param name="name">Config node name</param> /// <param name="elem">XML Element</param> /// <param name="nodeStack">Current Node Stack</param> private void ParseBodyNode(string name, XmlElement elem, Stack <AbstractConfigNode> nodeStack) { bool popStack = false; bool processed = false; AbstractConfigNode parent = nodeStack.Peek(); if (IsTextNode(elem)) { bool encrypted = false; if (elem.HasAttributes) { string attr = elem.Attributes[XML_VALUE_ENCRYPTED].Value; if (!String.IsNullOrWhiteSpace(attr)) { if (attr.CompareTo("true") == 0) { encrypted = true; } } } AddValueNode(parent, elem.Name, elem.FirstChild.Value, encrypted); } else { XmlNodeType nt = IsListNode(elem); if (nt == XmlNodeType.Element) { if (parent.GetType() != typeof(ConfigPathNode)) { throw new ConfigurationException(String.Format("Invalid Stack State: Cannot add List node to parent. [parent={0}]", parent.GetType().FullName)); } ConfigPathNode pnode = (ConfigPathNode)parent; ConfigElementListNode nodeList = new ConfigElementListNode(parent.Configuration, parent); nodeList.Name = name; pnode.AddChildNode(nodeList); nodeStack.Push(nodeList); popStack = true; } else if (nt == XmlNodeType.Text) { if (parent.GetType() != typeof(ConfigPathNode)) { throw new ConfigurationException(String.Format("Invalid Stack State: Cannot add List node to parent. [parent={0}]", parent.GetType().FullName)); } ConfigPathNode pnode = (ConfigPathNode)parent; ConfigListValueNode nodeList = new ConfigListValueNode(parent.Configuration, parent); nodeList.Name = name; pnode.AddChildNode(nodeList); nodeStack.Push(nodeList); popStack = true; } else { if (elem.Name == ConstXmlConfigIncludeNode.XML_CONFIG_INCLUDE) { if (parent.GetType() != typeof(ConfigPathNode)) { throw new ConfigurationException(String.Format("Invalid Stack State: Cannot add List node to parent. [parent={0}]", parent.GetType().FullName)); } ConfigPathNode pnode = (ConfigPathNode)parent; AddIncludeNode(pnode, elem); processed = true; } else if (elem.Name == ConstXmlResourceNode.XML_CONFIG_NODE_RESOURCE) { if (parent.GetType() != typeof(ConfigPathNode)) { throw new ConfigurationException(String.Format("Invalid Stack State: Cannot add List node to parent. [parent={0}]", parent.GetType().FullName)); } ConfigPathNode pnode = (ConfigPathNode)parent; AddResourceNode(pnode, elem); processed = true; } else if (elem.Name == settings.ParametersNodeName) { if (parent.GetType() != typeof(ConfigPathNode)) { throw new ConfigurationException(String.Format("Invalid Stack State: Cannot add List node to parent. [parent={0}]", parent.GetType().FullName)); } ConfigPathNode pnode = (ConfigPathNode)parent; ConfigParametersNode paramNode = new ConfigParametersNode(parent.Configuration, parent); paramNode.Name = name; pnode.AddChildNode(paramNode); nodeStack.Push(paramNode); popStack = true; } else if (elem.Name == settings.PropertiesNodeName) { if (parent.GetType() != typeof(ConfigPathNode)) { throw new ConfigurationException(String.Format("Invalid Stack State: Cannot add List node to parent. [parent={0}]", parent.GetType().FullName)); } ConfigPathNode pnode = (ConfigPathNode)parent; ConfigPropertiesNode propNode = new ConfigPropertiesNode(parent.Configuration, parent); propNode.Name = name; pnode.AddChildNode(propNode); nodeStack.Push(propNode); popStack = true; } else { ConfigPathNode cnode = new ConfigPathNode(parent.Configuration, parent); cnode.Name = name; if (parent.GetType() == typeof(ConfigPathNode)) { ConfigPathNode pnode = (ConfigPathNode)parent; pnode.AddChildNode(cnode); } else if (parent.GetType() == typeof(ConfigElementListNode)) { ConfigElementListNode nodeList = (ConfigElementListNode)parent; nodeList.Add(cnode); } else { throw new ConfigurationException(String.Format("Invalid Stack State: Cannot add path node to parent. [parent={0}]", parent.GetType().FullName)); } nodeStack.Push(cnode); popStack = true; } } if (!processed) { if (elem.HasAttributes) { AbstractConfigNode pp = nodeStack.Peek(); if (pp.GetType() == typeof(ConfigPathNode)) { ConfigPathNode cp = (ConfigPathNode)pp; ConfigAttributesNode attrs = new ConfigAttributesNode(cp.Configuration, cp); cp.AddChildNode(attrs); foreach (XmlAttribute attr in elem.Attributes) { ConfigValueNode vn = new ConfigValueNode(attrs.Configuration, attrs); vn.Name = attr.Name; vn.SetValue(attr.Value); attrs.Add(vn); } } } if (elem.HasChildNodes) { foreach (XmlNode cnode in elem.ChildNodes) { if (cnode.NodeType == XmlNodeType.Element) { ParseBodyNode(cnode.Name, (XmlElement)cnode, nodeStack); } } } } if (popStack) { nodeStack.Pop(); } } }
/// <summary> /// Write a configuration node. /// </summary> /// <param name="writer">XML Writer</param> /// <param name="node">Node To write</param> /// <param name="settings">Configuration Settings.</param> private void WriteNode(XmlWriter writer, AbstractConfigNode node, ConfigurationSettings settings) { if (node.GetType() == typeof(ConfigPathNode)) { ConfigPathNode pnode = (ConfigPathNode)node; writer.WriteStartElement(node.Name); { ConfigAttributesNode attrs = pnode.GetAttributes(); if (attrs != null) { Dictionary <string, ConfigValueNode> values = attrs.GetValues(); if (values != null && values.Count > 0) { foreach (string key in values.Keys) { ConfigValueNode vn = values[key]; if (vn != null) { writer.WriteAttributeString(vn.Name, vn.GetValue()); } } } } Dictionary <string, AbstractConfigNode> nodes = pnode.GetChildren(); foreach (string key in nodes.Keys) { AbstractConfigNode cnode = nodes[key]; if (cnode.Name == settings.AttributesNodeName) { continue; } WriteNode(writer, cnode, settings); } } writer.WriteEndElement(); } else if (node.GetType() == typeof(ConfigValueNode)) { ConfigValueNode vn = (ConfigValueNode)node; writer.WriteStartElement(vn.Name); writer.WriteString(vn.GetValue()); writer.WriteEndElement(); } else if (node.GetType() == typeof(ConfigParametersNode) || node.GetType() == typeof(ConfigPropertiesNode)) { string name = null; if (node.GetType() == typeof(ConfigParametersNode)) { name = settings.ParametersNodeName; } else { name = settings.PropertiesNodeName; } ConfigKeyValueNode kvnode = (ConfigKeyValueNode)node; WriteKeyValueNode(writer, kvnode, name); } else if (node.GetType() == typeof(ConfigListValueNode)) { WriteListValueNode(writer, (ConfigListValueNode)node); } else if (node.GetType() == typeof(ConfigElementListNode)) { WriteListElementNode(writer, (ConfigElementListNode)node, settings); } else if (node.GetType() == typeof(ConfigIncludeNode)) { ConfigIncludeNode inode = (ConfigIncludeNode)node; WriteNode(writer, inode.Node, settings); } else if (typeof(ConfigResourceNode).IsAssignableFrom(node.GetType())) { ConfigResourceNode rnode = (ConfigResourceNode)node; WriteResourceNode(writer, rnode); } }